feat(storage): one guarded issue-lifecycle surface for the CLI and linked consumers (#5191)

Adds issueops.Lifecycle — Create, Update, Close, Reopen — reached from the storage handle via
store.IssueLifecycle(), implemented once and shared by the CLI and linked library consumers. Three backends
implement it and a shared conformance suite asserts them against one spec. The bd CLI's create, update,
close and reopen now route through it.

Fixes several defects that predate this change and became visible once the write paths were forced to
agree: swallowed metadata-edit failures, a claim applied before field validation, missing value validation
on title/priority/estimate, silently dropped create edges to missing targets, infra-typed creates landing in
the wrong table, a dropped SourceRepo, closed_by_session written but never read, and a compound update
writing twice.

Behavior changes needing release notes: create with an occupied explicit id now fails instead of silently
overwriting; a compound update is one atomic operation with one hook and one version commit; reparenting
replaces all parent edges; reopening something not closed reports nothing to do.
This commit is contained in:
Julian Knutsen 2026-07-31 11:26:38 -07:00 • committed by GitHub
commit b92442d1a3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
145 changed files with 17197 additions and 926 deletions

View file

@ -84,6 +84,12 @@ type UpdateIssueOptions = storage.UpdateIssueOptions
// name it without importing internal/storage.
type CommentPageCursor = storage.CommentPageCursor
// ErrUnsupported reports that an operation is unavailable for a storage
// backend — for example Storage.IssueLifecycle on a backend that cannot serve
// guarded issue mutations. Exported so consumers can match it with errors.As
// without importing internal/storage.
type ErrUnsupported = storage.ErrUnsupported
// RemoteStore provides dolt remote management and replication operations.
// Use type assertion on a Storage value to access these methods:
//

View file

@ -17,6 +17,7 @@ import (
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/validation"
"github.com/steveyegge/beads/issueops"
)
var closeCmd = &cobra.Command{
@ -81,6 +82,10 @@ the flags appear in the command line.`,
}
ctx := rootCtx
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if continueFlag && len(args) > 1 {
return HandleErrorRespectJSON("--continue only works when closing a single issue")
@ -145,11 +150,18 @@ the flags appear in the command line.`,
}
}
// Delegate the is_blocked guard to the engine (GH#962). CloseIssueChecked
// runs the guard and the close in ONE transaction, so there is no
// read-then-write TOCTOU window between the check and the close. --force
// bypasses the guard; ExpectedVersion is unused on this path.
res, err := activeStore.CloseIssueChecked(ctx, id, actor, storage.CloseIssueOptions{
// Delegate the is_blocked guard to the engine (GH#962). The close
// operation runs the guard and the close in ONE transaction, so there is
// no read-then-write TOCTOU window between the check and the close.
// --force bypasses the guard; ExpectedVersion is unused on this path.
ops, err := writeOps(activeStore)
if err != nil {
fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", id, err)
continue
}
res, err := ops.Close(opsCtx, issueops.CloseRequest{
Actor: actor,
IssueID: id,
Reason: reason,
Session: session,
Force: force,
@ -164,7 +176,7 @@ the flags appear in the command line.`,
}
continue
}
if res.Unchanged {
if !res.Changed {
// Already closed: an idempotent no-op on the step's stored state. The
// old CloseIssue path also returned nil here and still reported the
// (already-closed) issue, so keep OUTPUT parity via the shared display
@ -217,9 +229,15 @@ the flags appear in the command line.`,
firstSettledID = id
}
// Re-fetch for display. A real close and an idempotent no-op both report
// the closed issue here, matching the historical output shape.
closedIssue, _ := activeStore.GetIssue(ctx, id)
// The operation's own post-state snapshot is what gets reported. A
// real close and an idempotent no-op both report the closed issue
// here, matching the historical output shape. Dependency records are
// dropped from it because `bd close` has never printed them: the
// re-read this replaced did not hydrate them either.
closedIssue := res.Issue
if closedIssue != nil {
closedIssue.Dependencies = nil
}
if jsonOutput {
if closedIssue != nil {

View file

@ -56,7 +56,8 @@ func bdDepAdd(t *testing.T, bd, dir string, args ...string) {
}
}
// querySessionSQL queries closed_by_session via raw SQL since it's not in IssueSelectColumns.
// querySessionSQL queries closed_by_session via raw SQL. IssueSelectColumns
// selects and hydrates the column too; this reads the stored row directly.
func querySessionSQL(t *testing.T, beadsDir, id string) string {
t.Helper()
dataDir := filepath.Join(beadsDir, "embeddeddolt")

View file

@ -24,6 +24,7 @@ import (
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/validation"
"github.com/steveyegge/beads/issueops"
)
// validateCreateArgs runs as cobra's Args validation, which executes before
@ -551,6 +552,15 @@ var createCmd = &cobra.Command{
ctx := createCtx
// Resolve partial --deps targets the way `bd dep add` does, so a bare
// slug becomes a qualified id rather than a dangling edge, and an
// unknown target fails closed here instead of reaching the write.
resolvedDepSpecs, resolveErr := resolveDepSpecTargets(ctx, store, depSpecs)
if resolveErr != nil {
return HandleErrorRespectJSON("%v", resolveErr)
}
depSpecs = resolvedDepSpecs
// If a discovered-from dependency is present, inherit source_repo
// from the referenced parent issue. Reuse the already-parsed specs
// (not the raw --deps strings) so this can't drift from parseDepSpec's
@ -563,20 +573,52 @@ var createCmd = &cobra.Command{
// If error getting parent or parent has no source_repo, continue with default
}
edges := createDepEdges{parentID: parentID, specs: depSpecs, waitsFor: waitsForSpec}
if err := createIssueWithDeps(ctx, store, issue, actor, edges); err != nil {
ops, err := writeOps(store)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
// Label inheritance stays CLI-side (mergeCreateLabels above) because the
// dry-run preview needs it too; asking the facade to inherit as well
// would append the parent's labels a second time.
result, err := ops.Create(opsCtx, issueops.CreateRequest{
Actor: actor,
Issue: issue,
ParentID: parentID,
Dependencies: createDependencyRequests(depSpecs),
WaitsFor: waitsForRequest(waitsForSpec),
ForceIDPrefix: forceCreate,
})
if err != nil {
// RULING R1: an occupied --id is a refusal, not a silent full-row
// upsert reported as success.
if errors.Is(err, storage.ErrAlreadyExists) && explicitID != "" {
return HandleErrorRespectJSON("%s already exists; use bd update, or bd import for upsert semantics", explicitID)
}
return HandleErrorRespectJSON("%v", err)
}
// Every post-write read comes from the facade's result snapshot, never
// from the local struct: the facade clones its request, so the local
// struct still has no ID for an auto-minted create and no persisted
// timestamps. Dependencies and comments are dropped because `bd create`
// has never printed them.
created := result.Issue
created.Dependencies = nil
created.Comments = nil
edges := createDepEdges{parentID: parentID, specs: depSpecs, waitsFor: waitsForSpec}
if edges.empty() {
// Bare create: preserve the embedded-mode follow-up Dolt commit.
// The deps path commits inside its transaction instead.
shouldCommit, err := shouldCommitCreatePostWrites(issue, false)
shouldCommit, err := shouldCommitCreatePostWrites(created, false)
if err != nil {
return HandleError("dolt auto-commit failed: %v", err)
}
if shouldCommit {
commitMsg := fmt.Sprintf("bd: create %s", issue.ID)
commitMsg := fmt.Sprintf("bd: create %s", created.ID)
if err := store.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) {
WarnError("failed to commit: %v", err)
}
@ -586,7 +628,7 @@ var createCmd = &cobra.Command{
if repoPath != "." && targetStore != nil {
if err := commitPendingIfEmbedded(ctx, targetStore, actor, doltAutoCommitParams{
Command: "create",
IssueIDs: []string{issue.ID},
IssueIDs: []string{created.ID},
}); err != nil {
debug.Logf("warning: failed to commit routed repo: %v", err)
}
@ -599,20 +641,20 @@ var createCmd = &cobra.Command{
}
if jsonOutput {
if err := outputJSON(issue); err != nil {
if err := outputJSON(created); err != nil {
return err
}
} else if silent {
fmt.Println(issue.ID)
fmt.Println(created.ID)
} else {
debug.PrintNormal("%s Created issue: %s\n", ui.RenderPass("✓"), formatFeedbackID(issue.ID, issue.Title))
debug.PrintNormal(" Priority: P%d\n", issue.Priority)
debug.PrintNormal(" Status: %s\n", issue.Status)
debug.PrintNormal("%s Created issue: %s\n", ui.RenderPass("✓"), formatFeedbackID(created.ID, created.Title))
debug.PrintNormal(" Priority: P%d\n", created.Priority)
debug.PrintNormal(" Status: %s\n", created.Status)
maybeShowTip(store)
}
SetLastTouchedID(issue.ID)
SetLastTouchedID(created.ID)
return nil
},
}
@ -783,17 +825,7 @@ func renderCreateDryRunPreview(issue *types.Issue, labels, deps []string) {
}
func shouldCommitCreatePostWrites(_ *types.Issue, _ bool) (bool, error) {
if isEmbeddedMode() {
if strings.TrimSpace(doltAutoCommit) == "" {
return true, nil
}
mode, err := getDoltAutoCommitMode()
if err != nil {
return false, err
}
return mode == doltAutoCommitOn, nil
}
return false, nil
return embeddedWritesCommitNow()
}
func createDepsAcceptedTypeList() string {

View file

@ -10,8 +10,38 @@ import (
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/issueops"
)
// createDependencyRequests translates parsed --deps specs into the create
// request's edge list. The specs are already alias-normalized and deduped by
// parseDepSpecs; the facade rejects the exact duplicates that dedupe removes.
func createDependencyRequests(specs []domain.DependencySpec) []issueops.CreateDependency {
if len(specs) == 0 {
return nil
}
requests := make([]issueops.CreateDependency, 0, len(specs))
for _, spec := range specs {
requests = append(requests, issueops.CreateDependency{
TargetID: spec.TargetID,
Type: spec.Type,
Reverse: spec.SwapDirection,
Metadata: spec.Metadata,
ThreadID: spec.ThreadID,
})
}
return requests
}
// waitsForRequest translates the parsed --waits-for spec into the create
// request's spawner gate.
func waitsForRequest(spec *domain.WaitsForSpec) *issueops.WaitsFor {
if spec == nil {
return nil
}
return &issueops.WaitsFor{SpawnerID: spec.SpawnerID, Gate: spec.Gate}
}
func parseDepSpecs(deps []string) ([]domain.DependencySpec, error) {
// deps arrives already comma-split: cobra's StringSlice flag CSV-decodes
// each --deps value, so re-splitting on "," here would double-decode a

View file

@ -46,6 +46,43 @@ func transactHonoringAutoCommit(ctx context.Context, s storage.DoltStorage, comm
return err
}
// embeddedWritesCommitNow reports whether an embedded-mode CLI write should
// create its Dolt version commit now. Batch and off defer it to an explicit
// commit point (bd dolt commit); an unset value is the embedded default, which
// PersistentPreRun resolves to "on". Server mode is never the CLI's commit to
// make — the storage layer versions those writes itself.
func embeddedWritesCommitNow() (bool, error) {
if !isEmbeddedMode() {
return false, nil
}
if strings.TrimSpace(doltAutoCommit) == "" {
return true, nil
}
mode, err := getDoltAutoCommitMode()
if err != nil {
return false, err
}
return mode == doltAutoCommitOn, nil
}
// issueOpsContext applies command auto-commit policy to the context a write verb
// hands the issue-operations facade. The facade creates its Dolt version commit
// inside the storage layer, so batch mode cannot blank a commit message the way
// transactHonoringAutoCommit does — it has to say so on the context instead.
func issueOpsContext(ctx context.Context) (context.Context, error) {
if !isEmbeddedMode() {
return ctx, nil
}
commitNow, err := embeddedWritesCommitNow()
if err != nil {
return nil, err
}
if commitNow {
return ctx, nil
}
return issueops.WithDeferredVersionCommit(ctx), nil
}
type doltAutoCommitParams struct {
// Command is the top-level bd command name (e.g., "create", "update").
Command string

View file

@ -107,12 +107,9 @@ func runDuplicate(cmd *cobra.Command, args []string) error {
return fmt.Errorf("failed to add duplicate link: %w", err)
}
// Close the duplicate issue
closedStatus := string(types.StatusClosed)
updates := map[string]interface{}{
"status": closedStatus,
}
if err := store.UpdateIssue(ctx, duplicateID, updates, actor); err != nil {
// Close the duplicate issue through the lifecycle operation so it records
// the complete closure state.
if err := store.CloseIssue(ctx, duplicateID, "", actor, ""); err != nil {
return fmt.Errorf("failed to close duplicate: %w", err)
}
@ -180,12 +177,9 @@ func runSupersede(cmd *cobra.Command, args []string) error {
return fmt.Errorf("failed to add supersede link: %w", err)
}
// Close the superseded issue
closedStatus := string(types.StatusClosed)
updates := map[string]interface{}{
"status": closedStatus,
}
if err := store.UpdateIssue(ctx, oldID, updates, actor); err != nil {
// Close the superseded issue through the lifecycle operation so it records
// the complete closure state.
if err := store.CloseIssue(ctx, oldID, "", actor, ""); err != nil {
return fmt.Errorf("failed to close superseded issue: %w", err)
}

View file

@ -75,6 +75,9 @@ func TestEmbeddedDuplicate(t *testing.T) {
if issue.Status != "closed" {
t.Errorf("expected status=closed, got %s", issue.Status)
}
if issue.ClosedAt == nil {
t.Error("expected duplicate close to set closed_at")
}
})
// ===== Creates dependency link =====

View file

@ -0,0 +1,27 @@
package main
import (
"github.com/steveyegge/beads"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/issueops"
)
// newIssueOperations asks a store for its guarded issue-lifecycle surface.
// It is a variable purely as a test seam: the write-verb parity tests
// substitute a counting facade so "which operations did this command perform"
// stays observable. Production always calls the store's own accessor.
var newIssueOperations = func(st beads.Storage) (issueops.Lifecycle, error) {
return st.IssueLifecycle()
}
// writeOps returns the issue-lifecycle surface for st, the store a write verb
// is actually writing to.
//
// Callers build it per write site — the global store, a RoutedResult's store,
// or a --repo target — rather than once per command, because each store hands
// back a lifecycle carrying its own decorator stack. Building it over the
// store that owns the issue is what keeps a routed write hookless and a local
// write hooked, exactly as the direct store calls did.
func writeOps(st storage.DoltStorage) (issueops.Lifecycle, error) {
return newIssueOperations(st)
}

View file

@ -18,8 +18,8 @@ import (
"github.com/steveyegge/beads/internal/types"
)
// bd-206: Test updating open issue to closed preserves closed_at
func TestImportOpenToClosedTransition(t *testing.T) {
// TestCloseIssueSetsClosedAt verifies the dedicated close operation owns its lifecycle metadata.
func TestCloseIssueSetsClosedAt(t *testing.T) {
tmpDir := t.TempDir()
dbPath := filepath.Join(tmpDir, "test.db")
@ -45,13 +45,9 @@ func TestImportOpenToClosedTransition(t *testing.T) {
t.Fatalf("Failed to create open issue: %v", err)
}
// Step 2: Update via UpdateIssue with closed status (closed_at managed automatically)
updates := map[string]interface{}{
"status": types.StatusClosed,
}
if err := testStore.UpdateIssue(ctx, "bd-transition-1", updates, "test"); err != nil {
t.Fatalf("Update failed: %v", err)
// Step 2: Lifecycle transitions use the dedicated close operation.
if err := testStore.CloseIssue(ctx, "bd-transition-1", "", "test", ""); err != nil {
t.Fatalf("CloseIssue failed: %v", err)
}
// Step 3: Verify the issue is now closed with correct closed_at
@ -69,8 +65,8 @@ func TestImportOpenToClosedTransition(t *testing.T) {
}
}
// bd-206: Test updating closed issue to open clears closed_at
func TestImportClosedToOpenTransition(t *testing.T) {
// TestReopenIssueClearsClosedAt verifies the dedicated reopen operation clears lifecycle metadata.
func TestReopenIssueClearsClosedAt(t *testing.T) {
tmpDir := t.TempDir()
dbPath := filepath.Join(tmpDir, "test.db")
@ -97,13 +93,9 @@ func TestImportClosedToOpenTransition(t *testing.T) {
t.Fatalf("Failed to create closed issue: %v", err)
}
// Step 2: Update via UpdateIssue with open status (closed_at managed automatically)
updates := map[string]interface{}{
"status": types.StatusOpen,
}
if err := testStore.UpdateIssue(ctx, "bd-transition-2", updates, "test"); err != nil {
t.Fatalf("Update failed: %v", err)
// Step 2: Lifecycle transitions use the dedicated reopen operation.
if err := testStore.ReopenIssue(ctx, "bd-transition-2", "", "test"); err != nil {
t.Fatalf("ReopenIssue failed: %v", err)
}
// Step 3: Verify the issue is now open with null closed_at

View file

@ -143,7 +143,7 @@ func TestMessagingSuite(t *testing.T) {
t.Fatalf("AddDep(duplicates): %v", err)
}
// Close the duplicate
if err := testStore.UpdateIssue(ctx, dup.ID, map[string]interface{}{"status": types.StatusClosed}, "test"); err != nil {
if err := testStore.CloseIssue(ctx, dup.ID, "duplicate", "test", ""); err != nil {
t.Fatalf("Close dup: %v", err)
}
@ -174,10 +174,8 @@ func TestMessagingSuite(t *testing.T) {
}
// Close (ack)
if err := testStore.UpdateIssue(ctx, lifecycleMsg.ID, map[string]interface{}{
"status": types.StatusClosed,
}, "test"); err != nil {
t.Fatalf("UpdateIssue (close): %v", err)
if err := testStore.CloseIssue(ctx, lifecycleMsg.ID, "acknowledged", "test", ""); err != nil {
t.Fatalf("CloseIssue (ack): %v", err)
}
acked, err := testStore.GetIssue(ctx, lifecycleMsg.ID)
if err != nil {

View file

@ -9,6 +9,7 @@ import (
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/issueops"
)
var reopenCmd = &cobra.Command{
@ -36,6 +37,10 @@ This is more explicit than 'bd update --status open' and emits a Reopened event.
reason, _ := cmd.Flags().GetString("reason")
ctx := rootCtx
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
reopenedIssues := []*types.Issue{}
hasError := false
@ -61,17 +66,41 @@ This is more explicit than 'bd update --status open' and emits a Reopened event.
result.Close()
continue
}
if err := issueStore.ReopenIssue(ctx, fullID, reason, actor); err != nil {
ops, err := writeOps(issueStore)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reopening %s: %v\n", fullID, err)
hasError = true
result.Close()
continue
}
reopened, err := ops.Reopen(opsCtx, issueops.ReopenRequest{
Actor: actor,
IssueID: fullID,
Reason: reason,
})
if err != nil {
fmt.Fprintf(os.Stderr, "Error reopening %s: %v\n", fullID, err)
hasError = true
result.Close()
continue
}
if !reopened.Changed {
// RULING R4: only literal closed and configured done statuses
// reopen. Anything else was never closed, so there is nothing to
// report as reopened, nothing to commit, and no hook to fire —
// the same "nothing to do" shape as the already-open skip above.
fmt.Fprintf(os.Stderr, "%s is not closed (status: %s); nothing to do\n", fullID, reopenStatusOf(reopened.Issue, issue))
result.Close()
continue
}
mutatedStores[issueStore] = append(mutatedStores[issueStore], fullID)
pendingCloseResults = append(pendingCloseResults, result)
if jsonOutput {
updated, _ := issueStore.GetIssue(ctx, fullID)
if updated != nil {
// The operation's own post-state snapshot replaces the re-read.
// Dependency records are dropped because `bd reopen` has never
// printed them.
if updated := reopened.Issue; updated != nil {
updated.Dependencies = nil
reopenedIssues = append(reopenedIssues, updated)
}
} else {
@ -111,6 +140,18 @@ This is more explicit than 'bd update --status open' and emits a Reopened event.
},
}
// reopenStatusOf reports the status a no-op reopen left in place, preferring
// the operation's post-state snapshot over the pre-read it was based on.
func reopenStatusOf(post, pre *types.Issue) types.Status {
if post != nil {
return post.Status
}
if pre != nil {
return pre.Status
}
return ""
}
func init() {
reopenCmd.Flags().StringP("reason", "r", "", "Reason for reopening")
reopenCmd.ValidArgsFunction = issueIDCompletion

View file

@ -38,10 +38,9 @@ func (h *reopenTestHelper) closeIssue(issueID, reason string) {
}
func (h *reopenTestHelper) reopenIssue(issueID string) {
updates := map[string]interface{}{
"status": string(types.StatusOpen),
}
if err := h.s.UpdateIssue(h.ctx, issueID, updates, "test-user"); err != nil {
// Reopen through the lifecycle operation so the fixture carries the full
// closure teardown, mirroring closeIssue above.
if err := h.s.ReopenIssue(h.ctx, issueID, "", "test-user"); err != nil {
h.t.Fatalf("Failed to reopen issue: %v", err)
}
}

View file

@ -74,39 +74,3 @@ func uowClaimPoolAliases(ctx context.Context, uw uow.UnitOfWork) func() []string
return issueops.ParseClaimPools(raw)
}
}
func applyLabelUpdates(ctx context.Context, st storage.DoltStorage, issueID, actor string, setLabels, addLabels, removeLabels []string) error {
// Set labels (replaces all existing labels)
if len(setLabels) > 0 {
currentLabels, err := st.GetLabels(ctx, issueID)
if err != nil {
return err
}
for _, label := range currentLabels {
if err := st.RemoveLabel(ctx, issueID, label, actor); err != nil {
return err
}
}
for _, label := range setLabels {
if err := st.AddLabel(ctx, issueID, label, actor); err != nil {
return err
}
}
}
// Add labels
for _, label := range addLabels {
if err := st.AddLabel(ctx, issueID, label, actor); err != nil {
return err
}
}
// Remove labels
for _, label := range removeLabels {
if err := st.RemoveLabel(ctx, issueID, label, actor); err != nil {
return err
}
}
return nil
}

View file

@ -56,62 +56,6 @@ func TestValidateIssueClosable(t *testing.T) {
}
}
func TestApplyLabelUpdates_SetAddRemove(t *testing.T) {
ctx := context.Background()
st := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test")
issue := &types.Issue{Title: "x", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := st.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
_ = st.AddLabel(ctx, issue.ID, "old1", "tester")
_ = st.AddLabel(ctx, issue.ID, "old2", "tester")
if err := applyLabelUpdates(ctx, st, issue.ID, "tester", []string{"a", "b"}, []string{"b", "c"}, []string{"a"}); err != nil {
t.Fatalf("applyLabelUpdates: %v", err)
}
labels, _ := st.GetLabels(ctx, issue.ID)
if len(labels) != 2 {
t.Fatalf("expected 2 labels, got %v", labels)
}
// Order is not guaranteed.
foundB := false
foundC := false
for _, l := range labels {
if l == "b" {
foundB = true
}
if l == "c" {
foundC = true
}
if l == "old1" || l == "old2" || l == "a" {
t.Fatalf("unexpected label %q in %v", l, labels)
}
}
if !foundB || !foundC {
t.Fatalf("expected labels b and c, got %v", labels)
}
}
func TestApplyLabelUpdates_AddRemoveOnly(t *testing.T) {
ctx := context.Background()
st := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test")
issue := &types.Issue{Title: "x", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := st.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
_ = st.AddLabel(ctx, issue.ID, "a", "tester")
if err := applyLabelUpdates(ctx, st, issue.ID, "tester", nil, []string{"b"}, []string{"a"}); err != nil {
t.Fatalf("applyLabelUpdates: %v", err)
}
labels, _ := st.GetLabels(ctx, issue.ID)
if len(labels) != 1 || labels[0] != "b" {
t.Fatalf("expected [b], got %v", labels)
}
}
func TestFindRepliesToAndReplies_WorksWithDoltStorage(t *testing.T) {
ctx := context.Background()
st := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test")

View file

@ -75,6 +75,9 @@ func TestEmbeddedSupersede(t *testing.T) {
if issue.Status != "closed" {
t.Errorf("expected status=closed, got %s", issue.Status)
}
if issue.ClosedAt == nil {
t.Error("expected supersede close to set closed_at")
}
})
// ===== Creates supersedes link =====

View file

@ -13,12 +13,13 @@ import (
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/issueops"
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/timeparsing"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/internal/validation"
"github.com/steveyegge/beads/issueops"
)
var updateCmd = &cobra.Command{
@ -145,7 +146,7 @@ pointless).`,
}
if cmd.Flags().Changed("append-notes") {
appendNotes, _ := cmd.Flags().GetString("append-notes")
updates[issueops.OpAppendNotes] = appendNotes
updates[storageissueops.OpAppendNotes] = appendNotes
}
if cmd.Flags().Changed("acceptance") || cmd.Flags().Changed("acceptance-criteria") {
var acceptanceCriteria string
@ -302,7 +303,7 @@ pointless).`,
// Passed as a merge OPERATION, not a pre-merged value: the storage
// layer re-reads and merges inside the mutation transaction so a
// concurrent writer's keys survive (lost-update fix).
updates[issueops.OpMergeMetadata] = json.RawMessage(metadataJSON)
updates[storageissueops.OpMergeMetadata] = json.RawMessage(metadataJSON)
}
// Incremental metadata edits (GH#1406)
@ -312,10 +313,10 @@ pointless).`,
return HandleErrorRespectJSON("cannot combine --metadata with --set-metadata or --unset-metadata")
}
if len(setMetadataFlags) > 0 {
updates[issueops.OpSetMetadata] = setMetadataFlags
updates[storageissueops.OpSetMetadata] = setMetadataFlags
}
if len(unsetMetadataFlags) > 0 {
updates[issueops.OpUnsetMetadata] = unsetMetadataFlags
updates[storageissueops.OpUnsetMetadata] = unsetMetadataFlags
}
// Get claim flag
@ -337,8 +338,24 @@ pointless).`,
if err != nil {
return err
}
var expectedStatus *issueops.Status
if ifStatus != nil {
expected := issueops.Status(*ifStatus)
expectedStatus = &expected
}
// One typed patch for the whole batch. The flag-derived map is still
// the source (the guard rules and the notes-overwrite warning read it);
// this reshapes it once instead of once per issue.
basePatch, err := buildUpdatePatch(updates)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
ctx := rootCtx
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
updatedIssues := []*types.Issue{}
var firstUpdatedID string // Track first successful update for last-touched
@ -424,166 +441,73 @@ pointless).`,
}
}
// Handle claim operation atomically using compare-and-swap semantics
if claimFlag {
if err := issueStore.ClaimIssue(ctx, result.ResolvedID, actor); err != nil {
fmt.Fprintf(os.Stderr, "Error claiming %s: %v\n", id, err)
recordFailure(id, fmt.Sprintf("claiming issue: %v", err))
closeIfUnmutated(result)
continue
}
trackMutation(result)
}
// Apply regular field updates if any. Metadata edits (--metadata,
// --set-metadata, --unset-metadata) and --append-notes pass through
// as merge OPERATIONS: the storage layer resolves them against the
// row re-read inside the mutation transaction. Merging here against
// the `issue` snapshot (read in an earlier transaction) silently
// erased concurrent writers' keys — both processes exited 0, one
// process's committed write vanished.
regularUpdates := make(map[string]interface{})
for k, v := range updates {
if k != "add_labels" && k != "remove_labels" && k != "set_labels" && k != "parent" {
regularUpdates[k] = v
}
}
// One atomic operation carries the claim, every field edit, the
// label edits, the metadata edits and the reparent. Metadata edits
// (--metadata, --set-metadata, --unset-metadata) and --append-notes
// still resolve against the row re-read inside the mutation
// transaction: merging against the `issue` snapshot (read in an
// earlier transaction) silently erased concurrent writers' keys —
// both processes exited 0, one process's committed write vanished.
patch := basePatch
// GH#3233: --defer="" restores ready visibility only if the issue
// was actually deferred. Other statuses (blocked, in_progress, …)
// shouldn't be clobbered just because defer_until was stale.
if clearDeferStatus && issue.Status == types.StatusDeferred {
regularUpdates["status"] = string(types.StatusOpen)
patch.Status = issueops.Field[issueops.Status]{Set: true, Value: types.StatusOpen}
}
notesOverwritten := replacesExistingNotes(issue.Notes, updates)
if len(regularUpdates) > 0 {
// With guards present, route through the checked (CAS) path: a
// stale assignee/status refuses atomically with a typed
// mismatch error and MUST surface as a non-zero exit — never
// collapse it to success (finding #10).
var updateErr error
if ifAssignee != nil || ifStatus != nil {
updateErr = issueStore.UpdateIssueChecked(ctx, result.ResolvedID, regularUpdates, actor,
storage.UpdateIssueOptions{ExpectedAssignee: ifAssignee, ExpectedStatus: ifStatus})
} else {
updateErr = issueStore.UpdateIssue(ctx, result.ResolvedID, regularUpdates, actor)
}
if updateErr != nil {
fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, updateErr)
failures = append(failures, updateIDFailure{
ID: id,
Error: fmt.Sprintf("updating issue: %v", updateErr),
GuardMismatch: isGuardMismatch(updateErr),
})
closeIfUnmutated(result)
continue
}
trackMutation(result)
if notesOverwritten {
notesOverwriteWarnings[issueStore] = append(notesOverwriteWarnings[issueStore], id)
}
// Audit log key field changes (survives Dolt GC flatten)
if s, ok := regularUpdates["status"].(string); ok {
audit.LogFieldChange(result.ResolvedID, "status", string(issue.Status), s, actor, "")
}
if a, ok := regularUpdates["assignee"].(string); ok {
audit.LogFieldChange(result.ResolvedID, "assignee", issue.Assignee, a, actor, "")
}
if p, ok := regularUpdates["priority"].(int); ok {
audit.LogFieldChange(result.ResolvedID, "priority", fmt.Sprintf("%d", issue.Priority), fmt.Sprintf("%d", p), actor, "")
}
ops, err := writeOps(issueStore)
if err != nil {
fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err)
recordFailure(id, fmt.Sprintf("updating issue: %v", err))
closeIfUnmutated(result)
continue
}
// Guards ride the operation itself: a stale assignee/status refuses
// atomically with a typed mismatch error and MUST surface as a
// non-zero exit — never collapse it to success (finding #10).
updateResult, updateErr := ops.Update(opsCtx, issueops.UpdateRequest{
Actor: actor,
IssueID: result.ResolvedID,
Patch: patch,
Claim: claimFlag,
ForceAssigneeTransfer: forceFlag,
ExpectedAssignee: ifAssignee,
ExpectedStatus: expectedStatus,
})
if updateErr != nil {
fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, updateErr)
failures = append(failures, updateIDFailure{
ID: id,
Error: fmt.Sprintf("updating issue: %v", updateErr),
GuardMismatch: isGuardMismatch(updateErr),
})
closeIfUnmutated(result)
continue
}
updatedIssue := updateResult.Issue
trackMutation(result)
if notesOverwritten {
notesOverwriteWarnings[issueStore] = append(notesOverwriteWarnings[issueStore], id)
}
// Audit log key field changes (survives Dolt GC flatten)
if patch.Status.Set {
audit.LogFieldChange(result.ResolvedID, "status", string(issue.Status), string(patch.Status.Value), actor, "")
}
if patch.Assignee.Set {
audit.LogFieldChange(result.ResolvedID, "assignee", issue.Assignee, patch.Assignee.Value, actor, "")
}
if patch.Priority.Set {
audit.LogFieldChange(result.ResolvedID, "priority", fmt.Sprintf("%d", issue.Priority), fmt.Sprintf("%d", patch.Priority.Value), actor, "")
}
// Handle label operations
var setLabels, addLabels, removeLabels []string
if v, ok := updates["set_labels"].([]string); ok {
setLabels = v
// The operation's own post-state snapshot replaces the re-read.
// Dependency records are dropped from it because `bd update` has
// never printed them: GetIssue did not hydrate them either.
if updatedIssue != nil {
updatedIssue.Dependencies = nil
}
if v, ok := updates["add_labels"].([]string); ok {
addLabels = v
}
if v, ok := updates["remove_labels"].([]string); ok {
removeLabels = v
}
if len(setLabels) > 0 || len(addLabels) > 0 || len(removeLabels) > 0 {
if err := applyLabelUpdates(ctx, issueStore, result.ResolvedID, actor, setLabels, addLabels, removeLabels); err != nil {
fmt.Fprintf(os.Stderr, "Error updating labels for %s: %v\n", id, err)
recordFailure(id, fmt.Sprintf("updating labels: %v", err))
closeIfUnmutated(result)
continue
}
trackMutation(result)
}
// Handle parent reparenting
if newParent, ok := updates["parent"].(string); ok {
// Validate new parent exists (unless empty string to remove parent)
if newParent != "" {
parentIssue, err := issueStore.GetIssue(ctx, newParent)
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting parent %s: %v\n", newParent, err)
recordFailure(id, fmt.Sprintf("getting parent %s: %v", newParent, err))
closeIfUnmutated(result)
continue
}
if parentIssue == nil {
fmt.Fprintf(os.Stderr, "Error: parent issue %s not found\n", newParent)
recordFailure(id, fmt.Sprintf("parent issue %s not found", newParent))
closeIfUnmutated(result)
continue
}
}
// Find and remove existing parent-child dependency
deps, err := issueStore.GetDependencyRecords(ctx, result.ResolvedID)
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting dependencies for %s: %v\n", id, err)
recordFailure(id, fmt.Sprintf("getting dependencies: %v", err))
closeIfUnmutated(result)
continue
}
oldParentRemoveFailed := false
for _, dep := range deps {
if dep.Type == types.DepParentChild {
if err := issueStore.RemoveDependency(ctx, result.ResolvedID, dep.DependsOnID, actor); err != nil {
// Reparenting removes the old parent edge before adding
// the new one; if removal fails, adding the new edge would
// leave the issue with two parents. Record the failed ID
// and stop so it surfaces in the nonzero-exit report
// instead of being silently counted as a success.
fmt.Fprintf(os.Stderr, "Error removing old parent dependency: %v\n", err)
recordFailure(id, fmt.Sprintf("removing old parent dependency: %v", err))
oldParentRemoveFailed = true
} else {
trackMutation(result)
}
break
}
}
if oldParentRemoveFailed {
closeIfUnmutated(result)
continue
}
// Add new parent-child dependency (if not removing parent)
if newParent != "" {
newDep := &types.Dependency{
IssueID: result.ResolvedID,
DependsOnID: newParent,
Type: types.DepParentChild,
}
if err := issueStore.AddDependency(ctx, newDep, actor); err != nil {
fmt.Fprintf(os.Stderr, "Error adding parent dependency: %v\n", err)
recordFailure(id, fmt.Sprintf("adding parent dependency: %v", err))
closeIfUnmutated(result)
continue
}
trackMutation(result)
}
}
// Re-fetch for display
updatedIssue, _ := issueStore.GetIssue(ctx, result.ResolvedID)
updateTitle := ""
if updatedIssue != nil {
updateTitle = updatedIssue.Title
@ -645,6 +569,167 @@ pointless).`,
},
}
// setField marks a patch field as supplied, including when the value is a zero
// value the caller meant to write.
func setField[T any](value T) issueops.Field[T] {
return issueops.Field[T]{Set: true, Value: value}
}
// buildUpdatePatch reshapes the flag-derived update map into the facade's typed
// patch. Every key it handles is a key the flag parsing above wrote, so an
// unrecognized one is a bug in this file rather than user input.
func buildUpdatePatch(updates map[string]interface{}) (issueops.IssuePatch, error) {
var patch issueops.IssuePatch
var wisp, noHistory *bool
for key, value := range updates {
var ok bool
switch key {
case "title":
patch.Title, ok = stringField(value)
case "description":
patch.Description, ok = stringField(value)
case "design":
patch.Design, ok = stringField(value)
case "acceptance_criteria":
patch.AcceptanceCriteria, ok = stringField(value)
case "notes":
patch.Notes, ok = stringField(value)
case storageissueops.OpAppendNotes:
patch.AppendNotes, ok = stringField(value)
case "spec_id":
patch.SpecID, ok = stringField(value)
case "await_id":
patch.AwaitID, ok = stringField(value)
case "closed_by_session":
patch.ClosedBySession, ok = stringField(value)
case "assignee":
patch.Assignee, ok = stringField(value)
case "parent":
patch.ParentID, ok = stringField(value)
case "status":
var status issueops.Field[string]
if status, ok = stringField(value); ok {
patch.Status = setField(issueops.Status(status.Value))
}
case "issue_type":
var issueType issueops.Field[string]
if issueType, ok = stringField(value); ok {
patch.IssueType = setField(issueops.IssueType(issueType.Value))
}
case "priority":
var priority int
if priority, ok = value.(int); ok {
patch.Priority = setField(priority)
}
case "estimated_minutes":
var estimate int
if estimate, ok = value.(int); ok {
patch.EstimatedMinutes = setField(&estimate)
}
case "external_ref":
ok = true
if value == nil {
patch.ExternalRef = setField[*string](nil)
} else if ref, isString := value.(string); isString {
patch.ExternalRef = setField(&ref)
} else {
ok = false
}
case "due_at":
patch.DueAt, ok = optionalTimeField(value)
case "defer_until":
patch.DeferUntil, ok = optionalTimeField(value)
case "add_labels":
patch.Labels.Add, ok = value.([]string)
case "remove_labels":
patch.Labels.Remove, ok = value.([]string)
case "set_labels":
var labels []string
if labels, ok = value.([]string); ok {
patch.Labels.Replace = setField(labels)
}
case storageissueops.OpMergeMetadata:
var merge json.RawMessage
if merge, ok = value.(json.RawMessage); ok {
patch.Metadata.Merge = setField(merge)
}
case storageissueops.OpSetMetadata:
var flags []string
if flags, ok = value.([]string); ok {
set, err := parseSetMetadataFlags(flags)
if err != nil {
return issueops.IssuePatch{}, err
}
patch.Metadata.Set = set
}
case storageissueops.OpUnsetMetadata:
patch.Metadata.Unset, ok = value.([]string)
case "wisp":
var flag bool
if flag, ok = value.(bool); ok {
wisp = &flag
}
case "no_history":
var flag bool
if flag, ok = value.(bool); ok {
noHistory = &flag
}
default:
return issueops.IssuePatch{}, fmt.Errorf("unsupported update field %q", key)
}
if !ok {
return issueops.IssuePatch{}, fmt.Errorf("unsupported value %T for update field %q", value, key)
}
}
// --ephemeral/--persistent/--no-history/--history select one complete
// persistence state. The flag parsing already rejects the contradictory
// pairs; the remaining combinations resolve most-specific-first, which
// reproduces the column pairs the old two-boolean write produced.
switch {
case wisp != nil && *wisp:
patch.Persistence = setField(issueops.PersistenceModeEphemeral)
case noHistory != nil && *noHistory:
patch.Persistence = setField(issueops.PersistenceModeNoHistory)
case wisp != nil || noHistory != nil:
patch.Persistence = setField(issueops.PersistenceModePersistent)
}
return patch, nil
}
func stringField(value any) (issueops.Field[string], bool) {
text, ok := value.(string)
if !ok {
return issueops.Field[string]{}, false
}
return setField(text), true
}
func optionalTimeField(value any) (issueops.Field[*time.Time], bool) {
if value == nil {
return setField[*time.Time](nil), true
}
at, ok := value.(time.Time)
if !ok {
return issueops.Field[*time.Time]{}, false
}
return setField(&at), true
}
// parseSetMetadataFlags splits --set-metadata key=value pairs, matching
// storage.ApplyMetadataEdits' parsing so the CLI contract is unchanged. Values
// are always stored as JSON strings (GH#4146).
func parseSetMetadataFlags(flags []string) (map[string]json.RawMessage, error) {
set := make(map[string]json.RawMessage, len(flags))
for _, flag := range flags {
key, value, ok := strings.Cut(flag, "=")
if !ok || key == "" {
return nil, fmt.Errorf("invalid --set-metadata: expected key=value, got %q", flag)
}
set[key] = storage.MetadataEditValue(value)
}
return set, nil
}
func replacesExistingNotes(existing string, fields map[string]any) bool {
newNotes, replacing := fields["notes"].(string)
return replacing && existing != "" && newNotes != existing

View file

@ -872,8 +872,8 @@ func TestEmbeddedUpdate(t *testing.T) {
issue := bdCreate(t, bd, dir, "Session test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--status", "closed", "--session", "sess-123")
got := bdShow(t, bd, dir, issue.ID)
// Verify the issue is closed (closed_by_session is stored but not
// included in IssueSelectColumns, so we verify status + closed_at).
// closed_by_session is selected by IssueSelectColumns and hydrated onto
// the issue; here we just verify the close itself landed.
if got.Status != types.StatusClosed {
t.Errorf("expected status closed, got %s", got.Status)
}

File diff suppressed because it is too large Load diff

2
go.mod
View file

@ -137,7 +137,7 @@ require (
github.com/dolthub/flatbuffers/v23 v23.3.3-dh.2 // indirect
github.com/dolthub/fslock v0.0.5 // indirect
github.com/dolthub/go-icu-regex v0.0.0-20260610153742-72563bc7ca83 // indirect
github.com/dolthub/go-mysql-server v0.20.1-0.20260713210757-6d01d00bbbf3 // indirect
github.com/dolthub/go-mysql-server v0.20.1-0.20260713210757-6d01d00bbbf3
github.com/dolthub/gozstd v0.0.0-20240423170813-23a2903bca63 // indirect
github.com/dolthub/ishell v0.0.0-20260414231531-5f031e3e9037 // indirect
github.com/dolthub/jsonpath v0.0.2-0.20240227200619-19675ab05c71 // indirect

View file

@ -16,6 +16,7 @@ import (
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/tracker"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
func TestRegistered(t *testing.T) {
@ -629,6 +630,9 @@ func (s *configStore) GetAllConfig(_ context.Context) (map[string]string, error)
}
// Storage interface stubs — not exercised by Init().
func (s *configStore) IssueLifecycle() (issueops.Lifecycle, error) {
return nil, &storage.ErrUnsupported{Op: "IssueLifecycle", Backend: "jira-config-stub"}
}
func (s *configStore) SetConfig(_ context.Context, _, _ string) error { return nil }
func (s *configStore) SetLocalMetadata(_ context.Context, _, _ string) error { return nil }
func (s *configStore) GetLocalMetadata(_ context.Context, _ string) (string, error) {

View file

@ -18,6 +18,9 @@ const (
// BatchCreateOptions contains options for batch issue creation.
// This is a backend-agnostic type that can be used by any storage implementation.
type BatchCreateOptions struct {
// CreateOnly uses strict insert semantics after the caller has reserved the
// issue ID. It is for guarded public creates; import behavior is unchanged.
CreateOnly bool
// OrphanHandling specifies how to handle issues with missing parent references
OrphanHandling OrphanHandling
// SkipPrefixValidation skips prefix validation for existing IDs (used during import)

View file

@ -32,7 +32,7 @@ func auditCountEventType(events []*types.Event, want types.EventType) int {
func RunAudit_issue_lifecycle(t *testing.T, f Factory) {
t.Helper()
t.Run("CloseIdempotentKeepsFirstReason", func(t *testing.T) { testAuditCloseIdempotentKeepsFirstReason(t, f) })
t.Run("ReopenOnOpenMintsEvent", func(t *testing.T) { testAuditReopenOnOpenMintsEvent(t, f) })
t.Run("ReopenEventSemantics", func(t *testing.T) { testAuditReopenEventSemantics(t, f) })
t.Run("ReopenNotFoundIsSentinel", func(t *testing.T) { testAuditReopenNotFoundIsSentinel(t, f) })
t.Run("DeleteIssuesBatchModes", func(t *testing.T) { testAuditDeleteIssuesBatchModes(t, f) })
t.Run("DeleteIssuesDryRunCounts", func(t *testing.T) { testAuditDeleteIssuesDryRunCounts(t, f) })
@ -80,22 +80,29 @@ func testAuditCloseIdempotentKeepsFirstReason(t *testing.T, f Factory) {
}
}
// Reopening an already-open issue mints a status_changed event on the reference
// (ReopenIssue -> UpdateIssue always records an event).
func testAuditReopenOnOpenMintsEvent(t *testing.T, f Factory) {
// Reopening an already-open issue is a strict no-op. Reopening the same issue
// after a genuine close mints exactly one reopened event.
func testAuditReopenEventSemantics(t *testing.T, f Factory) {
s := f(t)
must(t, s.CreateIssue(ctx(), withDefaults(&types.Issue{ID: "ro-1", Title: "T", Status: types.StatusOpen}), "a"))
before, err := s.GetEvents(ctx(), "ro-1", 0)
must(t, err)
// reason="" so no comment is added; only the status update event should appear.
must(t, s.ReopenIssue(ctx(), "ro-1", "", "a"))
after, err := s.GetEvents(ctx(), "ro-1", 0)
must(t, err)
if len(after) != len(before)+1 {
t.Errorf("events after reopen-on-open = %d, want %d (one new event)", len(after), len(before)+1)
if len(after) != len(before) {
t.Errorf("events after reopen-on-open = %d, want %d (strict no-op)", len(after), len(before))
}
must(t, s.CloseIssue(ctx(), "ro-1", "done", "a", "session"))
must(t, s.ReopenIssue(ctx(), "ro-1", "", "a"))
afterClosedReopen, err := s.GetEvents(ctx(), "ro-1", 0)
must(t, err)
if n := auditCountEventType(afterClosedReopen, types.EventReopened); n != 1 {
t.Errorf("EventReopened count after closed reopen = %d, want 1", n)
}
}

View file

@ -0,0 +1,286 @@
package conformance
import (
"context"
"encoding/json"
"errors"
"reflect"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// This file holds the behavior contract every implementation of
// publicops.Lifecycle must satisfy, independent of how it reaches storage.
// There are three of them — the direct store, the embedded store, and the
// unit-of-work backend — and the first two share an execution path the third
// does not. Behavior asserted only against one backend has repeatedly drifted
// on the others, so each of these runs against all three from one spec.
// RunIssueOperationsCreateRoutesInfraTypesToWisps pins the facade create
// against the same infra-type routing the stores' own CreateIssue applies: a
// configured infra type is ephemeral and lives in the wisp tables, never in
// issues.
func RunIssueOperationsCreateRoutesInfraTypesToWisps(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) {
t.Helper()
for key, value := range map[string]string{"types.custom": "agent", "types.infra": "agent"} {
if err := fixture.SetConfig(ctx, key, value); err != nil {
t.Fatalf("SetConfig(%s): %v", key, err)
}
}
result, err := fixture.Operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
Issue: &types.Issue{Title: "infra bead", Status: types.StatusOpen, Priority: 2, IssueType: types.IssueType("agent")},
})
if err != nil {
t.Fatalf("Create: %v", err)
}
if !result.Issue.Ephemeral {
t.Errorf("create result Ephemeral = false, want true for infra type %q", result.Issue.IssueType)
}
assertIssueOperationsRowCount(t, ctx, fixture, "wisps", result.Issue.ID, 1)
assertIssueOperationsRowCount(t, ctx, fixture, "issues", result.Issue.ID, 0)
// A no-history infra create keeps its no-history retention rather than
// being upgraded to ephemeral, matching CreateIssue.
noHistory, err := fixture.Operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
Issue: &types.Issue{Title: "infra no-history", Status: types.StatusOpen, Priority: 2, IssueType: types.IssueType("agent"), NoHistory: true},
})
if err != nil {
t.Fatalf("Create no-history: %v", err)
}
if noHistory.Issue.Ephemeral {
t.Errorf("no-history infra create Ephemeral = true, want false")
}
assertIssueOperationsRowCount(t, ctx, fixture, "wisps", noHistory.Issue.ID, 1)
assertIssueOperationsRowCount(t, ctx, fixture, "issues", noHistory.Issue.ID, 0)
// A non-infra type is unaffected.
durable, err := fixture.Operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
Issue: &types.Issue{Title: "durable bead", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
})
if err != nil {
t.Fatalf("Create durable: %v", err)
}
if durable.Issue.Ephemeral {
t.Errorf("durable create Ephemeral = true, want false")
}
assertIssueOperationsRowCount(t, ctx, fixture, "issues", durable.Issue.ID, 1)
assertIssueOperationsRowCount(t, ctx, fixture, "wisps", durable.Issue.ID, 0)
}
// RunIssueOperationsCreateRejectsMissingDependencyTargets pins the facade
// create against reporting success for an issue whose requested relationships
// were never written. The batch engine tolerates a dangling edge so a partial
// import still lands; a guarded single create must refuse the whole request
// with a typed error naming the target, and leave nothing behind.
func RunIssueOperationsCreateRejectsMissingDependencyTargets(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) {
t.Helper()
seed := &types.Issue{ID: fixture.IssuePrefix + "-skipdep-seed", Title: "seed", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := fixture.CreateIssue(ctx, seed, "seed"); err != nil {
t.Fatalf("seed: %v", err)
}
cases := []struct {
name string
id string
request publicops.CreateRequest
target string
}{
{
name: "explicit dependency",
id: fixture.IssuePrefix + "-skipdep-explicit",
target: fixture.IssuePrefix + "-skipdep-missing-dep",
request: publicops.CreateRequest{
Dependencies: []publicops.CreateDependency{{TargetID: fixture.IssuePrefix + "-skipdep-missing-dep", Type: types.DepBlocks}},
},
},
{
name: "parent",
id: fixture.IssuePrefix + "-skipdep-parent",
target: fixture.IssuePrefix + "-skipdep-missing-parent",
request: publicops.CreateRequest{ParentID: fixture.IssuePrefix + "-skipdep-missing-parent"},
},
{
name: "waits-for spawner",
id: fixture.IssuePrefix + "-skipdep-waits",
target: fixture.IssuePrefix + "-skipdep-missing-spawner",
request: publicops.CreateRequest{
WaitsFor: &publicops.WaitsFor{SpawnerID: fixture.IssuePrefix + "-skipdep-missing-spawner"},
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := tc.request
request.Actor = "writer"
request.ForceIDPrefix = true
request.Issue = &types.Issue{ID: tc.id, Title: tc.name, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
_, err := fixture.Operations.Create(ctx, request)
if err == nil {
t.Fatal("Create returned nil error, want a refusal for the missing dependency target")
}
if !errors.Is(err, publicops.ErrNotFound) {
t.Errorf("Create error = %v, want ErrNotFound", err)
}
if !errors.Is(err, publicops.ErrValidation) {
t.Errorf("Create error = %v, want ErrValidation", err)
}
if !strings.Contains(err.Error(), tc.target) {
t.Errorf("Create error = %v, want it to name the missing target %q", err, tc.target)
}
assertIssueOperationsRowCount(t, ctx, fixture, "issues", tc.id, 0)
assertIssueOperationsRowCount(t, ctx, fixture, "wisps", tc.id, 0)
})
}
// A create whose targets all exist is unaffected.
result, err := fixture.Operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
ForceIDPrefix: true,
Issue: &types.Issue{ID: fixture.IssuePrefix + "-skipdep-ok", Title: "ok", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
Dependencies: []publicops.CreateDependency{{TargetID: seed.ID, Type: types.DepBlocks}},
})
if err != nil {
t.Fatalf("Create with existing target: %v", err)
}
if len(result.Issue.Dependencies) != 1 || result.Issue.Dependencies[0].DependsOnID != seed.ID {
t.Fatalf("Create result dependencies = %#v, want one edge to %s", result.Issue.Dependencies, seed.ID)
}
}
// RunIssueOperationsUpdateFoldsMetadataIntoOneEvent pins a compound update to a
// single event. A guarded update is one atomic mutation, so its history must
// read as one entry; a metadata patch riding along with field edits must not
// write the row twice and fabricate a second event in the stream every history
// consumer sees.
func RunIssueOperationsUpdateFoldsMetadataIntoOneEvent(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) {
t.Helper()
issue := &types.Issue{
ID: fixture.IssuePrefix + "-metadata-event", Title: "metadata event", Status: types.StatusOpen,
Priority: 2, IssueType: types.TypeTask, Metadata: json.RawMessage(`{"keep":"old"}`),
}
if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed: %v", err)
}
events := newIssueOperationsEventCounter(t, ctx, fixture, issue.ID)
updated, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{
Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusInProgress},
Metadata: publicops.MetadataPatch{
Set: map[string]json.RawMessage{"added": json.RawMessage(`"value"`)},
},
}})
if err != nil {
t.Fatalf("compound update: %v", err)
}
if !updated.Changed || updated.Issue.Status != types.StatusInProgress {
t.Fatalf("compound update result = %#v", updated)
}
assertIssueOperationsMetadata(t, "compound update", updated.Issue.Metadata, `{"added":"value","keep":"old"}`)
events.assert(t, "compound update", 1, map[types.EventType]int{types.EventStatusChanged: 1, types.EventUpdated: 0})
// A metadata-only patch still records its own single event.
metadataOnly, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{
Metadata: publicops.MetadataPatch{Unset: []string{"keep"}},
}})
if err != nil || !metadataOnly.Changed {
t.Fatalf("metadata-only update = %#v, %v", metadataOnly, err)
}
assertIssueOperationsMetadata(t, "metadata-only update", metadataOnly.Issue.Metadata, `{"added":"value"}`)
events.assert(t, "metadata-only update", 1, map[types.EventType]int{types.EventUpdated: 1})
// A metadata patch that changes nothing stays elided.
noOp, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{
Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"added": json.RawMessage(`"value"`)}},
}})
if err != nil || noOp.Changed {
t.Fatalf("no-op metadata update = %#v, %v", noOp, err)
}
events.assert(t, "no-op metadata update", 0, nil)
}
func assertIssueOperationsRowCount(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, table, id string, want int) {
t.Helper()
var got int
//nolint:gosec // G201: table is one of the contract's hardcoded table names
if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM "+table+" WHERE id = ?", []any{id}, &got); err != nil {
t.Fatalf("count %s rows for %s: %v", table, id, err)
}
if got != want {
t.Errorf("%s rows for %s = %d, want %d", table, id, got, want)
}
}
func assertIssueOperationsMetadata(t *testing.T, label string, got json.RawMessage, want string) {
t.Helper()
var gotValue, wantValue any
if err := json.Unmarshal(got, &gotValue); err != nil {
t.Fatalf("%s metadata %s: %v", label, got, err)
}
if err := json.Unmarshal([]byte(want), &wantValue); err != nil {
t.Fatalf("%s want metadata %s: %v", label, want, err)
}
if !reflect.DeepEqual(gotValue, wantValue) {
t.Fatalf("%s metadata = %s, want %s", label, got, want)
}
}
// issueOperationsEventCounter reports how many event rows each operation adds
// for one issue.
type issueOperationsEventCounter struct {
ctx context.Context
fixture IssueOperationsStagingFixture
id string
total int
byType map[types.EventType]int
}
func newIssueOperationsEventCounter(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, id string) *issueOperationsEventCounter {
t.Helper()
counter := &issueOperationsEventCounter{ctx: ctx, fixture: fixture, id: id, byType: map[types.EventType]int{}}
counter.total = counter.count(t, "")
for _, eventType := range []types.EventType{types.EventUpdated, types.EventStatusChanged} {
counter.byType[eventType] = counter.count(t, eventType)
}
return counter
}
func (c *issueOperationsEventCounter) count(t *testing.T, eventType types.EventType) int {
t.Helper()
query := "SELECT COUNT(*) FROM events WHERE issue_id = ?"
args := []any{c.id}
if eventType != "" {
query += " AND event_type = ?"
args = append(args, string(eventType))
}
var got int
if err := c.fixture.QueryScalar(c.ctx, query, args, &got); err != nil {
t.Fatalf("count events for %s (%q): %v", c.id, eventType, err)
}
return got
}
// assert checks the rows added since the previous assert and re-baselines.
func (c *issueOperationsEventCounter) assert(t *testing.T, label string, wantTotal int, wantByType map[types.EventType]int) {
t.Helper()
total := c.count(t, "")
if got := total - c.total; got != wantTotal {
t.Errorf("%s wrote %d event rows, want %d", label, got, wantTotal)
}
c.total = total
for eventType, want := range wantByType {
current := c.count(t, eventType)
if got := current - c.byType[eventType]; got != want {
t.Errorf("%s wrote %d %q events, want %d", label, got, eventType, want)
}
}
for _, eventType := range []types.EventType{types.EventUpdated, types.EventStatusChanged} {
c.byType[eventType] = c.count(t, eventType)
}
}

View file

@ -0,0 +1,195 @@
package conformance
import (
"context"
"testing"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// IssueOperationsStagingFixture supplies adapter-specific storage access for
// the issue-operations assertions. Each Run function documents which fields it
// needs; an adapter supplies only those.
type IssueOperationsStagingFixture struct {
IssuePrefix string
Operations publicops.Lifecycle
CreateIssue func(context.Context, *types.Issue, string) error
AddDependency func(context.Context, *types.Dependency, string) error
GetReadyWork func(context.Context, types.WorkFilter) ([]*types.Issue, error)
SetConfig func(context.Context, string, string) error
Commit func(context.Context, string) error
Exec func(context.Context, string, ...any) error
QueryScalar func(context.Context, string, []any, ...any) error
}
// RunIssueOperationsCreateReverseNonBlockingStagesConcreteTables proves that a
// reverse nonblocking dependency commits its concrete dependency row without
// sweeping an unrelated dirty durable row into the same commit.
func RunIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) {
t.Helper()
source := &types.Issue{
ID: fixture.IssuePrefix + "-create-relates-source",
Title: "source",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
dirty := &types.Issue{
ID: fixture.IssuePrefix + "-create-relates-dirty",
Title: "committed title",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
for _, issue := range []*types.Issue{source, dirty} {
if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed issue %s: %v", issue.ID, err)
}
}
if err := fixture.Commit(ctx, "seed selective create staging"); err != nil {
t.Fatalf("commit seed state: %v", err)
}
if err := fixture.Exec(ctx, "UPDATE issues SET title = ? WHERE id = ?", "working title", dirty.ID); err != nil {
t.Fatalf("dirty unrelated issue: %v", err)
}
assertIssueOperationsScalar(t, ctx, fixture, "working dirty title", "working title",
"SELECT title FROM issues WHERE id = ?", []any{dirty.ID})
assertIssueOperationsScalar(t, ctx, fixture, "committed dirty title before create", "committed title",
"SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", []any{dirty.ID})
created, err := fixture.Operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
ForceIDPrefix: true,
Issue: &types.Issue{
Title: "generated wisp",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
Ephemeral: true,
},
Dependencies: []publicops.CreateDependency{{
TargetID: source.ID,
Type: types.DepRelatesTo,
Reverse: true,
}},
})
if err != nil {
t.Fatalf("create generated wisp: %v", err)
}
if created.Issue == nil || created.Issue.ID == "" {
t.Fatalf("created issue = %#v, want generated wisp ID", created.Issue)
}
assertIssueOperationsScalar(t, ctx, fixture, "committed reverse dependency", 1,
"SELECT COUNT(*) FROM dependencies AS OF 'HEAD' WHERE issue_id = ? AND depends_on_wisp_id = ? AND type = ?",
[]any{source.ID, created.Issue.ID, types.DepRelatesTo})
assertIssueOperationsScalar(t, ctx, fixture, "working source blocked state", false,
"SELECT is_blocked FROM issues WHERE id = ?", []any{source.ID})
assertIssueOperationsScalar(t, ctx, fixture, "committed source blocked state", false,
"SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{source.ID})
assertIssueOperationsScalar(t, ctx, fixture, "working dirty title after create", "working title",
"SELECT title FROM issues WHERE id = ?", []any{dirty.ID})
assertIssueOperationsScalar(t, ctx, fixture, "committed dirty title after create", "committed title",
"SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", []any{dirty.ID})
}
// RunIssueOperationsCreateParentChildRecomputesWaitsForClosure proves that
// creating an open child updates an existing waiter on the child's spawner in
// both the working set and committed readiness state.
func RunIssueOperationsCreateParentChildRecomputesWaitsForClosure(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) {
t.Helper()
spawner := &types.Issue{
ID: fixture.IssuePrefix + "-create-spawner",
Title: "spawner",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
waiter := &types.Issue{
ID: fixture.IssuePrefix + "-create-waiter",
Title: "waiter",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
for _, issue := range []*types.Issue{spawner, waiter} {
if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed issue %s: %v", issue.ID, err)
}
}
if err := fixture.AddDependency(ctx, &types.Dependency{
IssueID: waiter.ID,
DependsOnID: spawner.ID,
Type: types.DepWaitsFor,
}, "seed"); err != nil {
t.Fatalf("seed waits-for dependency: %v", err)
}
if err := fixture.Commit(ctx, "seed waits-for create closure"); err != nil {
t.Fatalf("commit seed state: %v", err)
}
assertIssueOperationsScalar(t, ctx, fixture, "working waiter before child create", false,
"SELECT is_blocked FROM issues WHERE id = ?", []any{waiter.ID})
assertIssueOperationsScalar(t, ctx, fixture, "committed waiter before child create", false,
"SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{waiter.ID})
assertIssueOperationsReady(t, ctx, fixture, waiter.ID, true)
created, err := fixture.Operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
ForceIDPrefix: true,
Issue: &types.Issue{
Title: "open child",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
},
ParentID: spawner.ID,
})
if err != nil {
t.Fatalf("create open child: %v", err)
}
if created.Issue == nil || created.Issue.ID != spawner.ID+".1" {
t.Fatalf("created issue = %#v, want child %s.1", created.Issue, spawner.ID)
}
assertIssueOperationsScalar(t, ctx, fixture, "committed parent-child dependency", 1,
"SELECT COUNT(*) FROM dependencies AS OF 'HEAD' WHERE issue_id = ? AND depends_on_issue_id = ? AND type = ?",
[]any{created.Issue.ID, spawner.ID, types.DepParentChild})
assertIssueOperationsScalar(t, ctx, fixture, "working waiter after child create", true,
"SELECT is_blocked FROM issues WHERE id = ?", []any{waiter.ID})
assertIssueOperationsScalar(t, ctx, fixture, "committed waiter after child create", true,
"SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{waiter.ID})
assertIssueOperationsReady(t, ctx, fixture, waiter.ID, false)
}
func assertIssueOperationsScalar[T comparable](t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, name string, want T, query string, args []any) {
t.Helper()
var got T
if err := fixture.QueryScalar(ctx, query, args, &got); err != nil {
t.Fatalf("%s: %v", name, err)
}
if got != want {
t.Fatalf("%s = %v, want %v", name, got, want)
}
}
func assertIssueOperationsReady(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, issueID string, want bool) {
t.Helper()
ready, err := fixture.GetReadyWork(ctx, types.WorkFilter{})
if err != nil {
t.Fatalf("get ready work: %v", err)
}
for _, issue := range ready {
if issue != nil && issue.ID == issueID {
if !want {
t.Fatalf("ready work contains %s, want absent", issueID)
}
return
}
}
if want {
t.Fatalf("ready work omits %s, want present", issueID)
}
}

View file

@ -40,3 +40,22 @@ func IsTableNotExist(err error) bool {
quotedTableMissingPattern.MatchString(s) ||
unquotedTableMissingPattern.MatchString(s)
}
// IsMissingForeignKeyTarget reports whether err is the integrity-constraint
// violation a write hits when it references a row that does not exist: MySQL
// 1452 (ER_NO_REFERENCED_ROW_2) and its older 1216 (ER_NO_REFERENCED_ROW).
// It deliberately does not classify 1451 (ER_ROW_IS_REFERENCED_2), which is
// the opposite direction — deleting a row other rows still point at.
func IsMissingForeignKeyTarget(err error) bool {
if err == nil {
return false
}
var mysqlErr *mysql.MySQLError
if errors.As(err, &mysqlErr) {
return mysqlErr.Number == 1452 || mysqlErr.Number == 1216
}
s := strings.ToLower(err.Error())
return strings.Contains(s, "error 1452") || strings.Contains(s, "error 1216")
}

View file

@ -48,12 +48,18 @@ type claimPostcondition struct {
}
func claimedBy(actor string) claimPostcondition {
return claimedAs(actor, types.StatusInProgress)
}
// claimedAs is claimedBy for a claim whose request overrides the assignee or
// status the bare claim would have written.
func claimedAs(assignee string, status types.Status) claimPostcondition {
return claimPostcondition{
op: "claim",
want: func(assignee string, status types.Status) bool {
return assignee == actor && status == types.StatusInProgress
want: func(gotAssignee string, gotStatus types.Status) bool {
return gotAssignee == assignee && gotStatus == status
},
desc: fmt.Sprintf("assignee=%q status=%q", actor, types.StatusInProgress),
desc: fmt.Sprintf("assignee=%q status=%q", assignee, status),
}
}

View file

@ -1,10 +1,13 @@
package dolt
import (
"database/sql"
"errors"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/depid"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
)
@ -414,6 +417,315 @@ func TestCloseIssueChecked(t *testing.T) {
tc.check(t, id, res, err)
})
}
t.Run("open children refuse and force reports count", func(t *testing.T) {
parent, permanentChild, wispChild := "cic-children-parent", "cic-children-permanent", "cic-children-wisp"
blocker := "cic-children-blocker"
createPerm(t, ctx, store, parent)
createPerm(t, ctx, store, permanentChild)
createWisp(t, ctx, store, wispChild)
createPerm(t, ctx, store, blocker)
if err := store.AddDependency(ctx, &types.Dependency{IssueID: parent, DependsOnID: blocker, Type: types.DepBlocks}, "tester"); err != nil {
t.Fatalf("AddDependency(%s -> %s): %v", parent, blocker, err)
}
for _, child := range []string{permanentChild, wispChild} {
if err := store.AddDependency(ctx, &types.Dependency{IssueID: child, DependsOnID: parent, Type: types.DepParentChild}, "tester"); err != nil {
t.Fatalf("AddDependency(%s -> %s): %v", child, parent, err)
}
}
res, err := store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "done"})
var childErr *storage.CloseOpenChildrenError
if !errors.Is(err, storage.ErrCloseOpenChildren) || !errors.As(err, &childErr) || childErr.IssueID != parent || childErr.OpenChildren != 2 {
t.Fatalf("child error = %+v, err = %v; want typed refusal for %s with 2 children", childErr, err, parent)
}
if got, want := getStatus(t, parent), types.StatusOpen; got != want {
t.Fatalf("parent status after refusal = %q, want %q", got, want)
}
res, err = store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "override", Force: true})
if err != nil || res.Unchanged || res.OpenChildren != 2 {
t.Fatalf("force result = %+v, err = %v; want changed close with 2 children", res, err)
}
res, err = store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "again"})
if !errors.Is(err, storage.ErrCloseOpenChildren) {
t.Fatalf("non-force re-close error = %v, want ErrCloseOpenChildren", err)
}
res, err = store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "again", Force: true})
if err != nil || !res.Unchanged || res.OpenChildren != 2 {
t.Fatalf("forced re-close result = %+v, err = %v; want unchanged with 2 children", res, err)
}
wispParent, childOfWispParent := "cic-children-wisp-parent", "cic-children-wisp-parent-child"
createWisp(t, ctx, store, wispParent)
createPerm(t, ctx, store, childOfWispParent)
if err := store.AddDependency(ctx, &types.Dependency{IssueID: childOfWispParent, DependsOnID: wispParent, Type: types.DepParentChild}, "tester"); err != nil {
t.Fatalf("AddDependency(%s -> %s): %v", childOfWispParent, wispParent, err)
}
res, err = store.CloseIssueChecked(ctx, wispParent, "tester", storage.CloseIssueOptions{Reason: "done"})
if !errors.Is(err, storage.ErrCloseOpenChildren) {
t.Fatalf("wisp parent close error = %v, want ErrCloseOpenChildren", err)
}
res, err = store.CloseIssueChecked(ctx, wispParent, "tester", storage.CloseIssueOptions{Reason: "override", Force: true})
if err != nil || res.Unchanged || res.OpenChildren != 1 {
t.Fatalf("wisp parent force result = %+v, err = %v; want changed close with 1 child", res, err)
}
})
t.Run("duplicate durable and wisp child edge counts once", func(t *testing.T) {
parent, child := "cic-collision-parent", "cic-collision-child"
createPerm(t, ctx, store, parent)
createPerm(t, ctx, store, child)
if err := store.AddDependency(ctx, &types.Dependency{
IssueID: child, DependsOnID: parent, Type: types.DepParentChild,
}, "tester"); err != nil {
t.Fatalf("AddDependency(%s -> %s): %v", child, parent, err)
}
if _, err := store.execContext(ctx, `
INSERT INTO wisps (id, title, description, design, acceptance_criteria, notes, status, priority, issue_type, ephemeral, no_history)
VALUES (?, ?, '', '', '', '', ?, ?, ?, ?, ?)
`, child, "wisp duplicate "+child, types.StatusOpen, 2, types.TypeTask, false, true); err != nil {
t.Fatalf("insert matching wisp child: %v", err)
}
collisionID := depid.New(child, parent)
if _, err := store.db.ExecContext(ctx,
"INSERT INTO wisp_dependencies (id, issue_id, depends_on_issue_id, type, created_by) VALUES (?, ?, ?, 'parent-child', 'tester')",
collisionID, child, parent); err != nil {
t.Fatalf("seed duplicate child edge: %v", err)
}
res, err := store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "done"})
var childErr *storage.CloseOpenChildrenError
if !errors.Is(err, storage.ErrCloseOpenChildren) || !errors.As(err, &childErr) || childErr.OpenChildren != 1 {
t.Fatalf("child error = %+v, err = %v; want typed refusal with 1 child", childErr, err)
}
res, err = store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "override", Force: true})
if err != nil || res.Unchanged || res.OpenChildren != 1 {
t.Fatalf("force result = %+v, err = %v; want changed close with 1 child", res, err)
}
})
t.Run("durable dependency wins a cross-table type conflict", func(t *testing.T) {
parent, child := "cic-conflict-parent", "cic-conflict-child"
createPerm(t, ctx, store, parent)
createPerm(t, ctx, store, child)
if err := store.AddDependency(ctx, &types.Dependency{
IssueID: child, DependsOnID: parent, Type: types.DepRelated,
}, "tester"); err != nil {
t.Fatalf("AddDependency(%s -> %s): %v", child, parent, err)
}
if _, err := store.execContext(ctx, `
INSERT INTO wisps (id, title, description, design, acceptance_criteria, notes, status, priority, issue_type, ephemeral, no_history)
VALUES (?, ?, '', '', '', '', ?, ?, ?, ?, ?)
`, child, "wisp duplicate "+child, types.StatusOpen, 2, types.TypeTask, false, true); err != nil {
t.Fatalf("insert matching wisp child: %v", err)
}
collisionID := depid.New(child, parent)
if _, err := store.db.ExecContext(ctx,
"INSERT INTO wisp_dependencies (id, issue_id, depends_on_issue_id, type, created_by) VALUES (?, ?, ?, 'parent-child', 'tester')",
collisionID, child, parent); err != nil {
t.Fatalf("seed conflicting child edge: %v", err)
}
res, err := store.CloseIssueChecked(ctx, parent, "tester", storage.CloseIssueOptions{Reason: "done"})
if err != nil || res.Unchanged || res.OpenChildren != 0 {
t.Fatalf("close result = %+v, err = %v; want changed close with no durable parent-child child", res, err)
}
})
t.Run("missing target precedes child count", func(t *testing.T) {
child, missing := "cic-dangling-child", "cic-dangling-parent"
createPerm(t, ctx, store, child)
if _, err := store.db.ExecContext(ctx, "SET FOREIGN_KEY_CHECKS = 0"); err != nil {
t.Fatalf("disable FK checks: %v", err)
}
if _, err := store.db.ExecContext(ctx, "INSERT INTO dependencies (id, issue_id, depends_on_issue_id, type, created_at, created_by) VALUES (UUID(), ?, ?, 'parent-child', NOW(), 'tester')", child, missing); err != nil {
t.Fatalf("insert dangling parent-child edge: %v", err)
}
if _, err := store.db.ExecContext(ctx, "SET FOREIGN_KEY_CHECKS = 1"); err != nil {
t.Fatalf("re-enable FK checks: %v", err)
}
_, err := store.CloseIssueChecked(ctx, missing, "tester", storage.CloseIssueOptions{Reason: "done"})
if !errors.Is(err, storage.ErrNotFound) || errors.Is(err, storage.ErrCloseOpenChildren) {
t.Fatalf("err = %v, want ErrNotFound but not ErrCloseOpenChildren", err)
}
})
}
// TestCloseIssueCheckedParentChildInsertCannotPhantomMerge is a controlled
// two-transaction Dolt regression: a close which observes no children and a
// concurrently-created open parent-child edge must not both commit. If they do,
// the resulting durable state can preserve an overlapping stale-snapshot
// decision instead of forcing one writer to retry against the other.
func TestCloseIssueCheckedParentChildInsertCannotPhantomMerge(t *testing.T) {
store, cleanup := setupConcurrentTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
const (
parent = "close-child-phantom-parent"
child = "close-child-phantom-child"
)
createPerm(t, ctx, store, parent)
createPerm(t, ctx, store, child)
// Deliberately start both transactions before either writes. The close reads
// zero children before txAdd inserts its edge; committing close first makes
// this interleaving deterministic rather than timing-dependent.
txClose, err := store.db.BeginTx(ctx, nil)
if err != nil {
t.Fatalf("begin close transaction: %v", err)
}
defer txClose.Rollback() // no-op after Commit; preserves cleanup on early Fatal.
txAdd, err := store.db.BeginTx(ctx, nil)
if err != nil {
t.Fatalf("begin add-child transaction: %v", err)
}
defer txAdd.Rollback()
closeResult, err := issueops.CloseIssueCheckedInTx(ctx, txClose, parent, "done", "tester", "", false, nil)
if err != nil {
t.Fatalf("checked close before concurrent edge: %v", err)
}
if closeResult.OpenChildren != 0 || closeResult.AlreadyClosed {
t.Fatalf("close precondition result = %+v, want a real close after observing zero children", closeResult)
}
if _, err := issueops.AddDependencyInTx(ctx, txAdd, &types.Dependency{
IssueID: child, DependsOnID: parent, Type: types.DepParentChild,
}, "tester", issueops.AddDependencyOpts{}); err != nil {
t.Fatalf("insert concurrent parent-child edge: %v", err)
}
closeCommitErr := txClose.Commit()
addCommitErr := txAdd.Commit()
t.Logf("controlled close/add commits: close=%v add=%v", closeCommitErr, addCommitErr)
if closeCommitErr == nil && addCommitErr == nil {
var parentStatus, childStatus string
if err := store.db.QueryRowContext(ctx, "SELECT status FROM issues WHERE id = ?", parent).Scan(&parentStatus); err != nil {
t.Fatalf("read parent after both commits: %v", err)
}
if err := store.db.QueryRowContext(ctx, "SELECT status FROM issues WHERE id = ?", child).Scan(&childStatus); err != nil {
t.Fatalf("read child after both commits: %v", err)
}
t.Fatalf("phantom parent-child merge: checked close and edge insert both committed (parent=%s child=%s); one transaction must conflict or be refused", parentStatus, childStatus)
}
// A conflict on either commit is the required serialization outcome. Keep
// both errors in the failure below should a future Dolt version return an
// unexpected non-serialization result from a changed transaction contract.
if closeCommitErr != nil && !isSerializationError(closeCommitErr) {
t.Fatalf("close commit error = %v, want a serialization conflict", closeCommitErr)
}
if addCommitErr != nil && !isSerializationError(addCommitErr) {
t.Fatalf("add-child commit error = %v, want a serialization conflict", addCommitErr)
}
}
// TestCloseIssueCheckedPinnedConnRefusalRestoresCoordinationSavepoint proves
// that the production pinned-connection UOW can catch a checked-close refusal
// and commit a sibling operation without persisting the refused close's
// coordination writes.
func TestCloseIssueCheckedPinnedConnRefusalRestoresCoordinationSavepoint(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
const (
parent = "close-savepoint-parent"
child = "close-savepoint-child"
sibling = "close-savepoint-sibling"
)
for _, id := range []string{parent, child, sibling} {
createPerm(t, ctx, store, id)
}
if err := store.AddDependency(ctx, &types.Dependency{
IssueID: child, DependsOnID: parent, Type: types.DepParentChild,
}, "tester"); err != nil {
t.Fatalf("AddDependency(%s -> %s): %v", child, parent, err)
}
coordinationValue := func(t *testing.T, tier string) *string {
t.Helper()
var value string
err := store.db.QueryRowContext(ctx,
"SELECT value FROM local_metadata WHERE `key` LIKE ?",
"dependency-coordination/v1/"+tier+"/%",
).Scan(&value)
if errors.Is(err, sql.ErrNoRows) {
return nil
}
if err != nil {
t.Fatalf("read %s coordination cell: %v", tier, err)
}
return &value
}
beforeDurable := coordinationValue(t, "dependencies")
beforeWisp := coordinationValue(t, "wisp_dependencies")
if beforeDurable == nil || beforeWisp != nil {
t.Fatalf("pre-call coordination = durable:%v wisp:%v, want durable token and absent wisp token", beforeDurable, beforeWisp)
}
conn, err := store.db.Conn(ctx)
if err != nil {
t.Fatalf("pin transaction connection: %v", err)
}
transactionOpen := true
defer func() {
if transactionOpen {
_, _ = conn.ExecContext(ctx, "ROLLBACK")
}
_ = conn.Close()
}()
if _, err := conn.ExecContext(ctx, "START TRANSACTION"); err != nil {
t.Fatalf("start pinned-connection transaction: %v", err)
}
_, err = issueops.CloseIssueCheckedInTx(ctx, conn, parent, "done", "tester", "", false, nil)
if !errors.Is(err, storage.ErrCloseOpenChildren) {
t.Fatalf("checked close error = %v, want ErrCloseOpenChildren", err)
}
if _, err := issueops.CloseIssueInTx(ctx, conn, sibling, "done", "tester", ""); err != nil {
t.Fatalf("close sibling after refused parent close: %v", err)
}
if _, err := conn.ExecContext(ctx, "COMMIT"); err != nil {
t.Fatalf("commit sibling close after refusal: %v", err)
}
transactionOpen = false
if err := conn.Close(); err != nil {
t.Fatalf("release committed transaction connection: %v", err)
}
for _, check := range []struct {
id string
status types.Status
}{{parent, types.StatusOpen}, {sibling, types.StatusClosed}} {
issue, err := store.GetIssue(ctx, check.id)
if err != nil {
t.Fatalf("GetIssue(%s): %v", check.id, err)
}
if issue.Status != check.status {
t.Fatalf("%s status = %q, want %q", check.id, issue.Status, check.status)
}
}
for _, check := range []struct {
tier string
want *string
}{
{tier: "dependencies", want: beforeDurable},
{tier: "wisp_dependencies", want: beforeWisp},
} {
got := coordinationValue(t, check.tier)
if (got == nil) != (check.want == nil) {
t.Fatalf("%s coordination presence = %v, want %v", check.tier, got != nil, check.want != nil)
}
if got != nil && *got != *check.want {
t.Fatalf("%s coordination value = %q, want pre-call %q", check.tier, *got, *check.want)
}
}
}
// TestCloseIssueCheckedVersionCAS exercises the optional ExpectedVersion

View file

@ -174,11 +174,13 @@ func TestDemoteToWisp_MetadataAndClosedAtUpdatesApplied(t *testing.T) {
if err := store.UpdateIssue(ctx, issue.ID, map[string]interface{}{
"no_history": true,
"status": string(types.StatusClosed),
"metadata": `{"review":"kept"}`,
}, "tester"); err != nil {
t.Fatalf("UpdateIssue: %v", err)
}
if err := store.CloseIssue(ctx, issue.ID, "", "tester", ""); err != nil {
t.Fatalf("CloseIssue: %v", err)
}
wisp, err := store.GetIssue(ctx, issue.ID)
if err != nil {

View file

@ -0,0 +1,65 @@
package dolt
import (
"testing"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
)
func TestAddDependencyInTxParentChildCoordinationTouch(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
parent, child, blocker, blocked := "coord-parent", "coord-child", "coord-blocker", "coord-blocked"
for _, id := range []string{parent, child, blocker, blocked} {
createPerm(t, ctx, store, id)
}
key := "dependency-coordination/v1/dependencies/%"
add := func(dep *types.Dependency) {
t.Helper()
tx, err := store.db.BeginTx(ctx, nil)
if err != nil {
t.Fatalf("begin add dependency transaction: %v", err)
}
defer tx.Rollback()
if _, err := issueops.AddDependencyInTx(ctx, tx, dep, "tester", issueops.AddDependencyOpts{}); err != nil {
t.Fatalf("AddDependencyInTx(%s -> %s): %v", dep.IssueID, dep.DependsOnID, err)
}
if err := tx.Commit(); err != nil {
t.Fatalf("commit add dependency: %v", err)
}
}
add(&types.Dependency{IssueID: child, DependsOnID: parent, Type: types.DepParentChild})
var value string
if err := store.db.QueryRowContext(ctx, "SELECT value FROM local_metadata WHERE `key` LIKE ?", key).Scan(&value); err != nil {
t.Fatalf("read new parent-child coordination token: %v", err)
}
if value == "" {
t.Fatal("new parent-child edge did not write a coordination token")
}
if _, err := store.db.ExecContext(ctx, "UPDATE local_metadata SET value = 'sentinel' WHERE `key` LIKE ?", key); err != nil {
t.Fatalf("seed idempotent sentinel: %v", err)
}
add(&types.Dependency{IssueID: child, DependsOnID: parent, Type: types.DepParentChild})
if err := store.db.QueryRowContext(ctx, "SELECT value FROM local_metadata WHERE `key` LIKE ?", key).Scan(&value); err != nil {
t.Fatalf("read idempotent coordination token: %v", err)
}
if value != "sentinel" {
t.Fatalf("idempotent parent-child re-add rewrote coordination token = %q, want sentinel", value)
}
add(&types.Dependency{IssueID: blocker, DependsOnID: blocked, Type: types.DepBlocks})
var count int
if err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM local_metadata WHERE `key` LIKE ?", key).Scan(&count); err != nil {
t.Fatalf("count coordination rows after non-parent edge: %v", err)
}
if count != 1 {
t.Fatalf("coordination rows after non-parent edge = %d, want 1", count)
}
}

View file

@ -0,0 +1,29 @@
package dolt
import (
"errors"
"testing"
"github.com/steveyegge/beads/internal/storage"
)
func TestDoltStoreIssueLifecycleBuildsOperations(t *testing.T) {
lifecycle, err := (&DoltStore{}).IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle() error = %v", err)
}
if lifecycle == nil {
t.Fatal("IssueLifecycle() returned nil operations")
}
}
func TestDoltStoreIssueLifecycleRejectsNilStore(t *testing.T) {
lifecycle, err := (*DoltStore)(nil).IssueLifecycle()
if lifecycle != nil {
t.Fatalf("IssueLifecycle() lifecycle = %T, want nil", lifecycle)
}
var unsupported *storage.ErrUnsupported
if !errors.As(err, &unsupported) {
t.Fatalf("IssueLifecycle() error = %v, want *storage.ErrUnsupported", err)
}
}

View file

@ -0,0 +1,143 @@
package dolt
import (
"context"
"database/sql"
"github.com/steveyegge/beads/internal/storage"
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// IssueLifecycle returns the guarded issue-lifecycle surface for this store.
func (s *DoltStore) IssueLifecycle() (issueops.Lifecycle, error) {
return NewIssueOperations(s)
}
// NewIssueOperations returns guarded issue operations backed by store.
func NewIssueOperations(store *DoltStore) (issueops.Lifecycle, error) {
if store == nil {
return nil, &storage.ErrUnsupported{Op: "NewIssueOperations", Backend: "nil"}
}
return &issueOperations{store: store}, nil
}
type issueOperations struct{ store *DoltStore }
// updateCommitMessage names the updated issue in the Dolt commit message.
func updateCommitMessage(issueID string) string {
if issueID == "" {
return "bd: update issue"
}
return "bd: update " + issueID
}
func (o *issueOperations) Create(ctx context.Context, request issueops.CreateRequest) (issueops.CreateResult, error) {
snapshot := storageissueops.CloneCreateRequest(request)
var result issueops.CreateResult
err := o.store.runIssueOperationTx(ctx, "bd: create issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) {
var err error
var tables storageissueops.ChangedTables
result, tables, err = storageissueops.ExecuteCreate(ctx, tx, snapshot)
return tables, err
})
return result, err
}
func (o *issueOperations) Update(ctx context.Context, request issueops.UpdateRequest) (issueops.UpdateResult, error) {
snapshot := storageissueops.CloneUpdateRequest(request)
var result issueops.UpdateResult
err := o.verifiedUpdate(ctx, snapshot, func() error {
// The message names the issue because that is the one `bd dolt log`
// affordance callers actually grep, and it is what the CLI's own
// per-command commit wrote before updates moved onto this path.
return o.store.runIssueOperationTx(ctx, updateCommitMessage(snapshot.IssueID), func(tx *sql.Tx) (storageissueops.ChangedTables, error) {
var err error
var tables storageissueops.ChangedTables
result, tables, err = storageissueops.ExecuteUpdate(ctx, tx, snapshot)
return tables, err
})
})
return result, err
}
// verifiedUpdate runs a facade update under claim-family verify-after-write
// (bd-zccb9) when the request writes coordination state, and unwrapped
// otherwise. The facade reaches the same writes as ClaimIssue and
// UpdateIssueWithOptions, so under a degraded server its exit status is no more
// trustworthy than theirs. Replay is safe: the claim CAS and the compare-and-set
// guards are re-checked inside the replayed transaction, so a racing writer
// makes the replay refuse rather than clobber.
func (o *issueOperations) verifiedUpdate(ctx context.Context, request issueops.UpdateRequest, write func() error) error {
post, verify := updateClaimPostcondition(request)
if !verify {
return write()
}
return o.store.verifiedClaimWrite(ctx, request.IssueID, post, write)
}
// updateClaimPostcondition derives the row state a facade update must leave
// behind to count as applied, and whether the update is claim-family at all. A
// claim always is; an ordinary update is only when a compare-and-set guard
// authorizes a write to assignee or status. The postcondition describes the
// state the request intends, so a patch that overrides the claim's own
// assignee or status is honored rather than read as a lost write.
//
// A request that also moves the issue across the persistence boundary is
// exempt: the row can legitimately leave the issues table mid-write, which the
// re-read would report as an unverifiable claim.
func updateClaimPostcondition(request issueops.UpdateRequest) (claimPostcondition, bool) {
if request.Patch.Persistence.Set {
return claimPostcondition{}, false
}
updates := map[string]interface{}{}
if request.Patch.Assignee.Set {
updates["assignee"] = request.Patch.Assignee.Value
}
if request.Patch.Status.Set {
updates["status"] = string(request.Patch.Status.Value)
}
if request.Claim {
assignee, status := request.Actor, types.StatusInProgress
if request.Patch.Assignee.Set {
assignee = request.Patch.Assignee.Value
}
if request.Patch.Status.Set {
status = request.Patch.Status.Value
}
return claimedAs(assignee, status), true
}
opts := storage.UpdateIssueOptions{ExpectedAssignee: request.ExpectedAssignee}
if request.ExpectedStatus != nil {
expected := string(*request.ExpectedStatus)
opts.ExpectedStatus = &expected
}
return guardedUpdatePostcondition(opts, updates)
}
func (o *issueOperations) Close(ctx context.Context, request issueops.CloseRequest) (issueops.CloseResult, error) {
snapshot := storageissueops.CloneCloseRequest(request)
var result issueops.CloseResult
err := o.store.runIssueOperationTx(ctx, "bd: close issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) {
var err error
var tables storageissueops.ChangedTables
result, tables, err = storageissueops.ExecuteClose(ctx, tx, snapshot)
return tables, err
})
return result, err
}
func (o *issueOperations) Reopen(ctx context.Context, request issueops.ReopenRequest) (issueops.ReopenResult, error) {
snapshot := storageissueops.CloneReopenRequest(request)
var result issueops.ReopenResult
err := o.store.runIssueOperationTx(ctx, "bd: reopen issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) {
var err error
var tables storageissueops.ChangedTables
result, tables, err = storageissueops.ExecuteReopen(ctx, tx, snapshot)
return tables, err
})
return result, err
}
var _ issueops.Lifecycle = (*issueOperations)(nil)

View file

@ -0,0 +1,640 @@
package dolt
import (
"encoding/json"
"errors"
"reflect"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// TestIssueOperationsGuardedVerbs exercises the public operation adapter against
// a real direct store. Each subtest states a guard which the adapter, rather
// than a caller, must enforce.
func TestIssueOperationsGuardedVerbs(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatalf("NewIssueOperations: %v", err)
}
create := func(t *testing.T, id string) *types.Issue {
t.Helper()
issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed %s: %v", id, err)
}
return issue
}
t.Run("create rejects occupied ID without overwriting", func(t *testing.T) {
create(t, "ops-duplicate")
_, err := operations.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: &types.Issue{ID: "ops-duplicate", Title: "replacement", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}})
if !errors.Is(err, publicops.ErrAlreadyExists) {
t.Fatalf("Create error = %v, want ErrAlreadyExists", err)
}
got, getErr := store.GetIssue(ctx, "ops-duplicate")
if getErr != nil || got.Title != "ops-duplicate" {
t.Fatalf("stored duplicate = %#v, %v; want original title", got, getErr)
}
})
t.Run("create applies aggregate request and validates prefix", func(t *testing.T) {
parent := create(t, "ops-parent")
spawner := create(t, "ops-spawner")
if err := store.AddLabel(ctx, parent.ID, "parent-label", "seed"); err != nil {
t.Fatal(err)
}
target := create(t, "ops-target")
_, err := operations.Create(ctx, publicops.CreateRequest{Actor: "writer", Issue: &types.Issue{ID: "foreign-aggregate", Title: "aggregate", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, ParentID: parent.ID, InheritLabelsFromParent: true, Dependencies: []publicops.CreateDependency{{TargetID: target.ID, Type: types.DepRelated, ThreadID: "thread"}, {TargetID: target.ID, Type: types.DepRelatesTo, Reverse: true, ThreadID: "reverse-thread"}}, WaitsFor: &publicops.WaitsFor{SpawnerID: spawner.ID}})
if !errors.Is(err, publicops.ErrPrefixMismatch) {
t.Fatalf("unforced foreign prefix error = %v, want ErrPrefixMismatch", err)
}
result, err := operations.Create(ctx, publicops.CreateRequest{Actor: "writer", Issue: &types.Issue{ID: "foreign-aggregate", Title: "aggregate", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, ForceIDPrefix: true, ParentID: parent.ID, InheritLabelsFromParent: true, Dependencies: []publicops.CreateDependency{{TargetID: target.ID, Type: types.DepRelated, ThreadID: "thread"}, {TargetID: target.ID, Type: types.DepRelatesTo, Reverse: true, ThreadID: "reverse-thread"}}, WaitsFor: &publicops.WaitsFor{SpawnerID: spawner.ID}})
if err != nil {
t.Fatalf("forced Create: %v", err)
}
if len(result.Issue.Labels) != 1 || result.Issue.Labels[0] != "parent-label" {
t.Fatalf("Create result aggregate = %#v", result.Issue)
}
if len(result.Issue.Dependencies) != 3 {
t.Fatalf("Create dependencies = %#v, want parent, waits-for, and direct edges", result.Issue.Dependencies)
}
inbound, err := store.GetDependentRecords(ctx, result.Issue.ID, "", 10, "")
if err != nil || len(inbound) != 1 || inbound[0].IssueID != target.ID || inbound[0].ThreadID != "reverse-thread" {
t.Fatalf("reverse dependency = %#v, %v", inbound, err)
}
})
t.Run("update enforces CAS claim and patch aggregate", func(t *testing.T) {
issue := create(t, "ops-update")
stale := issue.RowVersion + 1
_, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedVersion: &stale, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must not persist"}}})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("stale Update error = %v, want ErrVersionMismatch", err)
}
claimed, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Claim: true})
if err != nil || !claimed.Changed || claimed.Issue.Assignee != "writer" || claimed.Issue.Status != publicops.StatusInProgress {
t.Fatalf("claim result = %#v, %v", claimed, err)
}
updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{AppendNotes: publicops.Field[string]{Set: true, Value: "note"}, ExternalRef: publicops.Field[*string]{Set: true, Value: stringPtr("external")}, Labels: publicops.LabelPatch{Add: []string{"label"}}, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"key": json.RawMessage(`"value"`)}}, Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: publicops.PersistenceModeEphemeral}}})
if err != nil || !updated.Changed || updated.Issue.ExternalRef == nil || *updated.Issue.ExternalRef != "external" || len(updated.Issue.Labels) != 1 {
t.Fatalf("aggregate update = %#v, %v", updated, err)
}
})
t.Run("update enforces field guards and reports no-op", func(t *testing.T) {
issue := create(t, "ops-field-guards")
expectedAssignee := "other"
_, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expectedAssignee, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}})
if !errors.Is(err, publicops.ErrAssigneeMismatch) {
t.Fatalf("assignee guard error = %v, want ErrAssigneeMismatch", err)
}
noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: issue.Title}}})
if err != nil || noOp.Changed {
t.Fatalf("same-value update = %#v, %v; want unchanged", noOp, err)
}
})
t.Run("update applies metadata patch", func(t *testing.T) {
issue := create(t, "ops-metadata")
updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"answer": json.RawMessage(`42`)}}}})
if err != nil || !updated.Changed || string(updated.Issue.Metadata) != `{"answer":42}` {
t.Fatalf("metadata update = %#v, %v", updated, err)
}
})
t.Run("close and reopen enforce lifecycle guards", func(t *testing.T) {
parent := create(t, "ops-close-parent")
child := create(t, "ops-close-child")
if err := store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil {
t.Fatal(err)
}
stale := parent.RowVersion + 1
_, err := operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, ExpectedVersion: &stale})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("stale Close error = %v, want ErrVersionMismatch", err)
}
_, err = operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID})
if !errors.Is(err, publicops.ErrCloseOpenChildren) {
t.Fatalf("unforced close error = %v, want ErrCloseOpenChildren", err)
}
closed, err := operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, Force: true})
if err != nil || !closed.Changed || closed.OpenChildren != 1 {
t.Fatalf("forced close = %#v, %v", closed, err)
}
stale = closed.Issue.RowVersion + 1
_, err = operations.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: parent.ID, ExpectedVersion: &stale})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("stale Reopen error = %v, want ErrVersionMismatch", err)
}
})
}
func TestIssueOperationsUpdateMetadataPatchOrderingAndReplacementGuard(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatalf("NewIssueOperations: %v", err)
}
issue := &types.Issue{ID: "ops-metadata-order", Title: "metadata", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Metadata: json.RawMessage(`{"keep":"old","remove":"old"}`)}
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{
Merge: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"keep":"merged","merge":true}`)},
Set: map[string]json.RawMessage{"after": json.RawMessage(`"set"`), "keep": json.RawMessage(`"set"`)},
Unset: []string{"keep", "remove"},
}}})
if err != nil || !updated.Changed || !sameMetadataJSON(updated.Issue.Metadata, json.RawMessage(`{"after":"set","merge":true}`)) {
t.Fatalf("ordered metadata update = %#v, %v", updated, err)
}
replaced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{Replace: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"replacement":true}`)}}}})
if err != nil || !replaced.Changed || !sameMetadataJSON(replaced.Issue.Metadata, json.RawMessage(`{"replacement":true}`)) {
t.Fatalf("metadata replacement = %#v, %v", replaced, err)
}
_, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{
Replace: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"replacement":true}`)},
Set: map[string]json.RawMessage{"must_not_persist": json.RawMessage(`true`)},
}}})
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("combined replacement error = %v, want ErrValidation", err)
}
stored, err := store.GetIssue(ctx, issue.ID)
if err != nil || !sameMetadataJSON(stored.Metadata, json.RawMessage(`{"replacement":true}`)) {
t.Fatalf("replacement guard persisted metadata = %#v, %v", stored, err)
}
}
func TestIssueOperationsUpdateLabelPatchOrderingAndNoop(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatalf("NewIssueOperations: %v", err)
}
issue := &types.Issue{ID: "ops-label-order", Title: "labels", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"old", "shared"}}
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
patch := publicops.LabelPatch{Replace: publicops.Field[[]string]{Set: true, Value: []string{"replace", "shared"}}, Add: []string{"add", "shared"}, Remove: []string{"old", "shared"}}
updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Labels: patch}})
if err != nil || !updated.Changed || strings.Join(updated.Issue.Labels, ",") != "add,replace" {
t.Fatalf("ordered labels update = %#v, %v", updated, err)
}
noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Labels: publicops.LabelPatch{Replace: publicops.Field[[]string]{Set: true, Value: []string{"replace", "add"}}, Add: []string{"add"}, Remove: []string{"missing"}}}})
if err != nil || noOp.Changed || strings.Join(noOp.Issue.Labels, ",") != "add,replace" {
t.Fatalf("same labels update = %#v, %v", noOp, err)
}
}
func TestIssueOperationsUpdateParentReplacementClearAndNoop(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatalf("NewIssueOperations: %v", err)
}
create := func(id string) *types.Issue {
issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
return issue
}
parentA, parentB, parentC := create("ops-parent-a"), create("ops-parent-b"), create("ops-parent-c")
child := create("ops-parent-child")
for _, parent := range []*types.Issue{parentA, parentB} {
if err := store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil {
t.Fatal(err)
}
}
replaced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: parentC.ID}}})
if err != nil || !replaced.Changed || issueParentIDs(replaced.Issue) != parentC.ID {
t.Fatalf("parent replacement = %#v, %v", replaced, err)
}
noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: parentC.ID}}})
if err != nil || noOp.Changed || issueParentIDs(noOp.Issue) != parentC.ID {
t.Fatalf("same parent replacement = %#v, %v", noOp, err)
}
cleared, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true}}})
if err != nil || !cleared.Changed || issueParentIDs(cleared.Issue) != "" {
t.Fatalf("parent clear = %#v, %v", cleared, err)
}
noOp, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true}}})
if err != nil || noOp.Changed || issueParentIDs(noOp.Issue) != "" {
t.Fatalf("same parent clear = %#v, %v", noOp, err)
}
}
func TestIssueOperationsUpdateClaimCASAndTransferMatrix(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
create := func(id, assignee string, status types.Status, wisp bool) *types.Issue {
issue := &types.Issue{ID: id, Title: id, Assignee: assignee, Status: status, Priority: 2, IssueType: types.TypeTask, Ephemeral: wisp}
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
return issue
}
t.Run("CAS and claim eligibility", func(t *testing.T) {
issue := create("ops-cas", "owner", types.StatusOpen, false)
stale := issue.RowVersion + 1
_, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedVersion: &stale, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("version error = %v", err)
}
expected, status := "other", publicops.StatusOpen
_, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expected, ExpectedStatus: &status, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}})
if !errors.Is(err, publicops.ErrAssigneeMismatch) {
t.Fatalf("assignee error = %v", err)
}
status = publicops.StatusInProgress
expected = "owner"
_, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expected, ExpectedStatus: &status, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}})
if !errors.Is(err, publicops.ErrStatusMismatch) {
t.Fatalf("status error = %v", err)
}
status = publicops.StatusOpen
matched, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expected, ExpectedStatus: &status, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "matched"}}})
if err != nil || !matched.Changed || matched.Issue.Title != "matched" {
t.Fatalf("matching CAS = %#v, %v", matched, err)
}
claimable := create("ops-claim", "", types.StatusOpen, false)
claimed, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: claimable.ID, Claim: true})
if err != nil || !claimed.Changed {
t.Fatalf("claim = %#v, %v", claimed, err)
}
noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: claimable.ID, Claim: true})
if err != nil || noOp.Changed {
t.Fatalf("same claim = %#v, %v", noOp, err)
}
foreign := create("ops-foreign", "owner", types.StatusOpen, false)
_, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: foreign.ID, Claim: true})
if !errors.Is(err, publicops.ErrAlreadyClaimed) {
t.Fatalf("foreign claim = %v", err)
}
if err := store.SetConfig(ctx, "claim.pools", "crew"); err != nil {
t.Fatal(err)
}
pool := create("ops-pool", "crew", types.StatusOpen, false)
pooled, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: pool.ID, Claim: true})
if err != nil || !pooled.Changed || pooled.Issue.Assignee != "worker" {
t.Fatalf("pool claim = %#v, %v", pooled, err)
}
poolTransfer := create("ops-pool-transfer", "crew", types.StatusInProgress, false)
transferred, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: poolTransfer.ID, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}})
if err != nil || !transferred.Changed || transferred.Issue.Assignee != "next" {
t.Fatalf("pool transfer = %#v, %v", transferred, err)
}
})
t.Run("transfer override validation and wisp", func(t *testing.T) {
foreign := create("ops-transfer", "owner", types.StatusInProgress, false)
_, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: foreign.ID, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}})
if !errors.Is(err, publicops.ErrAlreadyClaimed) {
t.Fatalf("unforced transfer = %v", err)
}
forced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: foreign.ID, ForceAssigneeTransfer: true, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}})
if err != nil || !forced.Changed {
t.Fatalf("forced transfer = %#v, %v", forced, err)
}
expected := "owner"
authorized := create("ops-authorized", "owner", types.StatusInProgress, false)
result, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: authorized.ID, ExpectedAssignee: &expected, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}})
if err != nil || !result.Changed {
t.Fatalf("authorized transfer = %#v, %v", result, err)
}
override := create("ops-override", "", types.StatusOpen, false)
result, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: override.ID, Claim: true, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "reviewer"}, Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusOpen}}})
if err != nil || !result.Changed || result.Issue.Assignee != "reviewer" || result.Issue.Status != publicops.StatusOpen {
t.Fatalf("override = %#v, %v", result, err)
}
wisp := create("ops-wisp", "", types.StatusOpen, true)
wispResult, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: wisp.ID, Claim: true})
if err != nil || !wispResult.Changed {
t.Fatalf("wisp claim = %#v, %v", wispResult, err)
}
expected = ""
for _, request := range []publicops.UpdateRequest{{Actor: "worker", IssueID: override.ID, Claim: true, ExpectedAssignee: &expected}, {Actor: "worker", IssueID: override.ID, Claim: true, ForceAssigneeTransfer: true}, {Actor: "worker", IssueID: override.ID, ForceAssigneeTransfer: true}, {Actor: "worker", IssueID: override.ID, ForceAssigneeTransfer: true, ExpectedAssignee: &expected, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}}} {
_, err := operations.Update(ctx, request)
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("invalid request = %v", err)
}
}
})
}
func TestIssueOperationsLifecycleContractMatrix(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
ops, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
makeIssue := func(id string, status types.Status, wisp bool) *types.Issue {
issue := &types.Issue{ID: id, Title: id, Status: status, Priority: 2, IssueType: types.TypeTask, Ephemeral: wisp}
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
return issue
}
t.Run("close session and reclose", func(t *testing.T) {
issue := makeIssue("ops-life", types.StatusOpen, false)
result, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: issue.ID, Reason: "because", Session: "session-1"})
if err != nil || !result.Changed || result.Issue.ClosedBySession != "session-1" || result.Issue.CloseReason != "because" {
t.Fatalf("first close session=%q reason=%q changed=%t error=%v", result.Issue.ClosedBySession, result.Issue.CloseReason, result.Changed, err)
}
reclose, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: issue.ID})
if err != nil || reclose.Changed {
t.Fatalf("idempotent reclose = %#v, %v; want unchanged", reclose, err)
}
})
t.Run("version force and reopen routes", func(t *testing.T) {
parent, child := makeIssue("ops-life-parent", types.StatusOpen, false), makeIssue("ops-life-child", types.StatusOpen, false)
if err := store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil {
t.Fatal(err)
}
_, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID})
if !errors.Is(err, publicops.ErrCloseOpenChildren) {
t.Fatalf("children refusal = %v", err)
}
forced, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, Force: true})
if err != nil || forced.OpenChildren != 1 {
t.Fatalf("forced close = %#v, %v", forced, err)
}
stale := forced.Issue.RowVersion + 1
_, err = ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, ExpectedVersion: &stale})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("close version = %v", err)
}
opened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: parent.ID})
if err != nil || !opened.Changed || opened.Issue.Status != publicops.StatusOpen {
t.Fatalf("reopen = %#v, %v", opened, err)
}
noOp, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: parent.ID})
if err != nil || noOp.Changed {
t.Fatalf("open reopen = %#v, %v", noOp, err)
}
wisp := makeIssue("ops-life-wisp", types.StatusOpen, true)
closed, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: wisp.ID})
if err != nil || !closed.Changed {
t.Fatalf("wisp close = %#v, %v", closed, err)
}
if _, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: wisp.ID}); err != nil {
t.Fatal(err)
}
})
}
func TestIssueOperationsLifecycleRemainingCausalCases(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
ops, _ := NewIssueOperations(store)
makeIssue := func(id string, status types.Status) *types.Issue {
issue := &types.Issue{ID: id, Title: id, Status: status, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
return issue
}
t.Run("blocker refusal and force leave no partial mutation", func(t *testing.T) {
blocker, target := makeIssue("ops-blocker", types.StatusOpen), makeIssue("ops-blocked", types.StatusOpen)
if err := store.AddDependency(ctx, &types.Dependency{IssueID: target.ID, DependsOnID: blocker.ID, Type: types.DepBlocks}, "seed"); err != nil {
t.Fatal(err)
}
_, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: target.ID})
if !errors.Is(err, publicops.ErrCloseBlocked) {
t.Fatalf("blocker=%v", err)
}
got, _ := store.GetIssue(ctx, target.ID)
if got.Status != types.StatusOpen {
t.Fatalf("refusal mutated=%#v", got)
}
forced, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: target.ID, Force: true})
if err != nil || !forced.Changed {
t.Fatalf("force=%#v,%v", forced, err)
}
})
t.Run("reopen version before non-done noop and custom done", func(t *testing.T) {
open := makeIssue("ops-open", types.StatusOpen)
stale := open.RowVersion + 1
_, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: open.ID, ExpectedVersion: &stale})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("reopen version=%v", err)
}
if err := store.SetConfig(ctx, "status.custom", "archived:done"); err != nil {
t.Fatal(err)
}
custom := makeIssue("ops-custom", types.Status("archived"))
reopened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: custom.ID})
if err != nil || !reopened.Changed || reopened.Issue.Status != types.StatusOpen {
t.Fatalf("custom=%#v,%v", reopened, err)
}
})
}
func issueParentIDs(issue *types.Issue) string {
parents := make([]string, 0)
for _, dependency := range issue.Dependencies {
if dependency.Type == types.DepParentChild {
parents = append(parents, dependency.DependsOnID)
}
}
return strings.Join(parents, ",")
}
func sameMetadataJSON(left, right json.RawMessage) bool {
var leftValue, rightValue any
return json.Unmarshal(left, &leftValue) == nil && json.Unmarshal(right, &rightValue) == nil && reflect.DeepEqual(leftValue, rightValue)
}
func stringPtr(value string) *string { return &value }
func TestIssueOperationsUpdateAllScalarAndPointerFieldsReportChanged(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
ops, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
when := time.Date(2026, 7, 30, 12, 0, 0, 0, time.UTC)
minutes, external := 15, "external"
base := func(id string) *types.Issue {
return &types.Issue{ID: id, Title: "title", Description: "description", Design: "design", AcceptanceCriteria: "criteria", Notes: "notes", SpecID: "spec", AwaitID: "await", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Assignee: "worker", Owner: "owner", ClosedBySession: "session", EstimatedMinutes: &minutes, ExternalRef: &external, DueAt: &when, DeferUntil: &when}
}
cases := []struct {
name string
patch publicops.IssuePatch
check func(*types.Issue) bool
}{
{"title", publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "changed"}}, func(i *types.Issue) bool { return i.Title == "changed" }},
{"description clear", publicops.IssuePatch{Description: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Description == "" }},
{"design clear", publicops.IssuePatch{Design: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Design == "" }},
{"acceptance criteria clear", publicops.IssuePatch{AcceptanceCriteria: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.AcceptanceCriteria == "" }},
{"notes clear", publicops.IssuePatch{Notes: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Notes == "" }},
{"append notes", publicops.IssuePatch{AppendNotes: publicops.Field[string]{Set: true, Value: "later"}}, func(i *types.Issue) bool { return i.Notes == "notes\nlater" }},
{"spec ID clear", publicops.IssuePatch{SpecID: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.SpecID == "" }},
{"await ID clear", publicops.IssuePatch{AwaitID: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.AwaitID == "" }},
{"status", publicops.IssuePatch{Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusInProgress}}, func(i *types.Issue) bool { return i.Status == publicops.StatusInProgress }},
{"priority zero", publicops.IssuePatch{Priority: publicops.Field[int]{Set: true}}, func(i *types.Issue) bool { return i.Priority == 0 }},
{"issue type", publicops.IssuePatch{IssueType: publicops.Field[publicops.IssueType]{Set: true, Value: types.TypeBug}}, func(i *types.Issue) bool { return i.IssueType == types.TypeBug }},
{"assignee clear", publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Assignee == "" }},
{"owner clear", publicops.IssuePatch{Owner: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Owner == "" }},
{"closed by session clear", publicops.IssuePatch{ClosedBySession: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.ClosedBySession == "" }},
{"estimated minutes clear", publicops.IssuePatch{EstimatedMinutes: publicops.Field[*int]{Set: true}}, func(i *types.Issue) bool { return i.EstimatedMinutes == nil }},
{"external ref clear", publicops.IssuePatch{ExternalRef: publicops.Field[*string]{Set: true}}, func(i *types.Issue) bool { return i.ExternalRef == nil }},
{"due at clear", publicops.IssuePatch{DueAt: publicops.Field[*time.Time]{Set: true}}, func(i *types.Issue) bool { return i.DueAt == nil }},
{"defer until clear", publicops.IssuePatch{DeferUntil: publicops.Field[*time.Time]{Set: true}}, func(i *types.Issue) bool { return i.DeferUntil == nil }},
}
for n, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
issue := base("ops-scalars-" + tc.name)
issue.ID = strings.ReplaceAll(issue.ID, " ", "-")
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
result, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: tc.patch})
if err != nil || !result.Changed || !tc.check(result.Issue) {
t.Fatalf("Update(%s) = %#v, %v", tc.name, result, err)
}
stored, err := store.GetIssue(ctx, issue.ID)
if err != nil || !tc.check(stored) {
t.Fatalf("stored %s = %#v, %v", tc.name, stored, err)
}
if tc.name != "append notes" {
noOp, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: tc.patch})
if err != nil || noOp.Changed {
t.Fatalf("same-value %s = %#v, %v", tc.name, noOp, err)
}
after, err := store.GetIssue(ctx, issue.ID)
if err != nil || after.RowVersion != stored.RowVersion {
t.Fatalf("same-value %s wrote row version %d -> %d, %v", tc.name, stored.RowVersion, after.RowVersion, err)
}
}
_ = n
})
}
issue := base("ops-notes-conflict")
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
_, err = ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must rollback"}, Notes: publicops.Field[string]{Set: true, Value: "replace"}, AppendNotes: publicops.Field[string]{Set: true, Value: "append"}}})
if err == nil {
t.Fatal("Notes plus AppendNotes succeeded")
}
stored, err := store.GetIssue(ctx, issue.ID)
if err != nil || stored.Title != "title" || stored.Notes != "notes" {
t.Fatalf("notes conflict persisted %#v, %v", stored, err)
}
}
func TestIssueOperationsUpdatePersistenceContributionAndRollback(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
ops, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
for _, transition := range []struct {
from, to publicops.PersistenceMode
}{
{publicops.PersistenceModePersistent, publicops.PersistenceModeEphemeral}, {publicops.PersistenceModeEphemeral, publicops.PersistenceModeNoHistory}, {publicops.PersistenceModeNoHistory, publicops.PersistenceModePersistent},
} {
id := "ops-persistence-" + string(transition.from) + "-" + string(transition.to)
ephemeral := transition.from == publicops.PersistenceModeEphemeral
noHistory := transition.from == publicops.PersistenceModeNoHistory
if err := store.CreateIssue(ctx, &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: ephemeral, NoHistory: noHistory}, "seed"); err != nil {
t.Fatal(err)
}
result, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: transition.to}}})
if err != nil || !result.Changed || result.Issue.Ephemeral != (transition.to == publicops.PersistenceModeEphemeral) || result.Issue.NoHistory != (transition.to == publicops.PersistenceModeNoHistory) {
t.Fatalf("transition %s->%s = %#v, %v", transition.from, transition.to, result, err)
}
noOp, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: transition.to}}})
if err != nil || noOp.Changed {
t.Fatalf("same persistence %s = %#v, %v", transition.to, noOp, err)
}
}
unversioned := &types.Issue{ID: "ops-persistence-rollback", Title: "original", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, StorageClass: types.StorageClassUnversioned, Labels: []string{"keep"}, Metadata: json.RawMessage(`{"keep":true}`)}
if err := store.CreateIssue(ctx, unversioned, "seed"); err != nil {
t.Fatal(err)
}
_, err = ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: unversioned.ID, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must rollback"}, Labels: publicops.LabelPatch{Add: []string{"must-rollback"}}, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"must_rollback": json.RawMessage(`true`)}}, Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: publicops.PersistenceModeEphemeral}}})
if err == nil {
t.Fatal("unversioned demotion succeeded")
}
stored, err := store.GetIssue(ctx, unversioned.ID)
if err != nil || stored.Title != "original" || strings.Join(stored.Labels, ",") != "keep" || !sameMetadataJSON(stored.Metadata, json.RawMessage(`{"keep":true}`)) || stored.Ephemeral || stored.NoHistory {
t.Fatalf("failed demotion left state %#v, %v", stored, err)
}
}
func TestIssueOperationsWispAggregateLifecycleAndResultDetachment(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
ops, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
external := "external"
wisp := &types.Issue{ID: "ops-wisp-detached", Title: "wisp", Notes: "before", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true, Labels: []string{"keep"}, Metadata: json.RawMessage(`{"keep":true}`), ExternalRef: &external}
if err := store.CreateIssue(ctx, wisp, "seed"); err != nil {
t.Fatal(err)
}
updated, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: wisp.ID, Patch: publicops.IssuePatch{AppendNotes: publicops.Field[string]{Set: true, Value: "after"}, Labels: publicops.LabelPatch{Add: []string{"added"}}, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"added": json.RawMessage(`true`)}}}})
if err != nil || !updated.Changed || updated.Issue.Notes != "before\nafter" || strings.Join(updated.Issue.Labels, ",") != "added,keep" {
t.Fatalf("wisp update = %#v, %v", updated, err)
}
updated.Issue.Labels[0], updated.Issue.Metadata[2], *updated.Issue.ExternalRef = "corrupt", 'X', "corrupt"
stored, err := store.GetIssue(ctx, wisp.ID)
if err != nil || strings.Join(stored.Labels, ",") != "added,keep" || !sameMetadataJSON(stored.Metadata, json.RawMessage(`{"added":true,"keep":true}`)) || stored.ExternalRef == nil || *stored.ExternalRef != "external" {
t.Fatalf("update result aliases store %#v, %v", stored, err)
}
closed, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: wisp.ID})
if err != nil || !closed.Changed || closed.Issue.Status != publicops.StatusClosed {
t.Fatalf("wisp close = %#v, %v", closed, err)
}
closed.Issue.Metadata[2] = 'X'
reopened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: wisp.ID})
if err != nil || !reopened.Changed || reopened.Issue.Status != publicops.StatusOpen {
t.Fatalf("wisp reopen = %#v, %v", reopened, err)
}
reopened.Issue.Labels[0] = "corrupt"
stored, err = store.GetIssue(ctx, wisp.ID)
if err != nil || strings.Join(stored.Labels, ",") != "added,keep" || !sameMetadataJSON(stored.Metadata, json.RawMessage(`{"added":true,"keep":true}`)) {
t.Fatalf("lifecycle result aliases store %#v, %v", stored, err)
}
}

View file

@ -0,0 +1,197 @@
package dolt
import (
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// The public facade reaches the same coordination-critical writes the store's
// own ClaimIssue/UpdateIssue do, so it needs the same verify-after-write
// resolution (bd-zccb9). Failure injection happens at the write-func seam,
// matching claim_verify_test.go.
// TestIssueOperationsClaimVerifyPostcondition pins which facade updates are
// claim-family and what state each one must leave behind.
func TestIssueOperationsClaimVerifyPostcondition(t *testing.T) {
assignee := func(v string) *string { return &v }
status := func(v types.Status) *types.Status { return &v }
cases := []struct {
name string
request publicops.UpdateRequest
wantVerified bool
wantDesc string
holds [][2]string // assignee, status pairs the postcondition accepts
rejects [][2]string
}{
{
name: "bare claim",
request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", Claim: true},
wantVerified: true,
wantDesc: `assignee="alice" status="in_progress"`,
holds: [][2]string{{"alice", "in_progress"}},
rejects: [][2]string{{"", "open"}, {"bob", "in_progress"}, {"alice", "open"}},
},
{
name: "claim with overriding status patch",
request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", Claim: true, Patch: publicops.IssuePatch{
Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusBlocked},
}},
wantVerified: true,
wantDesc: `assignee="alice" status="blocked"`,
holds: [][2]string{{"alice", "blocked"}},
rejects: [][2]string{{"alice", "in_progress"}},
},
{
name: "claim with overriding assignee patch",
request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", Claim: true, Patch: publicops.IssuePatch{
Assignee: publicops.Field[string]{Set: true, Value: "dispatcher"},
}},
wantVerified: true,
wantDesc: `assignee="dispatcher" status="in_progress"`,
holds: [][2]string{{"dispatcher", "in_progress"}},
rejects: [][2]string{{"alice", "in_progress"}},
},
{
name: "claim that moves the issue to a wisp is not verified",
request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", Claim: true, Patch: publicops.IssuePatch{
Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: publicops.PersistenceModeEphemeral},
}},
},
{
name: "guarded assignee transfer",
request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", ExpectedAssignee: assignee("bob"), Patch: publicops.IssuePatch{
Assignee: publicops.Field[string]{Set: true, Value: "carol"},
}},
wantVerified: true,
wantDesc: `assignee="carol"`,
holds: [][2]string{{"carol", "open"}, {"carol", "in_progress"}},
rejects: [][2]string{{"bob", "open"}},
},
{
name: "guarded status write",
request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", ExpectedStatus: status(types.StatusOpen), Patch: publicops.IssuePatch{
Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusInProgress},
}},
wantVerified: true,
wantDesc: `status="in_progress"`,
holds: [][2]string{{"", "in_progress"}, {"bob", "in_progress"}},
rejects: [][2]string{{"", "open"}},
},
{
name: "guarded edit of ordinary fields is not claim-family",
request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", ExpectedStatus: status(types.StatusOpen), Patch: publicops.IssuePatch{
Title: publicops.Field[string]{Set: true, Value: "new title"},
}},
},
{
name: "unguarded ordinary update is not claim-family",
request: publicops.UpdateRequest{Actor: "alice", IssueID: "bd-1", Patch: publicops.IssuePatch{
Assignee: publicops.Field[string]{Set: true, Value: "carol"},
}},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
post, verified := updateClaimPostcondition(tc.request)
if verified != tc.wantVerified {
t.Fatalf("updateClaimPostcondition verified = %v, want %v", verified, tc.wantVerified)
}
if !verified {
return
}
if post.desc != tc.wantDesc {
t.Errorf("postcondition desc = %q, want %q", post.desc, tc.wantDesc)
}
for _, state := range tc.holds {
if !post.want(state[0], types.Status(state[1])) {
t.Errorf("postcondition rejected accepted state assignee=%q status=%q", state[0], state[1])
}
}
for _, state := range tc.rejects {
if post.want(state[0], types.Status(state[1])) {
t.Errorf("postcondition accepted lost state assignee=%q status=%q", state[0], state[1])
}
}
})
}
}
// TestIssueOperationsClaimVerifyFailsLoudlyOnLostFacadeClaim: a facade claim
// whose transaction reports success without landing must fail loudly, exactly
// like the store's own ClaimIssue. A silent phantom claim through the facade
// costs the same duplicated implementation the incident did.
func TestIssueOperationsClaimVerifyFailsLoudlyOnLostFacadeClaim(t *testing.T) {
s, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
id := claimVerifyTestIssue(t, s)
operations := &issueOperations{store: s}
err := operations.verifiedUpdate(ctx, publicops.UpdateRequest{Actor: "alice", IssueID: id, Claim: true}, func() error {
return nil // lie: report success without writing anything
})
if err == nil {
t.Fatal("expected loud failure for a success-reported-but-lost facade claim, got nil")
}
if !strings.Contains(err.Error(), "did not land") {
t.Fatalf("error should say the claim did not land, got: %v", err)
}
}
// TestIssueOperationsClaimVerifyLeavesOrdinaryUpdatesUnwrapped: an update that
// is not claim-family keeps its exit status. A lost label or notes edit is an
// annoyance, not a phantom claim, and re-reading every update would cost a
// round trip per write.
func TestIssueOperationsClaimVerifyLeavesOrdinaryUpdatesUnwrapped(t *testing.T) {
s, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
id := claimVerifyTestIssue(t, s)
operations := &issueOperations{store: s}
request := publicops.UpdateRequest{Actor: "alice", IssueID: id, Patch: publicops.IssuePatch{
Title: publicops.Field[string]{Set: true, Value: "retitled"},
}}
if err := operations.verifiedUpdate(ctx, request, func() error { return nil }); err != nil {
t.Fatalf("ordinary update must keep its exit status, got: %v", err)
}
}
// TestIssueOperationsClaimVerifyPassesHealthyFacadeClaim: the verify layer does
// not disturb a claim that actually lands.
func TestIssueOperationsClaimVerifyPassesHealthyFacadeClaim(t *testing.T) {
s, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
id := claimVerifyTestIssue(t, s)
operations, err := NewIssueOperations(s)
if err != nil {
t.Fatalf("NewIssueOperations: %v", err)
}
result, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "alice", IssueID: id, Claim: true})
if err != nil {
t.Fatalf("facade claim: %v", err)
}
if !result.Changed || result.Issue.Assignee != "alice" || result.Issue.Status != types.StatusInProgress {
t.Fatalf("facade claim result = %#v", result)
}
assignee, status, err := s.readClaimState(ctx, id)
if err != nil {
t.Fatalf("read claim state: %v", err)
}
if assignee != "alice" || status != types.StatusInProgress {
t.Fatalf("post-claim state: assignee=%q status=%q", assignee, status)
}
}

View file

@ -0,0 +1,51 @@
package dolt
import (
"context"
"testing"
"github.com/steveyegge/beads/internal/storage/conformance"
)
func TestIssueOperationsCreateRoutesInfraTypesToWisps(t *testing.T) {
fixture, ctx, cleanup := newDoltIssueOperationsFixture(t)
defer cleanup()
conformance.RunIssueOperationsCreateRoutesInfraTypesToWisps(t, ctx, fixture)
}
func TestIssueOperationsCreateRejectsMissingDependencyTargets(t *testing.T) {
fixture, ctx, cleanup := newDoltIssueOperationsFixture(t)
defer cleanup()
conformance.RunIssueOperationsCreateRejectsMissingDependencyTargets(t, ctx, fixture)
}
func TestIssueOperationsUpdateFoldsMetadataIntoOneEvent(t *testing.T) {
fixture, ctx, cleanup := newDoltIssueOperationsFixture(t)
defer cleanup()
conformance.RunIssueOperationsUpdateFoldsMetadataIntoOneEvent(t, ctx, fixture)
}
func newDoltIssueOperationsFixture(t *testing.T) (conformance.IssueOperationsStagingFixture, context.Context, func()) {
t.Helper()
store, storeCleanup := setupTestStore(t)
ctx, cancel := testContext(t)
operations, err := NewIssueOperations(store)
if err != nil {
cancel()
storeCleanup()
t.Fatalf("NewIssueOperations: %v", err)
}
fixture := conformance.IssueOperationsStagingFixture{
IssuePrefix: "test",
Operations: operations,
CreateIssue: store.CreateIssue,
SetConfig: store.SetConfig,
QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error {
return store.db.QueryRowContext(ctx, query, args...).Scan(dest...)
},
}
return fixture, ctx, func() {
cancel()
storeCleanup()
}
}

View file

@ -0,0 +1,303 @@
package dolt
import (
"context"
"database/sql"
"testing"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
)
func TestMoveIssuePersistenceInTxMovesAggregateAndReportsTables(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-move", Title: "move", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"label"}}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if _, err := store.AddIssueComment(ctx, issue.ID, "tester", "comment"); err != nil {
t.Fatal(err)
}
depender := &types.Issue{ID: "persist-depender", Title: "depender", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, depender, "tester"); err != nil {
t.Fatal(err)
}
if err := store.AddDependency(ctx, &types.Dependency{IssueID: depender.ID, DependsOnID: issue.ID, Type: types.DepBlocks}, "tester"); err != nil {
t.Fatal(err)
}
if _, err := store.db.ExecContext(ctx, `INSERT INTO child_counters (parent_id, last_child) VALUES (?, ?)`, issue.ID, 4); err != nil {
t.Fatal(err)
}
var moved issueops.PersistenceMoveResult
if err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
moved, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral)
return err
}); err != nil {
t.Fatal(err)
}
if !moved.Changed || !moved.ChangedTables["issues"] || !moved.ChangedTables["wisps"] || !moved.ChangedTables["wisp_comments"] || !moved.ChangedTables["wisp_labels"] || !moved.ChangedTables["dependencies"] {
t.Fatalf("move result = %#v, want changed aggregate tables", moved)
}
got, err := store.GetIssue(ctx, issue.ID)
if err != nil {
t.Fatal(err)
}
if !got.Ephemeral || got.NoHistory || len(got.Labels) != 1 || got.Labels[0] != "label" {
t.Fatalf("moved issue = %#v", got)
}
comments, err := store.GetIssueComments(ctx, issue.ID)
if err != nil {
t.Fatal(err)
}
if len(comments) != 1 || comments[0].Text != "comment" {
t.Fatalf("comments = %#v", comments)
}
var durableTarget, wispTarget *string
if err := store.db.QueryRowContext(ctx, `SELECT depends_on_issue_id, depends_on_wisp_id FROM dependencies WHERE issue_id = ?`, depender.ID).Scan(&durableTarget, &wispTarget); err != nil {
t.Fatal(err)
}
if durableTarget != nil || wispTarget == nil || *wispTarget != issue.ID {
t.Fatalf("inbound target = (%v,%v), want (nil,%q)", durableTarget, wispTarget, issue.ID)
}
var sourceEvents, targetEvents, sourceCounters, targetCounters int
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM events WHERE issue_id = ?`, issue.ID).Scan(&sourceEvents); err != nil {
t.Fatal(err)
}
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM wisp_events WHERE issue_id = ?`, issue.ID).Scan(&targetEvents); err != nil {
t.Fatal(err)
}
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM child_counters WHERE parent_id = ?`, issue.ID).Scan(&sourceCounters); err != nil {
t.Fatal(err)
}
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM wisp_child_counters WHERE parent_id = ? AND last_child = 4`, issue.ID).Scan(&targetCounters); err != nil {
t.Fatal(err)
}
if sourceEvents != 0 || targetEvents == 0 || sourceCounters != 0 || targetCounters != 1 {
t.Fatalf("moved event/counter rows = events(%d,%d) counters(%d,%d)", sourceEvents, targetEvents, sourceCounters, targetCounters)
}
}
func TestMoveIssuePersistenceInTxSameModeIsNoop(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-noop", Title: "noop", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
result, err := issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModePersistent)
if err != nil {
return err
}
if result.Changed {
t.Fatal("same persistence mode changed issue")
}
return nil
}); err != nil {
t.Fatal(err)
}
}
func TestMoveIssuePersistenceInTxTransitions(t *testing.T) {
for _, transition := range []struct {
name string
from types.PersistenceMode
to types.PersistenceMode
}{
{"persistent-to-ephemeral", types.PersistenceModePersistent, types.PersistenceModeEphemeral},
{"persistent-to-no-history", types.PersistenceModePersistent, types.PersistenceModeNoHistory},
{"ephemeral-to-persistent", types.PersistenceModeEphemeral, types.PersistenceModePersistent},
{"ephemeral-to-no-history", types.PersistenceModeEphemeral, types.PersistenceModeNoHistory},
{"no-history-to-persistent", types.PersistenceModeNoHistory, types.PersistenceModePersistent},
{"no-history-to-ephemeral", types.PersistenceModeNoHistory, types.PersistenceModeEphemeral},
} {
t.Run(transition.name, func(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
ephemeral, noHistory, _, err := types.NormalizePersistenceMode(types.Issue{}, transition.from)
if err != nil {
t.Fatal(err)
}
issue := &types.Issue{ID: "transition-" + transition.name, Title: transition.name, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: ephemeral, NoHistory: noHistory}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, transition.to)
return err
}); err != nil {
t.Fatal(err)
}
got, err := store.GetIssue(ctx, issue.ID)
if err != nil {
t.Fatal(err)
}
wantEphemeral, wantNoHistory, _, err := types.NormalizePersistenceMode(types.Issue{Ephemeral: ephemeral, NoHistory: noHistory}, transition.to)
if err != nil {
t.Fatal(err)
}
if got.Ephemeral != wantEphemeral || got.NoHistory != wantNoHistory {
t.Fatalf("persistence = (%t,%t), want (%t,%t)", got.Ephemeral, got.NoHistory, wantEphemeral, wantNoHistory)
}
})
}
}
func TestMoveIssuePersistenceInTxRefusesUnversionedDemotion(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "unversioned", Title: "unversioned", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, StorageClass: types.StorageClassUnversioned}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral)
return err
})
if err == nil {
t.Fatal("unversioned demotion succeeded")
}
got, err := store.GetIssue(ctx, issue.ID)
if err != nil || got.Ephemeral || got.NoHistory {
t.Fatalf("refusal state = %#v, %v", got, err)
}
}
func TestMoveIssuePersistenceInTxDeletesLeaseOnDemotion(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-lease", Title: "lease", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if err := store.ClaimIssue(ctx, issue.ID, "tester"); err != nil {
t.Fatal(err)
}
var before int
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM leases WHERE issue_id = ?`, issue.ID).Scan(&before); err != nil || before != 1 {
t.Fatalf("lease before move = %d, %v", before, err)
}
if err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral)
return err
}); err != nil {
t.Fatal(err)
}
var after int
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM leases WHERE issue_id = ?`, issue.ID).Scan(&after); err != nil || after != 0 {
t.Fatalf("lease after demotion = %d, %v", after, err)
}
}
func TestMoveIssuePersistenceInTxTargetCollisionRollsBackSource(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-collision", Title: "source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"source-label"}}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if _, err := store.db.ExecContext(ctx, `INSERT INTO wisps (id, title, description, design, acceptance_criteria, notes, status, priority, issue_type, ephemeral, is_blocked) VALUES (?, ?, '', '', '', '', ?, ?, ?, ?, ?)`, issue.ID, "target", types.StatusOpen, 2, types.TypeTask, true, 0); err != nil {
t.Fatal(err)
}
err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral)
return err
})
if err == nil {
t.Fatal("move into occupied target succeeded")
}
var sourceLabels int
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM labels WHERE issue_id = ? AND label = 'source-label'`, issue.ID).Scan(&sourceLabels); err != nil {
t.Fatal(err)
}
if sourceLabels != 1 {
t.Fatalf("source aggregate was not rolled back; labels = %d", sourceLabels)
}
}
func TestMoveIssuePersistenceInTxLateCounterConflictRollsBack(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-late-rollback", Title: "source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"source-label"}}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if _, err := store.AddIssueComment(ctx, issue.ID, "tester", "source comment"); err != nil {
t.Fatal(err)
}
if _, err := store.db.ExecContext(ctx, `INSERT INTO child_counters (parent_id, last_child) VALUES (?, ?)`, issue.ID, 3); err != nil {
t.Fatal(err)
}
// wisp_child_counters deliberately allows orphaned rows while a target wisp
// is absent. This duplicate is reached after the target issue, labels,
// comments, and events have been inserted, so it proves transaction rollback.
if _, err := store.db.ExecContext(ctx, `SET FOREIGN_KEY_CHECKS = 0`); err != nil {
t.Fatal(err)
}
if _, err := store.db.ExecContext(ctx, `INSERT INTO wisp_child_counters (parent_id, last_child) VALUES (?, ?)`, issue.ID, 9); err != nil {
t.Fatal(err)
}
if _, err := store.db.ExecContext(ctx, `SET FOREIGN_KEY_CHECKS = 1`); err != nil {
t.Fatal(err)
}
err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral)
return err
})
if err == nil {
t.Fatal("late child-counter conflict did not fail move")
}
var sourceIssue, targetIssue, sourceLabels, sourceComments, targetLabels, targetComments, sourceCounter, targetCounter int
for _, check := range []struct {
query string
dest *int
}{
{`SELECT COUNT(*) FROM issues WHERE id = ?`, &sourceIssue}, {`SELECT COUNT(*) FROM wisps WHERE id = ?`, &targetIssue},
{`SELECT COUNT(*) FROM labels WHERE issue_id = ?`, &sourceLabels}, {`SELECT COUNT(*) FROM comments WHERE issue_id = ?`, &sourceComments},
{`SELECT COUNT(*) FROM wisp_labels WHERE issue_id = ?`, &targetLabels}, {`SELECT COUNT(*) FROM wisp_comments WHERE issue_id = ?`, &targetComments},
{`SELECT COUNT(*) FROM child_counters WHERE parent_id = ? AND last_child = 3`, &sourceCounter}, {`SELECT COUNT(*) FROM wisp_child_counters WHERE parent_id = ? AND last_child = 9`, &targetCounter},
} {
if err := store.db.QueryRowContext(ctx, check.query, issue.ID).Scan(check.dest); err != nil {
t.Fatal(err)
}
}
if sourceIssue != 1 || targetIssue != 0 || sourceLabels != 1 || sourceComments != 1 || targetLabels != 0 || targetComments != 0 || sourceCounter != 1 || targetCounter != 1 {
t.Fatalf("rollback state issues(%d,%d) labels(%d,%d) comments(%d,%d) counters(%d,%d)", sourceIssue, targetIssue, sourceLabels, targetLabels, sourceComments, targetComments, sourceCounter, targetCounter)
}
}

View file

@ -0,0 +1,449 @@
package dolt
import (
"context"
"errors"
"testing"
"time"
"github.com/steveyegge/beads/internal/storage/conformance"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
func TestIssueOperationsCreateIgnoresDerivedFieldsAndRejectsMalformedAggregate(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
created, err := operations.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: &types.Issue{ID: "ops-staging-create", Title: "create", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, RowVersion: 91, LeaseExpiresAt: &now, ContentHash: "derived"}})
if err != nil {
t.Fatal(err)
}
if created.Issue.RowVersion == 91 || created.Issue.LeaseExpiresAt != nil || created.Issue.ContentHash == "derived" {
t.Fatalf("derived fields persisted: %#v", created.Issue)
}
_, err = operations.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: &types.Issue{ID: "ops-staging-invalid-create", Title: "invalid", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, Dependencies: []publicops.CreateDependency{{TargetID: "ops-staging-invalid-create", Type: types.DepBlocks}}})
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("malformed aggregate error = %v, want ErrValidation", err)
}
if _, err := store.GetIssue(ctx, "ops-staging-invalid-create"); !errors.Is(err, publicops.ErrNotFound) {
t.Fatalf("malformed aggregate persisted issue: %v", err)
}
}
func TestIssueOperationsCreateEmptyIDUsesChildIDAndStagesCounter(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
parent := &types.Issue{ID: "ops-staging-create-parent", Title: "parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic}
if err := store.CreateIssue(ctx, parent, "seed"); err != nil {
t.Fatal(err)
}
create := func(title string) *types.Issue {
t.Helper()
result, err := operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
ForceIDPrefix: true,
Issue: &types.Issue{Title: title, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
ParentID: parent.ID,
})
if err != nil {
t.Fatalf("Create(%q): %v", title, err)
}
return result.Issue
}
first := create("first child")
if first.ID != parent.ID+".1" {
t.Fatalf("first child ID = %q, want %q", first.ID, parent.ID+".1")
}
if !hasIssueOperationDependency(first.Dependencies, first.ID, parent.ID, types.DepParentChild, "{}", "") {
t.Fatalf("first child dependencies = %#v, want parent edge", first.Dependencies)
}
var counter int
if err := store.db.QueryRowContext(ctx, "SELECT last_child FROM child_counters AS OF 'HEAD' WHERE parent_id = ?", parent.ID).Scan(&counter); err != nil || counter != 1 {
t.Fatalf("committed first child counter = %d, %v; want 1", counter, err)
}
second := create("second child")
if second.ID != parent.ID+".2" {
t.Fatalf("second child ID = %q, want %q", second.ID, parent.ID+".2")
}
if err := store.db.QueryRowContext(ctx, "SELECT last_child FROM child_counters AS OF 'HEAD' WHERE parent_id = ?", parent.ID).Scan(&counter); err != nil || counter != 2 {
t.Fatalf("committed second child counter = %d, %v; want 2", counter, err)
}
}
func TestIssueOperationsCreateEmptyIDPersistsReverseDependenciesInSourceTier(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
durableSource := &types.Issue{ID: "test-staging-durable-source", Title: "durable source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
wispSource := &types.Issue{ID: "test-staging-wisp-source", Title: "wisp source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true}
for _, issue := range []*types.Issue{durableSource, wispSource} {
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
}
t.Run("durable source points at generated wisp", func(t *testing.T) {
result, err := operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
ForceIDPrefix: true,
Issue: &types.Issue{Title: "generated wisp", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true},
Dependencies: []publicops.CreateDependency{{TargetID: durableSource.ID, Type: types.DepBlocks, Reverse: true, Metadata: `{"direction":"durable"}`, ThreadID: "durable-thread"}},
})
if err != nil {
t.Fatal(err)
}
if result.Issue.ID == "" {
t.Fatal("generated wisp ID is empty")
}
var metadata, threadID string
if err := store.db.QueryRowContext(ctx, "SELECT metadata, thread_id FROM dependencies WHERE issue_id = ? AND depends_on_wisp_id = ?", durableSource.ID, result.Issue.ID).Scan(&metadata, &threadID); err != nil || metadata != `{"direction":"durable"}` || threadID != "durable-thread" {
t.Fatalf("durable dependency = metadata %q, thread %q, err %v", metadata, threadID, err)
}
if blocked, _, err := store.IsBlocked(ctx, durableSource.ID); err != nil || !blocked {
t.Fatalf("durable source blocked = %t, %v; want true", blocked, err)
}
})
t.Run("wisp source points at generated durable issue", func(t *testing.T) {
result, err := operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
ForceIDPrefix: true,
Issue: &types.Issue{Title: "generated durable", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
Dependencies: []publicops.CreateDependency{{TargetID: wispSource.ID, Type: types.DepBlocks, Reverse: true, Metadata: `{"direction":"wisp"}`, ThreadID: "wisp-thread"}},
})
if err != nil {
t.Fatal(err)
}
if result.Issue.ID == "" {
t.Fatal("generated durable issue ID is empty")
}
var metadata, threadID string
if err := store.db.QueryRowContext(ctx, "SELECT metadata, thread_id FROM wisp_dependencies WHERE issue_id = ? AND depends_on_issue_id = ?", wispSource.ID, result.Issue.ID).Scan(&metadata, &threadID); err != nil || metadata != `{"direction":"wisp"}` || threadID != "wisp-thread" {
t.Fatalf("wisp dependency = metadata %q, thread %q, err %v", metadata, threadID, err)
}
if blocked, _, err := store.IsBlocked(ctx, wispSource.ID); err != nil || !blocked {
t.Fatalf("wisp source blocked = %t, %v; want true", blocked, err)
}
})
}
func TestIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
conformance.RunIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t, ctx, conformance.IssueOperationsStagingFixture{
IssuePrefix: "test",
Operations: operations,
CreateIssue: store.CreateIssue,
Commit: store.Commit,
Exec: func(ctx context.Context, query string, args ...any) error {
_, err := store.db.ExecContext(ctx, query, args...)
return err
},
QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error {
return store.db.QueryRowContext(ctx, query, args...).Scan(dest...)
},
})
}
func TestIssueOperationsCreateParentChildRecomputesWaitsForClosure(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
conformance.RunIssueOperationsCreateParentChildRecomputesWaitsForClosure(t, ctx, conformance.IssueOperationsStagingFixture{
IssuePrefix: "test",
Operations: operations,
CreateIssue: store.CreateIssue,
AddDependency: store.AddDependency,
GetReadyWork: store.GetReadyWork,
Commit: store.Commit,
QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error {
return store.db.QueryRowContext(ctx, query, args...).Scan(dest...)
},
})
}
func hasIssueOperationDependency(dependencies []*types.Dependency, issueID, dependsOnID string, dependencyType types.DependencyType, metadata, threadID string) bool {
for _, dependency := range dependencies {
if dependency != nil && dependency.IssueID == issueID && dependency.DependsOnID == dependsOnID && dependency.Type == dependencyType && dependency.Metadata == metadata && dependency.ThreadID == threadID {
return true
}
}
return false
}
func TestIssueOperationsReopenWispStagesOnlyConcreteDurableChanges(t *testing.T) {
newStore := func(t *testing.T) (*DoltStore, context.Context) {
t.Helper()
store, cleanup := setupTestStore(t)
t.Cleanup(cleanup)
ctx, cancel := testContext(t)
t.Cleanup(cancel)
return store, ctx
}
t.Run("isolated wisp leaves dirty durable rows uncommitted", func(t *testing.T) {
store, ctx := newStore(t)
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
createPerm(t, ctx, store, "ops-staging-reopen-dirty")
createWisp(t, ctx, store, "ops-staging-reopen-wisp")
if err := store.CloseIssue(ctx, "ops-staging-reopen-wisp", "done", "tester", ""); err != nil {
t.Fatal(err)
}
before := reopenDoltHead(t, ctx, store)
stageReopenDirtyIssue(t, ctx, store, "ops-staging-reopen-dirty")
stageReopenDirtyEvent(t, ctx, store, "ops-staging-reopen-event", "ops-staging-reopen-dirty")
if _, err := operations.Reopen(ctx, publicops.ReopenRequest{Actor: "tester", IssueID: "ops-staging-reopen-wisp"}); err != nil {
t.Fatal(err)
}
if after := reopenDoltHead(t, ctx, store); after != before {
t.Fatalf("isolated adapter reopen changed HEAD from %s to %s", before, after)
}
assertReopenDirtyRowsUncommitted(t, ctx, store, "ops-staging-reopen-dirty", "ops-staging-reopen-event")
})
t.Run("durable recompute stages issues only", func(t *testing.T) {
store, ctx := newStore(t)
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
createPerm(t, ctx, store, "ops-staging-reopen-depender")
createWisp(t, ctx, store, "ops-staging-reopen-flip")
if err := store.AddDependency(ctx, &types.Dependency{IssueID: "ops-staging-reopen-depender", DependsOnID: "ops-staging-reopen-flip", Type: types.DepBlocks}, "tester"); err != nil {
t.Fatal(err)
}
if err := store.CloseIssue(ctx, "ops-staging-reopen-flip", "done", "tester", ""); err != nil {
t.Fatal(err)
}
commitReopenIssueWorkingSet(t, ctx, store, "seed closed wisp")
before := reopenDoltHead(t, ctx, store)
stageReopenDirtyEvent(t, ctx, store, "ops-staging-reopen-flip-event", "ops-staging-reopen-depender")
if _, err := operations.Reopen(ctx, publicops.ReopenRequest{Actor: "tester", IssueID: "ops-staging-reopen-flip"}); err != nil {
t.Fatal(err)
}
if after := reopenDoltHead(t, ctx, store); after == before {
t.Fatal("durable recompute did not advance HEAD")
}
var blocked bool
if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", "ops-staging-reopen-depender").Scan(&blocked); err != nil || !blocked {
t.Fatalf("committed durable recompute = %t, %v", blocked, err)
}
// events is dolt_ignored since migration 0062 (bd-red8u): the unrelated
// audit row has no HEAD state and cannot ride the issues commit, but it
// must survive it in the working set. assertEventsNotCommitted keeps the
// plane invariant pinned here, where the recompute does advance HEAD.
var events int
if err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE id = ?", "ops-staging-reopen-flip-event").Scan(&events); err != nil || events != 1 {
t.Fatalf("unrelated working-set event = %d, %v", events, err)
}
assertEventsNotCommitted(ctx, t, store.db)
})
}
func TestIssueOperationsUpdateClaimPatchAppliesAfterClaim(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
issue := &types.Issue{ID: "ops-staging-claim-patch", Title: "claim patch", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
result, err := operations.Update(ctx, publicops.UpdateRequest{
Actor: "worker",
IssueID: issue.ID,
Claim: true,
Patch: publicops.IssuePatch{
Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusOpen},
Assignee: publicops.Field[string]{Set: true},
},
})
if err != nil {
t.Fatal(err)
}
if !result.Changed || result.Issue.Status != publicops.StatusOpen || result.Issue.Assignee != "" {
t.Fatalf("claim then patch = %#v, want open and unassigned", result)
}
}
func TestIssueOperationsUpdateInvalidIssueTypePreservesValidationSentinel(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
issue := &types.Issue{ID: "ops-staging-invalid-type", Title: "invalid type", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
_, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{IssueType: publicops.Field[publicops.IssueType]{Set: true, Value: "not-a-type"}}})
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("invalid issue type error = %v, want ErrValidation", err)
}
}
func TestIssueOperationsUpdateNotesConflictPreservesValidationSentinel(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
issue := &types.Issue{ID: "ops-staging-notes-conflict", Title: "notes conflict", Notes: "before", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
_, err = operations.Update(ctx, publicops.UpdateRequest{
Actor: "writer",
IssueID: issue.ID,
Patch: publicops.IssuePatch{
Notes: publicops.Field[string]{Set: true, Value: "replacement"},
AppendNotes: publicops.Field[string]{Set: true, Value: "append"},
},
})
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("notes conflict error = %v, want ErrValidation", err)
}
stored, err := store.GetIssue(ctx, issue.ID)
if err != nil || stored.Notes != "before" {
t.Fatalf("notes conflict persisted notes = %q, %v; want before", stored.Notes, err)
}
}
func TestIssueOperationsUpdateParentStagesBlockedStateAndRollsBackFailure(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
issues := []*types.Issue{
{ID: "ops-staging-parent-blocker", Title: "blocker", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
{ID: "ops-staging-parent-clean", Title: "clean parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic},
{ID: "ops-staging-parent-blocked", Title: "blocked parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic},
{ID: "ops-staging-parent-child", Title: "child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
{ID: "ops-staging-parent-rollback", Title: "rollback child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
}
for _, issue := range issues {
if err := store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
}
for _, dependency := range []*types.Dependency{
{IssueID: "ops-staging-parent-blocked", DependsOnID: "ops-staging-parent-blocker", Type: types.DepBlocks},
{IssueID: "ops-staging-parent-child", DependsOnID: "ops-staging-parent-clean", Type: types.DepParentChild},
{IssueID: "ops-staging-parent-rollback", DependsOnID: "ops-staging-parent-blocked", Type: types.DepParentChild},
} {
if err := store.AddDependency(ctx, dependency, "seed"); err != nil {
t.Fatal(err)
}
}
if err := store.Commit(ctx, "seed blocked parent state"); err != nil {
t.Fatal(err)
}
operations, err := NewIssueOperations(store)
if err != nil {
t.Fatal(err)
}
result, err := operations.Update(ctx, publicops.UpdateRequest{
Actor: "writer",
IssueID: "ops-staging-parent-child",
Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: "ops-staging-parent-blocked"}},
})
if err != nil || !result.Changed || issueParentIDs(result.Issue) != "ops-staging-parent-blocked" {
t.Fatalf("blocked parent replacement = %#v, %v", result, err)
}
var workingBlocked, headBlocked bool
if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues WHERE id = ?", "ops-staging-parent-child").Scan(&workingBlocked); err != nil {
t.Fatal(err)
}
if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", "ops-staging-parent-child").Scan(&headBlocked); err != nil {
t.Fatal(err)
}
if !workingBlocked || !headBlocked {
t.Fatalf("blocked child state = working %t, HEAD %t; want both true", workingBlocked, headBlocked)
}
_, err = operations.Update(ctx, publicops.UpdateRequest{
Actor: "writer",
IssueID: "ops-staging-parent-rollback",
Patch: publicops.IssuePatch{
Title: publicops.Field[string]{Set: true, Value: "must rollback"},
ParentID: publicops.Field[string]{Set: true, Value: "ops-staging-parent-missing"},
},
})
if err == nil {
t.Fatal("missing parent replacement succeeded")
}
rolledBack, err := store.GetIssue(ctx, "ops-staging-parent-rollback")
if err != nil {
t.Fatal(err)
}
dependencies, err := store.GetDependencyRecords(ctx, rolledBack.ID)
if err != nil {
t.Fatal(err)
}
if rolledBack.Title != "rollback child" || !hasIssueOperationDependency(dependencies, rolledBack.ID, "ops-staging-parent-blocked", types.DepParentChild, "{}", "") {
t.Fatalf("failed parent replacement persisted issue = %#v, dependencies %#v", rolledBack, dependencies)
}
var rollbackWorkingTitle, rollbackHeadTitle string
if err := store.db.QueryRowContext(ctx, "SELECT title, is_blocked FROM issues WHERE id = ?", rolledBack.ID).Scan(&rollbackWorkingTitle, &workingBlocked); err != nil {
t.Fatal(err)
}
if err := store.db.QueryRowContext(ctx, "SELECT title, is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", rolledBack.ID).Scan(&rollbackHeadTitle, &headBlocked); err != nil {
t.Fatal(err)
}
if rollbackWorkingTitle != "rollback child" || rollbackHeadTitle != "rollback child" || !workingBlocked || !headBlocked {
t.Fatalf("failed parent replacement state = working (%q, %t), HEAD (%q, %t)", rollbackWorkingTitle, workingBlocked, rollbackHeadTitle, headBlocked)
}
}

View file

@ -0,0 +1,27 @@
package dolt
import (
"context"
"database/sql"
"sort"
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
)
func (s *DoltStore) runIssueOperationTx(ctx context.Context, commitMsg string, fn func(*sql.Tx) (storageissueops.ChangedTables, error)) error {
return s.withRetryTx(ctx, func(tx *sql.Tx) error {
tables, err := fn(tx)
if err != nil {
return err
}
if len(tables) == 0 {
return nil
}
staged := make([]string, 0, len(tables))
for table := range tables {
staged = append(staged, table)
}
sort.Strings(staged)
return s.doltAddAndCommitInTx(ctx, tx, staged, commitMsg)
})
}

View file

@ -209,9 +209,13 @@ func (s *DoltStore) UpdateIssue(ctx context.Context, id string, updates map[stri
// (https://www.dolthub.com/blog/2023-10-23-hold-my-beer/) — so retry is the
// only safety net. withRetryTx owns BeginTx and the final Commit.
return s.withRetryTx(ctx, func(tx *sql.Tx) error {
if _, err := issueops.UpdateIssueInTx(ctx, tx, id, updates, actor); err != nil {
result, err := issueops.UpdateIssueInTx(ctx, tx, id, updates, actor)
if err != nil {
return err
}
if !result.Changed {
return nil
}
for _, table := range []string{"issues", "events"} {
_ = schema.DrainCall(ctx, tx, "CALL DOLT_ADD(?)", table)
@ -283,9 +287,13 @@ func (s *DoltStore) UpdateIssueChecked(ctx context.Context, id string, updates m
if err := issueops.CheckExpectedFieldsInTx(ctx, tx, id, opts.ExpectedAssignee, opts.ExpectedStatus); err != nil {
return err
}
if _, err := issueops.UpdateIssueInTx(ctx, tx, id, updates, actor); err != nil {
result, err := issueops.UpdateIssueInTx(ctx, tx, id, updates, actor)
if err != nil {
return err
}
if !result.Changed {
return nil
}
for _, table := range []string{"issues", "events"} {
_ = schema.DrainCall(ctx, tx, "CALL DOLT_ADD(?)", table)
@ -568,23 +576,26 @@ func (s *DoltStore) UnclaimIssueIfAssignee(ctx context.Context, id string, actor
})
}
// ReopenIssue reopens a closed issue, setting status to open and clearing
// closed_at and defer_until. If reason is non-empty, it is recorded as a comment.
// Wraps UpdateIssue for Dolt-specific concerns (wisp routing, DOLT_COMMIT, etc.).
// ReopenIssue reopens a done-category issue atomically and stages only the
// versioned tables that this transaction concretely changed.
func (s *DoltStore) ReopenIssue(ctx context.Context, id string, reason string, actor string) error {
updates := map[string]interface{}{
"status": string(types.StatusOpen),
"defer_until": nil,
}
if err := s.UpdateIssue(ctx, id, updates, actor); err != nil {
return err
}
if reason != "" {
if err := s.AddComment(ctx, id, actor, reason); err != nil {
return fmt.Errorf("reopen comment: %w", err)
return s.withRetryTx(ctx, func(tx *sql.Tx) error {
res, err := issueops.ReopenIssueInTx(ctx, tx, id, reason, actor)
if err != nil {
return err
}
}
return nil
if !res.Changed {
return nil
}
switch {
case !res.IsWisp:
return s.doltAddAndCommitInTx(ctx, tx, []string{"issues", "events"}, fmt.Sprintf("bd: reopen %s", id))
case res.IssueRowsChanged:
return s.doltAddAndCommitInTx(ctx, tx, []string{"issues"}, fmt.Sprintf("bd: reopen %s", id))
default:
return nil
}
})
}
// UpdateIssueType changes the issue_type field of an issue.
@ -654,7 +665,7 @@ func (s *DoltStore) CloseIssueChecked(ctx context.Context, id string, actor stri
if err != nil {
return err
}
result = storage.CloseIssueResult{Unchanged: res.AlreadyClosed}
result = storage.CloseIssueResult{Unchanged: res.AlreadyClosed, OpenChildren: res.OpenChildren}
// Dolt versioning for permanent issues.
// GH#2455: Stage only the tables we modified, then commit without -A.
@ -937,8 +948,6 @@ func generateHashID(prefix, title, description, creator string, timestamp time.T
// Thin wrappers around exported issueops functions, kept for internal callers.
var (
isAllowedUpdateField = issueops.IsAllowedUpdateField
manageClosedAt = issueops.ManageClosedAt
determineEventType = issueops.DetermineEventType
)
// Aliases for shared nullable helpers from issueops.

View file

@ -0,0 +1,225 @@
package dolt
import (
"context"
"database/sql"
"errors"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
func TestReopenIssueCategorySemantics(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
setStatus := func(t *testing.T, table, id, status string) int64 {
t.Helper()
if _, err := store.db.ExecContext(ctx, `
UPDATE `+table+`
SET status = ?, closed_at = UTC_TIMESTAMP(), close_reason = ?, closed_by_session = ?,
defer_until = DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 DAY)
WHERE id = ?
`, status, "completed", "session-1", id); err != nil {
t.Fatalf("set %s status: %v", table, err)
}
var rowLock int64
if err := store.db.QueryRowContext(ctx,
"SELECT row_lock FROM "+table+" WHERE id = ?", id).Scan(&rowLock); err != nil {
t.Fatalf("read %s row_lock: %v", table, err)
}
return rowLock
}
insertCustomStatus := func(t *testing.T, name string, category types.StatusCategory) {
t.Helper()
if _, err := store.db.ExecContext(ctx,
"INSERT INTO custom_statuses (name, category) VALUES (?, ?)", name, string(category)); err != nil {
t.Fatalf("insert custom status: %v", err)
}
}
assertLifecycleCleared := func(t *testing.T, table, id string, priorRowLock int64) {
t.Helper()
var status, reason, session string
var closedAt, deferred sql.NullTime
var rowLock int64
if err := store.db.QueryRowContext(ctx, `
SELECT status, closed_at, close_reason, closed_by_session, defer_until, row_lock
FROM `+table+` WHERE id = ?
`, id).Scan(&status, &closedAt, &reason, &session, &deferred, &rowLock); err != nil {
t.Fatalf("read reopened %s: %v", table, err)
}
if status != string(types.StatusOpen) || closedAt.Valid || reason != "" || session != "" || deferred.Valid {
t.Fatalf("reopened lifecycle = status=%q closed_at=%v reason=%q session=%q defer=%v",
status, closedAt.Valid, reason, session, deferred.Valid)
}
if rowLock == 0 || rowLock == priorRowLock {
t.Fatalf("reopened row_lock = %d, want fresh non-zero token different from %d", rowLock, priorRowLock)
}
}
t.Run("custom done permanent clears lifecycle and records events", func(t *testing.T) {
const id = "ro-category-permanent"
createPerm(t, ctx, store, id)
insertCustomStatus(t, "archived", types.CategoryDone)
priorRowLock := setStatus(t, "issues", id, "archived")
before := reopenDoltHead(t, ctx, store)
if err := store.ReopenIssue(ctx, id, "needs review", "tester"); err != nil {
t.Fatalf("ReopenIssue: %v", err)
}
assertLifecycleCleared(t, "issues", id, priorRowLock)
if after := reopenDoltHead(t, ctx, store); after == before {
t.Fatal("permanent reopen did not create a Dolt commit")
}
var reopened, comments int
if err := store.db.QueryRowContext(ctx,
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", id, string(types.EventReopened)).Scan(&reopened); err != nil {
t.Fatalf("count reopened events: %v", err)
}
if err := store.db.QueryRowContext(ctx,
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", id, string(types.EventCommented)).Scan(&comments); err != nil {
t.Fatalf("count comment events: %v", err)
}
if reopened != 1 || comments != 1 {
t.Fatalf("events = reopened:%d comments:%d, want 1 each", reopened, comments)
}
})
t.Run("custom done wisp mutates without a Dolt commit", func(t *testing.T) {
const id = "ro-category-wisp"
createWisp(t, ctx, store, id)
insertCustomStatus(t, "retired", types.CategoryDone)
priorRowLock := setStatus(t, "wisps", id, "retired")
before := reopenDoltHead(t, ctx, store)
if err := store.ReopenIssue(ctx, id, "", "tester"); err != nil {
t.Fatalf("ReopenIssue: %v", err)
}
assertLifecycleCleared(t, "wisps", id, priorRowLock)
if after := reopenDoltHead(t, ctx, store); after != before {
t.Fatalf("wisp reopen changed Dolt HEAD from %s to %s", before, after)
}
})
t.Run("wisp reopen commits durable depender recomputation", func(t *testing.T) {
const (
dependerID = "ro-category-wisp-depender"
targetID = "ro-category-wisp-target"
)
createPerm(t, ctx, store, dependerID)
createWisp(t, ctx, store, targetID)
if err := store.AddDependency(ctx, &types.Dependency{
IssueID: dependerID, DependsOnID: targetID, Type: types.DepBlocks,
}, "tester"); err != nil {
t.Fatalf("AddDependency: %v", err)
}
if err := store.CloseIssue(ctx, targetID, "done", "tester", ""); err != nil {
t.Fatalf("CloseIssue: %v", err)
}
before := reopenDoltHead(t, ctx, store)
if err := store.ReopenIssue(ctx, targetID, "", "tester"); err != nil {
t.Fatalf("ReopenIssue: %v", err)
}
var blocked bool
if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues WHERE id = ?", dependerID).Scan(&blocked); err != nil {
t.Fatalf("read durable depender: %v", err)
}
if !blocked {
t.Fatal("permanent depender was not re-blocked by reopened wisp")
}
if after := reopenDoltHead(t, ctx, store); after == before {
t.Fatal("wisp reopen with durable recomputation did not create a Dolt commit")
}
})
t.Run("custom non done and unknown statuses stay untouched", func(t *testing.T) {
const activeID = "ro-category-active"
const unknownID = "ro-category-unknown"
createPerm(t, ctx, store, activeID)
createPerm(t, ctx, store, unknownID)
insertCustomStatus(t, "triaged", types.CategoryActive)
setStatus(t, "issues", activeID, "triaged")
setStatus(t, "issues", unknownID, "unknown-status")
for _, check := range []struct {
id string
status string
}{{activeID, "triaged"}, {unknownID, "unknown-status"}} {
before := reopenDoltHead(t, ctx, store)
var beforeEvents int
if err := store.db.QueryRowContext(ctx,
"SELECT COUNT(*) FROM events WHERE issue_id = ?", check.id).Scan(&beforeEvents); err != nil {
t.Fatalf("count events before reopen for %s: %v", check.id, err)
}
if err := store.ReopenIssue(ctx, check.id, "ignored", "tester"); err != nil {
t.Fatalf("ReopenIssue(%s): %v", check.id, err)
}
if after := reopenDoltHead(t, ctx, store); after != before {
t.Fatalf("ineligible reopen for %s changed Dolt HEAD", check.id)
}
var status, reason string
var afterEvents int
if err := store.db.QueryRowContext(ctx,
"SELECT status, close_reason FROM issues WHERE id = ?", check.id).Scan(&status, &reason); err != nil {
t.Fatalf("read unchanged issue %s: %v", check.id, err)
}
if status != check.status || reason != "completed" {
t.Fatalf("unchanged issue %s = status:%q reason:%q", check.id, status, reason)
}
if err := store.db.QueryRowContext(ctx,
"SELECT COUNT(*) FROM events WHERE issue_id = ?", check.id).Scan(&afterEvents); err != nil {
t.Fatalf("count events for %s: %v", check.id, err)
}
if afterEvents != beforeEvents {
t.Fatalf("ineligible reopen for %s changed event count from %d to %d", check.id, beforeEvents, afterEvents)
}
}
})
t.Run("literal open is a strict no-op", func(t *testing.T) {
const id = "ro-category-open"
createPerm(t, ctx, store, id)
before := reopenDoltHead(t, ctx, store)
beforeEvents, err := store.GetEvents(ctx, id, 0)
if err != nil {
t.Fatalf("GetEvents before reopen: %v", err)
}
if err := store.ReopenIssue(ctx, id, "ignored", "tester"); err != nil {
t.Fatalf("ReopenIssue: %v", err)
}
if after := reopenDoltHead(t, ctx, store); after != before {
t.Fatalf("literal-open no-op changed Dolt HEAD from %s to %s", before, after)
}
afterEvents, err := store.GetEvents(ctx, id, 0)
if err != nil {
t.Fatalf("GetEvents after reopen: %v", err)
}
if len(afterEvents) != len(beforeEvents) {
t.Fatalf("literal-open no-op events = %+v, want no new events", afterEvents)
}
})
t.Run("missing target wraps not found", func(t *testing.T) {
err := store.ReopenIssue(ctx, "ro-category-missing", "", "tester")
if !errors.Is(err, storage.ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
})
}
func reopenDoltHead(t *testing.T, ctx context.Context, store *DoltStore) string {
t.Helper()
var head string
if err := store.db.QueryRowContext(ctx, "SELECT HASHOF('HEAD')").Scan(&head); err != nil {
t.Fatalf("read Dolt HEAD: %v", err)
}
return head
}

View file

@ -0,0 +1,154 @@
package dolt
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"io"
"reflect"
"strings"
"sync"
"testing"
)
// reopenPromotionDriver models the promotion seam: a pre-transaction probe
// finds an active wisp, while the write transaction sees the same ID only in
// the permanent issues table.
type reopenPromotionDriver struct {
mu sync.Mutex
inTx bool
preTxWispProbe bool
doltAddTables []string
doltCommitCalled bool
issueUpdated bool
}
func (d *reopenPromotionDriver) Open(string) (driver.Conn, error) {
return &reopenPromotionConn{driver: d}, nil
}
func (d *reopenPromotionDriver) Connect(context.Context) (driver.Conn, error) {
return &reopenPromotionConn{driver: d}, nil
}
func (d *reopenPromotionDriver) Driver() driver.Driver { return d }
type reopenPromotionConn struct {
driver *reopenPromotionDriver
}
func (c *reopenPromotionConn) Prepare(string) (driver.Stmt, error) {
return nil, errors.New("reopen promotion driver does not prepare statements")
}
func (c *reopenPromotionConn) Close() error { return nil }
func (c *reopenPromotionConn) Begin() (driver.Tx, error) {
c.driver.mu.Lock()
c.driver.inTx = true
c.driver.mu.Unlock()
return &reopenPromotionTx{driver: c.driver}, nil
}
func (c *reopenPromotionConn) QueryContext(_ context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
c.driver.mu.Lock()
defer c.driver.mu.Unlock()
if strings.Contains(query, "SELECT 1 FROM wisps WHERE id = ? LIMIT 1") {
if !c.driver.inTx {
c.driver.preTxWispProbe = true
return &reopenPromotionRows{columns: []string{"exists"}, values: [][]driver.Value{{int64(1)}}}, nil
}
return &reopenPromotionRows{columns: []string{"exists"}}, nil
}
if strings.Contains(query, "SELECT status FROM issues WHERE id = ?") {
return &reopenPromotionRows{
columns: []string{"status"},
values: [][]driver.Value{{string("closed")}},
}, nil
}
if strings.Contains(query, "CALL DOLT_ADD") && len(args) == 1 {
if table, ok := args[0].Value.(string); ok {
c.driver.doltAddTables = append(c.driver.doltAddTables, table)
}
}
if strings.Contains(query, "CALL DOLT_COMMIT") {
c.driver.doltCommitCalled = true
}
return &reopenPromotionRows{columns: []string{"value"}}, nil
}
func (c *reopenPromotionConn) ExecContext(_ context.Context, query string, _ []driver.NamedValue) (driver.Result, error) {
c.driver.mu.Lock()
defer c.driver.mu.Unlock()
if strings.Contains(query, "UPDATE issues") && strings.Contains(query, "SET status") {
c.driver.issueUpdated = true
return driver.RowsAffected(1), nil
}
return driver.RowsAffected(0), nil
}
type reopenPromotionTx struct {
driver *reopenPromotionDriver
}
func (t *reopenPromotionTx) Commit() error {
t.driver.mu.Lock()
t.driver.inTx = false
t.driver.mu.Unlock()
return nil
}
func (t *reopenPromotionTx) Rollback() error {
t.driver.mu.Lock()
t.driver.inTx = false
t.driver.mu.Unlock()
return nil
}
type reopenPromotionRows struct {
columns []string
values [][]driver.Value
index int
}
func (r *reopenPromotionRows) Columns() []string { return r.columns }
func (r *reopenPromotionRows) Close() error { return nil }
func (r *reopenPromotionRows) Next(dest []driver.Value) error {
if r.index >= len(r.values) {
return io.EOF
}
copy(dest, r.values[r.index])
r.index++
return nil
}
var _ driver.Connector = (*reopenPromotionDriver)(nil)
func TestReopenIssuePromotionRaceUsesTransactionRouting(t *testing.T) {
routingDriver := &reopenPromotionDriver{}
store := &DoltStore{db: sql.OpenDB(routingDriver)}
defer func() { _ = store.db.Close() }()
if err := store.ReopenIssue(context.Background(), "promoted-wisp", "", "tester"); err != nil {
t.Fatalf("ReopenIssue: %v", err)
}
routingDriver.mu.Lock()
defer routingDriver.mu.Unlock()
if routingDriver.preTxWispProbe {
t.Fatal("reopen probed wisp routing before its write transaction")
}
if !routingDriver.issueUpdated {
t.Fatal("promoted permanent issue was not updated")
}
if got, want := routingDriver.doltAddTables, []string{"issues", "events"}; !reflect.DeepEqual(got, want) {
t.Fatalf("DOLT_ADD tables = %v, want %v for promoted permanent issue", got, want)
}
if !routingDriver.doltCommitCalled {
t.Fatal("promoted permanent issue did not create a Dolt commit")
}
}

View file

@ -0,0 +1,187 @@
package dolt
import (
"context"
"testing"
"github.com/steveyegge/beads/internal/types"
)
func TestReopenWispStagesOnlyConcreteIssueChanges(t *testing.T) {
newStore := func(t *testing.T) (*DoltStore, context.Context) {
t.Helper()
store, cleanup := setupTestStore(t)
t.Cleanup(cleanup)
ctx, cancel := testContext(t)
t.Cleanup(cancel)
return store, ctx
}
t.Run("isolated wisp leaves unrelated dirty issues and events uncommitted", func(t *testing.T) {
store, ctx := newStore(t)
const (
wispID = "ro-stage-isolated-wisp"
issueID = "ro-stage-unrelated-issue"
eventID = "ro-stage-unrelated-event"
)
createPerm(t, ctx, store, issueID)
createWisp(t, ctx, store, wispID)
if err := store.CloseIssue(ctx, wispID, "done", "tester", ""); err != nil {
t.Fatalf("CloseIssue: %v", err)
}
before := reopenDoltHead(t, ctx, store)
stageReopenDirtyIssue(t, ctx, store, issueID)
stageReopenDirtyEvent(t, ctx, store, eventID, issueID)
if err := store.ReopenIssue(ctx, wispID, "", "tester"); err != nil {
t.Fatalf("ReopenIssue: %v", err)
}
if after := reopenDoltHead(t, ctx, store); after != before {
t.Fatalf("isolated wisp reopen changed HEAD from %s to %s", before, after)
}
assertReopenDirtyRowsUncommitted(t, ctx, store, issueID, eventID)
})
t.Run("affected issue without a SQL flip remains uncommitted", func(t *testing.T) {
store, ctx := newStore(t)
const (
dependerID = "ro-stage-no-flip-depender"
wispID = "ro-stage-no-flip-wisp"
dirtyID = "ro-stage-no-flip-dirty"
)
createPerm(t, ctx, store, dependerID)
createPerm(t, ctx, store, dirtyID)
createWisp(t, ctx, store, wispID)
if err := store.AddDependency(ctx, &types.Dependency{
IssueID: dependerID, DependsOnID: wispID, Type: types.DepBlocks,
}, "tester"); err != nil {
t.Fatalf("AddDependency: %v", err)
}
if err := store.CloseIssue(ctx, wispID, "done", "tester", ""); err != nil {
t.Fatalf("CloseIssue: %v", err)
}
if _, err := store.db.ExecContext(ctx,
"UPDATE issues SET is_blocked = 1 WHERE id = ?", dependerID); err != nil {
t.Fatalf("pre-converge affected issue: %v", err)
}
before := reopenDoltHead(t, ctx, store)
stageReopenDirtyIssue(t, ctx, store, dirtyID)
if err := store.ReopenIssue(ctx, wispID, "", "tester"); err != nil {
t.Fatalf("ReopenIssue: %v", err)
}
if after := reopenDoltHead(t, ctx, store); after != before {
t.Fatalf("no-flip wisp reopen changed HEAD from %s to %s", before, after)
}
var headNotes string
if err := store.db.QueryRowContext(ctx,
"SELECT notes FROM issues AS OF 'HEAD' WHERE id = ?", dirtyID).Scan(&headNotes); err != nil {
t.Fatalf("read dirty issue AS OF HEAD: %v", err)
}
if headNotes == "uncommitted reopen sentinel" {
t.Fatal("no-flip wisp reopen staged an unrelated dirty issue")
}
})
t.Run("durable issue flip commits issues but not unrelated event", func(t *testing.T) {
store, ctx := newStore(t)
const (
dependerID = "ro-stage-flip-depender"
wispID = "ro-stage-flip-wisp"
eventID = "ro-stage-flip-dirty-event"
)
createPerm(t, ctx, store, dependerID)
createWisp(t, ctx, store, wispID)
if err := store.AddDependency(ctx, &types.Dependency{
IssueID: dependerID, DependsOnID: wispID, Type: types.DepBlocks,
}, "tester"); err != nil {
t.Fatalf("AddDependency: %v", err)
}
if err := store.CloseIssue(ctx, wispID, "done", "tester", ""); err != nil {
t.Fatalf("CloseIssue: %v", err)
}
commitReopenIssueWorkingSet(t, ctx, store, "seed closed-wisp projection")
before := reopenDoltHead(t, ctx, store)
stageReopenDirtyEvent(t, ctx, store, eventID, dependerID)
if err := store.ReopenIssue(ctx, wispID, "", "tester"); err != nil {
t.Fatalf("ReopenIssue: %v", err)
}
if after := reopenDoltHead(t, ctx, store); after == before {
t.Fatal("wisp reopen with an actual issues-row flip did not advance HEAD")
}
var blocked bool
if err := store.db.QueryRowContext(ctx,
"SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", dependerID).Scan(&blocked); err != nil {
t.Fatalf("read durable depender AS OF HEAD: %v", err)
}
if !blocked {
t.Fatal("recomputed durable issue is not visible AS OF HEAD")
}
// events is dolt_ignored since migration 0062 (bd-red8u), so it has no
// HEAD state of its own: the sentinel row cannot ride the issues commit,
// but it must survive that commit in the working set. The plane
// invariant — no events row ever reaches committed history — is what
// assertEventsNotCommitted still checks here, where HEAD does advance.
var workingEvent int
if err := store.db.QueryRowContext(ctx,
"SELECT COUNT(*) FROM events WHERE id = ?", eventID).Scan(&workingEvent); err != nil {
t.Fatalf("read dirty event in working set: %v", err)
}
if workingEvent != 1 {
t.Fatalf("dirty working-set event count = %d, want 1 (the issues commit dropped it)", workingEvent)
}
assertEventsNotCommitted(ctx, t, store.db)
})
}
func stageReopenDirtyIssue(t *testing.T, ctx context.Context, store *DoltStore, id string) {
t.Helper()
if _, err := store.db.ExecContext(ctx,
"UPDATE issues SET notes = ? WHERE id = ?", "uncommitted reopen sentinel", id); err != nil {
t.Fatalf("stage dirty issue: %v", err)
}
}
func stageReopenDirtyEvent(t *testing.T, ctx context.Context, store *DoltStore, eventID, issueID string) {
t.Helper()
if _, err := store.db.ExecContext(ctx,
"INSERT INTO events (id, issue_id, event_type, actor, old_value, new_value) VALUES (?, ?, ?, ?, ?, ?)",
eventID, issueID, string(types.EventUpdated), "other", "", "uncommitted reopen event",
); err != nil {
t.Fatalf("stage dirty event: %v", err)
}
}
func assertReopenDirtyRowsUncommitted(
t *testing.T, ctx context.Context, store *DoltStore, issueID, eventID string,
) {
t.Helper()
var headNotes string
if err := store.db.QueryRowContext(ctx,
"SELECT notes FROM issues AS OF 'HEAD' WHERE id = ?", issueID).Scan(&headNotes); err != nil {
t.Fatalf("read dirty issue AS OF HEAD: %v", err)
}
if headNotes == "uncommitted reopen sentinel" {
t.Fatal("isolated wisp reopen staged an unrelated dirty issue")
}
// events is dolt_ignored since migration 0062 (bd-red8u): there is no HEAD
// state to read. Both callers already assert that HEAD did not move at all,
// which covers "nothing was published"; what is left to check about the
// sentinel event is that the reopen did not destroy it in the working set.
var workingEvent int
if err := store.db.QueryRowContext(ctx,
"SELECT COUNT(*) FROM events WHERE id = ?", eventID).Scan(&workingEvent); err != nil {
t.Fatalf("read dirty event in working set: %v", err)
}
if workingEvent != 1 {
t.Fatalf("dirty working-set event count = %d, want 1 (the reopen dropped it)", workingEvent)
}
}
func commitReopenIssueWorkingSet(t *testing.T, ctx context.Context, store *DoltStore, message string) {
t.Helper()
if err := store.doltAddAndCommit(ctx, []string{"issues"}, message); err != nil {
t.Fatalf("doltAddAndCommit issues: %v", err)
}
}

View file

@ -33,6 +33,7 @@ type doltTransaction struct {
// role: it deliberately drops wisp_* tables because they are dolt-ignored.
wroteRegularDep bool
wroteWispDep bool
lifecycle bool
}
func (t *doltTransaction) txFor(table string) *sql.Tx {
@ -68,6 +69,31 @@ func (s *DoltStore) RunInTransaction(ctx context.Context, commitMsg string, fn f
})
}
// RunInIssueLifecycleTransaction runs a lifecycle transition and its durable
// side effects through one SQL transaction and one Dolt commit attempt.
func (s *DoltStore) RunInIssueLifecycleTransaction(ctx context.Context, commitMsg string, fn func(tx storage.IssueLifecycleTransaction) error) error {
return s.withRetryTx(ctx, func(sqlTx *sql.Tx) error {
tx := &doltTransaction{regularTx: sqlTx, ignoredTx: sqlTx, store: s, lifecycle: true}
if err := fn(tx); err != nil {
return err
}
tables := tx.dirtyTableNames()
if len(tables) == 0 {
return nil
}
return s.doltAddAndCommitInTx(ctx, sqlTx, tables, commitMsg)
})
}
func (t *doltTransaction) dirtyTableNames() []string {
tables := make([]string, 0, len(t.dirty.DirtyTables()))
for table := range t.dirty.DirtyTables() {
tables = append(tables, table)
}
sort.Strings(tables)
return tables
}
func (s *DoltStore) runDoltTransaction(ctx context.Context, commitMsg string, fn func(tx storage.Transaction) error) error {
// Pin a single connection for the entire operation: SQL transaction,
// config protection, and DOLT_COMMIT must all run on the same Dolt
@ -650,10 +676,22 @@ func (t *doltTransaction) UpdateIssue(ctx context.Context, id string, updates ma
}
}
if _, err := issueops.UpdateIssueWithoutEventInTx(ctx, t.txFor(table), id, updates, actor); err != nil {
update := issueops.UpdateIssueWithoutEventInTx
if t.lifecycle {
update = issueops.UpdateIssueInTx
}
result, err := update(ctx, t.txFor(table), id, updates, actor)
if err != nil {
return wrapExecError("update issue in tx", err)
}
if !result.Changed {
return nil
}
t.dirty.MarkDirty(table)
if t.lifecycle {
_, _, eventTable, _ := issueops.WispTableRouting(table == "wisps")
t.dirty.MarkDirty(eventTable)
}
return nil
}
@ -674,9 +712,33 @@ func (t *doltTransaction) CloseIssue(ctx context.Context, id string, reason stri
}
t.dirty.MarkDirty(table)
t.dirty.MarkDirty(eventTable)
if result.IssueRowsChanged {
t.dirty.MarkDirty("issues")
}
return nil
}
// ReopenIssueWithResult reopens an issue within this transaction and reports
// whether the lifecycle state changed.
func (t *doltTransaction) ReopenIssueWithResult(ctx context.Context, id string, reason string, actor string) (bool, error) {
table, eventTable := "issues", "events"
if t.isActiveWisp(ctx, id) {
table, eventTable = "wisps", "wisp_events"
}
result, err := issueops.ReopenIssueInTx(ctx, t.txFor(table), id, reason, actor)
if err != nil {
return false, wrapExecError("reopen issue in tx", err)
}
if result.Changed {
t.dirty.MarkDirty(table)
t.dirty.MarkDirty(eventTable)
if result.IssueRowsChanged {
t.dirty.MarkDirty("issues")
}
}
return result.Changed, nil
}
func (t *doltTransaction) DeleteIssue(ctx context.Context, id string) error {
isWisp := t.isActiveWisp(ctx, id)
table := "issues"

View file

@ -0,0 +1,368 @@
package dolt
import (
"context"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// TestRunInTransactionWispLifecyclePersistsDurableDependent verifies that a
// transactional lifecycle transition of an ignored wisp still publishes the
// durable is_blocked recomputation of an issue that depends on it.
func TestRunInTransactionWispLifecyclePersistsDurableDependent(t *testing.T) {
ctx, store := newTransactionWispLifecycleStore(t)
t.Run("close", func(t *testing.T) {
const (
dependerID = "tx-wisp-close-depender"
wispID = "tx-wisp-close-blocker"
)
seedTransactionWispBlocker(t, ctx, store, dependerID, wispID)
before := transactionWispLifecycleHead(t, ctx, store)
if err := store.RunInIssueLifecycleTransaction(ctx, "test: close wisp blocker", func(tx storage.IssueLifecycleTransaction) error {
return tx.CloseIssue(ctx, wispID, "done", "tester", "session")
}); err != nil {
t.Fatalf("RunInTransaction CloseIssue: %v", err)
}
assertTransactionWispLifecyclePostState(t, ctx, store, dependerID, before, false)
})
t.Run("reopen", func(t *testing.T) {
const (
dependerID = "tx-wisp-reopen-depender"
wispID = "tx-wisp-reopen-blocker"
)
seedTransactionWispBlocker(t, ctx, store, dependerID, wispID)
if err := store.CloseIssue(ctx, wispID, "done", "tester", "session"); err != nil {
t.Fatalf("seed CloseIssue: %v", err)
}
if err := store.Commit(ctx, "test: seed closed wisp blocker"); err != nil {
t.Fatalf("Commit closed seed: %v", err)
}
before := transactionWispLifecycleHead(t, ctx, store)
if err := store.RunInIssueLifecycleTransaction(ctx, "test: reopen wisp blocker", func(tx storage.IssueLifecycleTransaction) error {
changed, err := tx.ReopenIssueWithResult(ctx, wispID, "", "tester")
if err != nil {
return err
}
if !changed {
t.Fatal("transactional reopen reported Changed=false")
}
return nil
}); err != nil {
t.Fatalf("RunInTransaction reopen: %v", err)
}
assertTransactionWispLifecyclePostState(t, ctx, store, dependerID, before, true)
})
}
// TestRunInIssueLifecycleTransactionStandaloneWispPersistsWithoutDoltCommit
// verifies that ignored-only lifecycle work commits its SQL transaction without
// attempting a version-control commit.
func TestRunInIssueLifecycleTransactionStandaloneWispPersistsWithoutDoltCommit(t *testing.T) {
ctx, store := newTransactionWispLifecycleStore(t)
t.Run("close", func(t *testing.T) {
const wispID = "tx-standalone-wisp-close"
createWisp(t, ctx, store, wispID)
before := transactionWispLifecycleHead(t, ctx, store)
if err := store.RunInIssueLifecycleTransaction(ctx, "test: close standalone wisp", func(tx storage.IssueLifecycleTransaction) error {
return tx.CloseIssue(ctx, wispID, "done", "tester", "session")
}); err != nil {
t.Fatalf("RunInIssueLifecycleTransaction CloseIssue: %v", err)
}
assertStandaloneWispLifecycleState(t, ctx, store, wispID, before, types.StatusClosed)
})
t.Run("reopen", func(t *testing.T) {
const wispID = "tx-standalone-wisp-reopen"
createWisp(t, ctx, store, wispID)
if err := store.CloseIssue(ctx, wispID, "done", "tester", "session"); err != nil {
t.Fatalf("seed CloseIssue: %v", err)
}
before := transactionWispLifecycleHead(t, ctx, store)
if err := store.RunInIssueLifecycleTransaction(ctx, "test: reopen standalone wisp", func(tx storage.IssueLifecycleTransaction) error {
changed, err := tx.ReopenIssueWithResult(ctx, wispID, "", "tester")
if err != nil {
return err
}
if !changed {
t.Fatal("transactional reopen reported Changed=false")
}
return nil
}); err != nil {
t.Fatalf("RunInIssueLifecycleTransaction ReopenIssueWithResult: %v", err)
}
assertStandaloneWispLifecycleState(t, ctx, store, wispID, before, types.StatusOpen)
})
}
func TestRunInIssueLifecycleTransactionSameStatusDoesNotPublishUnrelatedDurableChanges(t *testing.T) {
ctx, store := newTransactionWispLifecycleStore(t)
const (
targetID = "tx-same-status-target"
dirtyID = "tx-same-status-dirty"
)
createPerm(t, ctx, store, targetID)
createPerm(t, ctx, store, dirtyID)
before := transactionWispLifecycleHead(t, ctx, store)
if _, err := store.db.ExecContext(ctx, "UPDATE issues SET title = ? WHERE id = ?", "working-only title", dirtyID); err != nil {
t.Fatalf("stage unrelated issue edit: %v", err)
}
if _, err := store.db.ExecContext(ctx,
"UPDATE events SET comment = ? WHERE issue_id = ? AND event_type = ?",
"working-only event", dirtyID, string(types.EventCreated),
); err != nil {
t.Fatalf("stage unrelated event edit: %v", err)
}
if err := store.RunInIssueLifecycleTransaction(ctx, "test: same-status update", func(tx storage.IssueLifecycleTransaction) error {
return tx.UpdateIssue(ctx, targetID, map[string]interface{}{"status": types.StatusOpen}, "tester")
}); err != nil {
t.Fatalf("RunInIssueLifecycleTransaction: %v", err)
}
if after := transactionWispLifecycleHead(t, ctx, store); after != before {
t.Errorf("same-status transaction changed HEAD from %s to %s", before, after)
}
assertDirectSameStatusUnrelatedChangesWorkingOnly(t, ctx, store, dirtyID)
}
func TestRunInIssueLifecycleTransactionStandaloneWispMutationDoesNotPublishUnrelatedDurableChanges(t *testing.T) {
ctx, store := newTransactionWispLifecycleStore(t)
const (
durableID = "tx-wisp-isolation-durable"
wispID = "tx-wisp-isolation-wisp"
baselineLabel = "durable-baseline"
workingLabel = "durable-working-only"
removeWispLabel = "remove-from-wisp"
addWispLabel = "add-to-wisp"
)
createPerm(t, ctx, store, durableID)
if err := store.AddLabel(ctx, durableID, baselineLabel, "tester"); err != nil {
t.Fatalf("AddLabel durable baseline: %v", err)
}
createWisp(t, ctx, store, wispID)
if err := store.AddLabel(ctx, wispID, removeWispLabel, "tester"); err != nil {
t.Fatalf("AddLabel wisp baseline: %v", err)
}
if err := store.Commit(ctx, "test: seed durable baseline"); err != nil {
t.Fatalf("Commit baseline: %v", err)
}
before := transactionWispLifecycleHead(t, ctx, store)
if _, err := store.db.ExecContext(ctx, "UPDATE issues SET title = ? WHERE id = ?", "durable working-only", durableID); err != nil {
t.Fatalf("stage durable issue edit: %v", err)
}
if _, err := store.db.ExecContext(ctx, "UPDATE events SET comment = ? WHERE issue_id = ? AND event_type = ?",
"durable working-only", durableID, string(types.EventCreated)); err != nil {
t.Fatalf("stage durable event edit: %v", err)
}
if _, err := store.db.ExecContext(ctx, "UPDATE labels SET label = ? WHERE issue_id = ? AND label = ?",
workingLabel, durableID, baselineLabel); err != nil {
t.Fatalf("stage durable label edit: %v", err)
}
if err := store.RunInIssueLifecycleTransaction(ctx, "test: mutate standalone wisp", func(tx storage.IssueLifecycleTransaction) error {
if err := tx.UpdateIssue(ctx, wispID, map[string]interface{}{"title": "wisp updated"}, "tester"); err != nil {
return err
}
if err := tx.RemoveLabel(ctx, wispID, removeWispLabel, "tester"); err != nil {
return err
}
return tx.AddLabel(ctx, wispID, addWispLabel, "tester")
}); err != nil {
t.Fatalf("RunInIssueLifecycleTransaction: %v", err)
}
if after := transactionWispLifecycleHead(t, ctx, store); after != before {
t.Errorf("standalone wisp mutation changed HEAD from %s to %s", before, after)
}
wisp, err := store.GetIssue(ctx, wispID)
if err != nil {
t.Fatalf("GetIssue wisp: %v", err)
}
if wisp.Title != "wisp updated" {
t.Errorf("wisp title = %q, want %q", wisp.Title, "wisp updated")
}
labels, err := store.GetLabels(ctx, wispID)
if err != nil {
t.Fatalf("GetLabels wisp: %v", err)
}
if len(labels) != 1 || labels[0] != addWispLabel {
t.Errorf("wisp labels = %v, want [%s]", labels, addWispLabel)
}
events, err := store.GetEvents(ctx, wispID, 0)
if err != nil {
t.Fatalf("GetEvents wisp: %v", err)
}
eventCounts := make(map[types.EventType]int)
for _, event := range events {
eventCounts[event.EventType]++
}
if eventCounts[types.EventUpdated] != 1 || eventCounts[types.EventLabelRemoved] != 1 || eventCounts[types.EventLabelAdded] != 2 {
t.Errorf("wisp event counts = updated:%d label_removed:%d label_added:%d",
eventCounts[types.EventUpdated], eventCounts[types.EventLabelRemoved], eventCounts[types.EventLabelAdded])
}
var workingTitle, headTitle string
if err := store.db.QueryRowContext(ctx, "SELECT title FROM issues WHERE id = ?", durableID).Scan(&workingTitle); err != nil {
t.Fatalf("read working durable issue: %v", err)
}
if err := store.db.QueryRowContext(ctx, "SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", durableID).Scan(&headTitle); err != nil {
t.Fatalf("read durable issue AS OF HEAD: %v", err)
}
if workingTitle != "durable working-only" || headTitle != "perm "+durableID {
t.Errorf("durable issue titles = working:%q HEAD:%q", workingTitle, headTitle)
}
var headLabelCount int
if err := store.db.QueryRowContext(ctx,
"SELECT COUNT(*) FROM labels AS OF 'HEAD' WHERE issue_id = ? AND label = ?",
durableID, workingLabel,
).Scan(&headLabelCount); err != nil {
t.Fatalf("read durable label AS OF HEAD: %v", err)
}
if headLabelCount != 0 {
t.Errorf("durable working-only label count AS OF HEAD = %d, want 0", headLabelCount)
}
// events is dolt_ignored since migration 0062 (bd-red8u): it has no HEAD
// state, so the working-only audit edit can only be read from the working
// set. "Nothing was published" is already carried by the HEAD-unchanged
// assertion above; what remains to check is that the wisp mutation left the
// unrelated audit edit intact.
var workingEventCount int
if err := store.db.QueryRowContext(ctx,
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND comment = ?",
durableID, string(types.EventCreated), "durable working-only",
).Scan(&workingEventCount); err != nil {
t.Fatalf("read durable event in working set: %v", err)
}
if workingEventCount != 1 {
t.Errorf("durable working-only event count = %d, want 1", workingEventCount)
}
}
func assertDirectSameStatusUnrelatedChangesWorkingOnly(t *testing.T, ctx context.Context, store *DoltStore, dirtyID string) {
t.Helper()
var workingTitle, headTitle string
if err := store.db.QueryRowContext(ctx, "SELECT title FROM issues WHERE id = ?", dirtyID).Scan(&workingTitle); err != nil {
t.Fatalf("read working unrelated issue: %v", err)
}
if err := store.db.QueryRowContext(ctx, "SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", dirtyID).Scan(&headTitle); err != nil {
t.Fatalf("read unrelated issue AS OF HEAD: %v", err)
}
if workingTitle != "working-only title" || headTitle != "perm "+dirtyID {
t.Errorf("unrelated issue titles = working:%q HEAD:%q", workingTitle, headTitle)
}
// events is dolt_ignored since migration 0062 (bd-red8u): there is no HEAD
// state to compare against. Every caller of this helper asserts that HEAD
// did not move, which is the stronger form of "nothing was published"; the
// remaining events-specific claim is that the same-status update left the
// unrelated working-set audit edit alone.
var workingEvent int
if err := store.db.QueryRowContext(ctx,
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND comment = ?",
dirtyID, string(types.EventCreated), "working-only event",
).Scan(&workingEvent); err != nil {
t.Fatalf("read working unrelated event: %v", err)
}
if workingEvent != 1 {
t.Errorf("unrelated working-set event edit count = %d, want 1", workingEvent)
}
}
func newTransactionWispLifecycleStore(t *testing.T) (context.Context, *DoltStore) {
t.Helper()
store, cleanup := setupTestStore(t)
t.Cleanup(cleanup)
ctx, cancel := testContext(t)
t.Cleanup(cancel)
return ctx, store
}
func seedTransactionWispBlocker(t *testing.T, ctx context.Context, store *DoltStore, dependerID, wispID string) {
t.Helper()
createPerm(t, ctx, store, dependerID)
createWisp(t, ctx, store, wispID)
if err := store.AddDependency(ctx, &types.Dependency{
IssueID: dependerID, DependsOnID: wispID, Type: types.DepBlocks,
}, "tester"); err != nil {
t.Fatalf("AddDependency: %v", err)
}
if err := store.Commit(ctx, "test: seed wisp blocker"); err != nil {
t.Fatalf("Commit seed: %v", err)
}
var blocked bool
if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues WHERE id = ?", dependerID).Scan(&blocked); err != nil {
t.Fatalf("read seed durable depender: %v", err)
}
if !blocked {
t.Fatalf("seed durable depender %s is not blocked", dependerID)
}
var committed bool
if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", dependerID).Scan(&committed); err != nil {
t.Fatalf("read committed seed durable depender: %v", err)
}
if !committed {
t.Fatalf("committed seed durable depender %s is not blocked", dependerID)
}
}
func transactionWispLifecycleHead(t *testing.T, ctx context.Context, store *DoltStore) string {
t.Helper()
head, err := store.GetCurrentCommit(ctx)
if err != nil {
t.Fatalf("GetCurrentCommit: %v", err)
}
return head
}
func assertTransactionWispLifecyclePostState(t *testing.T, ctx context.Context, store *DoltStore, dependerID, before string, wantBlocked bool) {
t.Helper()
after := transactionWispLifecycleHead(t, ctx, store)
if after == before {
t.Errorf("transactional wisp lifecycle did not publish durable dependent; HEAD remained %s", before)
}
var working bool
if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues WHERE id = ?", dependerID).Scan(&working); err != nil {
t.Fatalf("read working durable depender: %v", err)
}
if working != wantBlocked {
t.Errorf("working durable depender is_blocked = %t, want %t", working, wantBlocked)
}
var committed bool
if err := store.db.QueryRowContext(ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", dependerID).Scan(&committed); err != nil {
t.Fatalf("read durable depender AS OF HEAD: %v", err)
}
if committed != wantBlocked {
t.Errorf("committed durable depender is_blocked = %t, want %t", committed, wantBlocked)
}
}
func assertStandaloneWispLifecycleState(t *testing.T, ctx context.Context, store *DoltStore, wispID, before string, wantStatus types.Status) {
t.Helper()
if after := transactionWispLifecycleHead(t, ctx, store); after != before {
t.Fatalf("standalone wisp lifecycle changed HEAD from %s to %s", before, after)
}
issue, err := store.GetIssue(ctx, wispID)
if err != nil {
t.Fatalf("GetIssue(%s): %v", wispID, err)
}
if issue.Status != wantStatus {
t.Errorf("wisp status = %q, want %q", issue.Status, wantStatus)
}
}

View file

@ -0,0 +1,149 @@
package dolt
import (
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
func TestUpdateIssueSameStatusDoesNotCreateLifecycleMutation(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
const id = "same-status-no-lifecycle-mutation"
createPerm(t, ctx, store, id)
before, err := store.GetIssue(ctx, id)
if err != nil {
t.Fatal(err)
}
beforeEvents, err := store.GetEvents(ctx, id, 0)
if err != nil {
t.Fatal(err)
}
if err := store.UpdateIssue(ctx, id, map[string]interface{}{"status": types.StatusOpen}, "tester"); err != nil {
t.Fatalf("same-status UpdateIssue: %v", err)
}
afterSameStatus, err := store.GetIssue(ctx, id)
if err != nil {
t.Fatal(err)
}
afterSameStatusEvents, err := store.GetEvents(ctx, id, 0)
if err != nil {
t.Fatal(err)
}
if afterSameStatus.RowVersion != before.RowVersion {
t.Errorf("same-status update changed RowVersion from %d to %d", before.RowVersion, afterSameStatus.RowVersion)
}
if len(afterSameStatusEvents) != len(beforeEvents) {
t.Errorf("same-status update recorded %d events, want %d", len(afterSameStatusEvents), len(beforeEvents))
}
if err := store.UpdateIssue(ctx, id, map[string]interface{}{"status": types.StatusOpen, "title": "renamed"}, "tester"); err != nil {
t.Fatalf("same-status scalar UpdateIssue: %v", err)
}
afterScalar, err := store.GetIssue(ctx, id)
if err != nil {
t.Fatal(err)
}
if afterScalar.Title != "renamed" {
t.Errorf("mixed scalar update title = %q, want renamed", afterScalar.Title)
}
events, err := store.GetEvents(ctx, id, 0)
if err != nil {
t.Fatal(err)
}
var updated, statusChanged int
for _, event := range events {
switch event.EventType {
case types.EventUpdated:
updated++
case types.EventStatusChanged:
statusChanged++
}
}
if len(events) != len(beforeEvents)+1 || updated != 1 || statusChanged != 0 {
t.Errorf("mixed scalar same-status events = updated:%d status_changed:%d total:%d", updated, statusChanged, len(events))
}
}
func TestDoltStoreSameStatusUpdatesDoNotPublishUnrelatedDurableChanges(t *testing.T) {
for _, test := range []struct {
name string
checked bool
}{
{name: "UpdateIssue"},
{name: "UpdateIssueChecked", checked: true},
} {
t.Run(test.name, func(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
targetID := "store-same-status-target-" + test.name
dirtyID := "store-same-status-dirty-" + test.name
createPerm(t, ctx, store, targetID)
createPerm(t, ctx, store, dirtyID)
targetBefore, err := store.GetIssue(ctx, targetID)
if err != nil {
t.Fatalf("GetIssue target before: %v", err)
}
before := transactionWispLifecycleHead(t, ctx, store)
if _, err := store.db.ExecContext(ctx, "UPDATE issues SET title = ? WHERE id = ?", "working-only title", dirtyID); err != nil {
t.Fatalf("stage unrelated issue edit: %v", err)
}
if _, err := store.db.ExecContext(ctx,
"UPDATE events SET comment = ? WHERE issue_id = ? AND event_type = ?",
"working-only event", dirtyID, string(types.EventCreated),
); err != nil {
t.Fatalf("stage unrelated event edit: %v", err)
}
updates := map[string]interface{}{"status": types.StatusOpen}
if test.checked {
version := targetBefore.RowVersion
err = store.UpdateIssueChecked(ctx, targetID, updates, "tester", storage.UpdateIssueOptions{ExpectedVersion: &version})
} else {
err = store.UpdateIssue(ctx, targetID, updates, "tester")
}
if err != nil {
t.Fatalf("%s: %v", test.name, err)
}
if after := transactionWispLifecycleHead(t, ctx, store); after != before {
t.Errorf("%s same-status update changed HEAD from %s to %s", test.name, before, after)
}
targetAfter, err := store.GetIssue(ctx, targetID)
if err != nil {
t.Fatalf("GetIssue target after: %v", err)
}
if targetAfter.RowVersion != targetBefore.RowVersion {
t.Errorf("%s same-status update changed RowVersion from %d to %d",
test.name, targetBefore.RowVersion, targetAfter.RowVersion)
}
assertDirectSameStatusUnrelatedChangesWorkingOnly(t, ctx, store, dirtyID)
})
}
}
func TestUpdateIssuePreservesCallerUpdatesAfterSameStatusNormalization(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx, cancel := testContext(t)
defer cancel()
const id = "same-status-preserves-caller-map"
createPerm(t, ctx, store, id)
updates := map[string]interface{}{"status": types.StatusOpen}
if err := store.UpdateIssue(ctx, id, updates, "tester"); err != nil {
t.Fatalf("UpdateIssue: %v", err)
}
if got, ok := updates["status"]; !ok || got != types.StatusOpen {
t.Fatalf("caller updates after same-status update = %#v, want status=open", updates)
}
}

View file

@ -279,7 +279,7 @@ func (s *DoltStore) closeWispChecked(ctx context.Context, id string, actor strin
if err := wrapTransactionError("commit close wisp", tx.Commit()); err != nil {
return storage.CloseIssueResult{}, err
}
return storage.CloseIssueResult{Unchanged: res.AlreadyClosed}, nil
return storage.CloseIssueResult{Unchanged: res.AlreadyClosed, OpenChildren: res.OpenChildren}, nil
}
// deleteWisp permanently removes a wisp and its related data.

View file

@ -17,6 +17,7 @@ type CommentSQLRepository interface {
ListByIssueIDs(ctx context.Context, issueIDs []string, opts CommentOpts) (map[string][]*types.Comment, error)
IterByIssueID(ctx context.Context, issueID string, opts CommentOpts) (storage.Iter[types.Comment], error)
Insert(ctx context.Context, issueID, author, text string, opts CommentOpts) (*types.Comment, error)
InsertRecord(ctx context.Context, comment *types.Comment, opts CommentOpts) (*types.Comment, error)
}
type CommentUseCase interface {

View file

@ -63,6 +63,10 @@ type CreateContext struct {
AllowedPrefixes string
CustomTypes []string
CustomStatuses []types.CustomStatus
// InfraTypes is the resolved infrastructure-type set. A create whose type
// is in this set is routed to the wisp tables, the same routing the
// embedded and direct stores apply from IsInfraTypeCtx.
InfraTypes map[string]bool
}
type Issue struct{}
@ -297,10 +301,15 @@ func (u *configUseCaseImpl) LoadCreateContext(ctx context.Context) (CreateContex
if err != nil {
return CreateContext{}, fmt.Errorf("LoadCreateContext: read custom statuses: %w", err)
}
infraTypes, err := u.GetInfraTypes(ctx)
if err != nil {
return CreateContext{}, fmt.Errorf("LoadCreateContext: read infra types: %w", err)
}
return CreateContext{
IssuePrefix: prefix,
AllowedPrefixes: allowed,
CustomTypes: customTypes,
CustomStatuses: customStatuses,
InfraTypes: infraTypes,
}, nil
}

View file

@ -17,6 +17,56 @@ func (s *testSuite) TestIssueUseCase_CloseIssueChecked() {
s.Run("UnblockedClosesAndReturnsIssue", s.uccCloseCheckedUnblockedCloses)
s.Run("WispDirectBlockerRefuses", s.uccCloseWispCheckedDirectBlockerRefuses)
s.Run("WispForceClosesDespiteDirectBlocker", s.uccCloseWispCheckedForceCloses)
s.Run("OpenChildrenRefuseAndForceReportsCount", s.uccCloseCheckedOpenChildren)
}
func (s *testSuite) uccCloseCheckedOpenChildren() {
parent := "bd-ucc-clc-parent"
permanentChild := "bd-ucc-clc-child"
wispChild := "bd-ucc-clc-wisp-child"
s.seedIssueRow(parent)
s.seedIssueRow(permanentChild)
s.seedWispRow(wispChild)
for _, child := range []struct {
id string
wisp bool
}{{permanentChild, false}, {wispChild, true}} {
s.Require().NoError(s.depRepo().Insert(s.Ctx(),
newDep(child.id, parent, types.DepParentChild), "tester", domain.DepInsertOpts{UseWispsTable: child.wisp}))
}
res, err := s.issueUseCase().CloseIssueChecked(s.Ctx(), parent,
domain.CloseIssueParams{Reason: "done"}, "tester", false)
s.Require().Error(err)
s.True(errors.Is(err, storage.ErrCloseOpenChildren))
var childErr *storage.CloseOpenChildrenError
s.True(errors.As(err, &childErr))
s.Equal(parent, childErr.IssueID)
s.Equal(2, childErr.OpenChildren)
s.False(res.Closed)
s.Equal(0, res.OpenChildren)
res, err = s.issueUseCase().CloseIssueChecked(s.Ctx(), parent,
domain.CloseIssueParams{Reason: "override"}, "tester", true)
s.Require().NoError(err)
s.True(res.Closed)
s.Equal(2, res.OpenChildren)
wispParent := "bd-ucc-clc-wisp-parent"
childOfWispParent := "bd-ucc-clc-wisp-parent-child"
s.seedWispRow(wispParent)
s.seedIssueRow(childOfWispParent)
s.Require().NoError(s.depRepo().Insert(s.Ctx(),
newDep(childOfWispParent, wispParent, types.DepParentChild), "tester", domain.DepInsertOpts{}))
res, err = s.issueUseCase().CloseWispChecked(s.Ctx(), wispParent,
domain.CloseIssueParams{Reason: "done"}, "tester", false)
s.Require().Error(err)
s.True(errors.Is(err, storage.ErrCloseOpenChildren))
res, err = s.issueUseCase().CloseWispChecked(s.Ctx(), wispParent,
domain.CloseIssueParams{Reason: "override"}, "tester", true)
s.Require().NoError(err)
s.True(res.Closed)
s.Equal(1, res.OpenChildren)
}
func (s *testSuite) uccCloseCheckedDirectBlockerRefuses() {

View file

@ -114,43 +114,64 @@ func (r *commentSQLRepositoryImpl) IterByIssueID(ctx context.Context, issueID st
}
func (r *commentSQLRepositoryImpl) Insert(ctx context.Context, issueID, author, text string, opts domain.CommentOpts) (*types.Comment, error) {
if issueID == "" {
return nil, fmt.Errorf("db: CommentSQLRepository.Insert: issueID must not be empty")
// Live add: advance past the issue's newest comment so a burst inside one
// second still reads back in write order (issueops.NextLiveCommentTime).
// InsertRecord honors a supplied CreatedAt verbatim, which is what keeps
// imported comments on their original timestamps.
stamp, err := issueops.NextLiveCommentTime(ctx, r.runner, pickCommentTable(opts.UseWispsTable), issueID, time.Now())
if err != nil {
return nil, fmt.Errorf("db: CommentSQLRepository.Insert: %w", err)
}
return r.InsertRecord(ctx, &types.Comment{IssueID: issueID, Author: author, Text: text, CreatedAt: stamp}, opts)
}
func (r *commentSQLRepositoryImpl) InsertRecord(ctx context.Context, comment *types.Comment, opts domain.CommentOpts) (*types.Comment, error) {
if comment == nil {
return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: comment must not be nil")
}
copy := *comment
if copy.IssueID == "" {
return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: issueID must not be empty")
}
issueTable := pickIssueTable(opts.UseWispsTable)
var exists bool
//nolint:gosec // G201: issueTable is one of two hardcoded constants
if err := r.runner.QueryRowContext(ctx,
fmt.Sprintf("SELECT EXISTS(SELECT 1 FROM %s WHERE id = ?)", issueTable), issueID).Scan(&exists); err != nil {
return nil, fmt.Errorf("db: CommentSQLRepository.Insert: check issue existence: %w", err)
fmt.Sprintf("SELECT EXISTS(SELECT 1 FROM %s WHERE id = ?)", issueTable), copy.IssueID).Scan(&exists); err != nil {
return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: check issue existence: %w", err)
}
if !exists {
return nil, fmt.Errorf("db: CommentSQLRepository.Insert: issue %s not found", issueID)
return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: issue %s not found", copy.IssueID)
}
commentTable := pickCommentTable(opts.UseWispsTable)
// Live add: advance past the issue's newest comment so a burst inside one
// second still reads back in write order (issueops.NextLiveCommentTime).
stamp, err := issueops.NextLiveCommentTime(ctx, r.runner, commentTable, issueID, time.Now())
if err != nil {
return nil, fmt.Errorf("db: CommentSQLRepository.Insert: %w", err)
if copy.CreatedAt.IsZero() {
copy.CreatedAt = time.Now().UTC()
} else {
copy.CreatedAt = copy.CreatedAt.UTC()
}
createdAtText := issueops.FormatAuxTime(stamp)
id, _, err := issueops.InsertDerivedComment(ctx, r.runner, commentTable, issueID, author, text, createdAtText)
if err != nil {
return nil, fmt.Errorf("db: CommentSQLRepository.Insert: %w", err)
createdAtText := issueops.FormatAuxTime(copy.CreatedAt)
commentTable := pickCommentTable(opts.UseWispsTable)
if copy.ID == "" {
id, _, err := issueops.InsertDerivedComment(ctx, r.runner, commentTable, copy.IssueID, copy.Author, copy.Text, createdAtText)
if err != nil {
return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: %w", err)
}
copy.ID = id
} else {
//nolint:gosec // G201: commentTable is one of two hardcoded constants
if _, err := r.runner.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO %s (id, issue_id, author, text, created_at)
VALUES (?, ?, ?, ?, ?)
`, commentTable), copy.ID, copy.IssueID, copy.Author, copy.Text, createdAtText); err != nil {
return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: %w", err)
}
}
createdAt, err := issueops.ParseAuxTime(createdAtText)
if err != nil {
return nil, fmt.Errorf("db: CommentSQLRepository.Insert: %w", err)
return nil, fmt.Errorf("db: CommentSQLRepository.InsertRecord: %w", err)
}
copy.CreatedAt = createdAt
return &types.Comment{
ID: id,
IssueID: issueID,
Author: author,
Text: text,
CreatedAt: createdAt,
}, nil
return &copy, nil
}

View file

@ -6,6 +6,7 @@ import (
"github.com/google/uuid"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
func (s *testSuite) TestCommentSQLRepository() {
@ -33,9 +34,32 @@ func (s *testSuite) TestCommentSQLRepository() {
s.Run("PopulatesReturnedComment", s.commentInsertPopulatesReturn)
s.Run("RoundTripsThroughList", s.commentInsertRoundTrip)
s.Run("RoutesToWispComments", s.commentInsertWispRouting)
s.Run("InsertRecordPreservesImportedValues", s.commentInsertRecordPreservesImportedValues)
})
}
func (s *testSuite) commentInsertRecordPreservesImportedValues() {
s.seedIssueRow("bd-cmt-ins-record")
createdAt := time.Date(2025, time.January, 2, 3, 4, 5, 987_654_321, time.UTC)
inserted, err := s.commentRepo().InsertRecord(s.Ctx(), &types.Comment{
ID: "imported-comment-id",
IssueID: "bd-cmt-ins-record",
Author: "importer",
Text: "preserved",
CreatedAt: createdAt,
}, domain.CommentOpts{})
s.Require().NoError(err)
s.Equal("imported-comment-id", inserted.ID)
s.Equal(createdAt.Truncate(time.Second), inserted.CreatedAt)
comments, err := s.commentRepo().ListByIssueIDs(s.Ctx(), []string{"bd-cmt-ins-record"}, domain.CommentOpts{})
s.Require().NoError(err)
s.Require().Len(comments["bd-cmt-ins-record"], 1)
s.Equal("imported-comment-id", comments["bd-cmt-ins-record"][0].ID)
s.Equal(createdAt.Truncate(time.Second), comments["bd-cmt-ins-record"][0].CreatedAt)
}
func (s *testSuite) commentRepo() domain.CommentSQLRepository {
return NewCommentSQLRepository(s.Runner())
}

View file

@ -145,6 +145,11 @@ func (r *dependencySQLRepositoryImpl) Insert(ctx context.Context, dep *types.Dep
); err != nil {
return fmt.Errorf("db: DependencySQLRepository.Insert: %w", err)
}
if dep.Type == types.DepParentChild {
if err := issueops.TouchDependencyCoordinationTableInTx(ctx, r.runner, dep.DependsOnID, table); err != nil {
return fmt.Errorf("db: DependencySQLRepository.Insert: %w", err)
}
}
// Record the dependency_added event on the source's event table, matching the
// embedded/issueops AddDependencyInTx path so the bd CLI and library callers

View file

@ -13,6 +13,7 @@ func (s *testSuite) TestDependencySQLRepository() {
s.Run("RejectsEmptyIDs", s.depInsertEmptyIDs)
s.Run("SameTypeIsIdempotentMetadataRefresh", s.depInsertIdempotentSameType)
s.Run("UsesDeterministicID", s.depInsertUsesDeterministicID)
s.Run("ParentChildTouchesCoordinationOnlyForNewEdge", s.depInsertParentChildTouchesCoordinationOnlyForNewEdge)
s.Run("DifferentTypeIsRejected", s.depInsertConflictingType)
s.Run("MissingTargetIssueFailsFK", s.depInsertFKViolation)
s.Run("ThreadIDPersists", s.depInsertThreadID)
@ -94,6 +95,39 @@ func (s *testSuite) depInsertUsesDeterministicID() {
s.Equal(depid.New("bd-dep-det-a", "bd-dep-det-b"), gotID)
}
func (s *testSuite) depInsertParentChildTouchesCoordinationOnlyForNewEdge() {
const keyPattern = "dependency-coordination/v1/dependencies/%"
parent, child, blocker, blocked := "bd-dep-coord-parent", "bd-dep-coord-child", "bd-dep-coord-blocker", "bd-dep-coord-blocked"
_, err := s.Runner().ExecContext(s.Ctx(), "DELETE FROM local_metadata WHERE `key` LIKE ?", keyPattern)
s.Require().NoError(err)
for _, id := range []string{parent, child, blocker, blocked} {
s.seedIssueRow(id)
}
s.Require().NoError(s.depRepo().Insert(s.Ctx(), newDep(child, parent, types.DepParentChild), "tester", domain.DepInsertOpts{}))
var value string
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT value FROM local_metadata WHERE `key` LIKE ?", keyPattern).Scan(&value))
s.NotEmpty(value, "new parent-child edge must touch its coordination row")
_, err = s.Runner().ExecContext(s.Ctx(),
"UPDATE local_metadata SET value = 'sentinel' WHERE `key` LIKE ?", keyPattern)
s.Require().NoError(err)
// Same-type re-add refreshes metadata only, so it must not rewrite the
// coordination token.
s.Require().NoError(s.depRepo().Insert(s.Ctx(), newDep(child, parent, types.DepParentChild), "tester", domain.DepInsertOpts{}))
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT value FROM local_metadata WHERE `key` LIKE ?", keyPattern).Scan(&value))
s.Equal("sentinel", value)
// A non-parent-child edge must not create a second coordination row.
s.Require().NoError(s.depRepo().Insert(s.Ctx(), newDep(blocker, blocked, types.DepBlocks), "tester", domain.DepInsertOpts{}))
var count int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM local_metadata WHERE `key` LIKE ?", keyPattern).Scan(&count))
s.Equal(1, count)
}
func (s *testSuite) depInsertRoundTrip() {
s.seedIssueRow("bd-dep-a")
s.seedIssueRow("bd-dep-b")

View file

@ -62,8 +62,8 @@ func (s *testSuite) ibUpdateCloseUnblocks() {
s.Require().True(s.isBlocked("bd-ib-up-src"))
issueRepo := NewIssueSQLRepository(s.Runner())
s.Require().NoError(issueRepo.Update(s.Ctx(), "bd-ib-up-tgt",
map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{}))
_, err := issueRepo.Close(s.Ctx(), "bd-ib-up-tgt", domain.CloseRowParams{}, "tester", domain.IssueTableOpts{})
s.Require().NoError(err)
s.False(s.isBlocked("bd-ib-up-src"), "closing the blocker must unblock its dependent")
}
@ -75,12 +75,12 @@ func (s *testSuite) ibUpdateReopenReblocks() {
newDep("bd-ib-re-src", "bd-ib-re-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{}))
issueRepo := NewIssueSQLRepository(s.Runner())
s.Require().NoError(issueRepo.Update(s.Ctx(), "bd-ib-re-tgt",
map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{}))
_, err := issueRepo.Close(s.Ctx(), "bd-ib-re-tgt", domain.CloseRowParams{}, "tester", domain.IssueTableOpts{})
s.Require().NoError(err)
s.Require().False(s.isBlocked("bd-ib-re-src"))
s.Require().NoError(issueRepo.Update(s.Ctx(), "bd-ib-re-tgt",
map[string]any{"status": string(types.StatusOpen)}, "tester", domain.IssueTableOpts{}))
_, err = issueRepo.Reopen(s.Ctx(), "bd-ib-re-tgt", domain.ReopenRowParams{}, "tester", domain.IssueTableOpts{})
s.Require().NoError(err)
s.True(s.isBlocked("bd-ib-re-src"), "reopening the blocker must re-block its dependent")
}

View file

@ -37,7 +37,7 @@ var _ domain.IssueSQLRepository = (*issueSQLRepositoryImpl)(nil)
const issueSelectColumns = sqlbuild.IssueSelectColumns
var allowedUpdateFields = map[string]struct{}{
"status": {}, "priority": {}, "title": {}, "assignee": {},
"status": {}, "priority": {}, "title": {}, "assignee": {}, "owner": {},
"description": {}, "design": {}, "acceptance_criteria": {}, "notes": {},
"issue_type": {}, "estimated_minutes": {}, "external_ref": {}, "spec_id": {},
"started_at": {}, "closed_at": {}, "close_reason": {}, "closed_by_session": {},
@ -66,6 +66,19 @@ func (r *issueSQLRepositoryImpl) Insert(ctx context.Context, issue *types.Issue,
}
table := pickIssueTable(opts.UseWispsTable)
if opts.CreateOnly {
if err := issueops.EnsureIssueIDAvailableInTx(ctx, r.runner, issue.ID); err != nil {
return err
}
if err := issueops.InsertIssueStrictInTx(ctx, r.runner, table, issue); err != nil {
return err
}
return r.events.Record(ctx, domain.Event{
IssueID: issue.ID,
Type: types.EventCreated,
Actor: actor,
}, domain.RecordEventOpts{UseWispsTable: opts.UseWispsTable})
}
if err := insertIssueRow(ctx, r.runner, table, issue); err != nil {
return err
}
@ -85,6 +98,18 @@ func (r *issueSQLRepositoryImpl) InsertBatch(ctx context.Context, issues []*type
return nil
}
func (r *issueSQLRepositoryImpl) MovePersistence(ctx context.Context, id string, mode types.PersistenceMode) (bool, error) {
issue, err := issueops.GetIssueInTx(ctx, r.runner, id)
if err != nil {
return false, fmt.Errorf("db: MovePersistence %s: get issue: %w", id, err)
}
result, err := issueops.MoveIssuePersistenceInTx(ctx, r.runner, issue, mode)
if err != nil {
return false, fmt.Errorf("db: MovePersistence %s: %w", id, err)
}
return result.Changed, nil
}
func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates map[string]any, actor string, opts domain.IssueTableOpts) error {
if id == "" {
return errors.New("db: Update: id must not be empty")
@ -92,6 +117,7 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates
if len(updates) == 0 {
return nil
}
updates = cloneUpdateFields(updates)
// Bound the VARCHAR(255) assignment columns before touching SQL, mirroring
// issueops.updateIssueInTx: an over-length assignee/owner aborts with a typed
@ -108,27 +134,17 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates
table := pickIssueTable(opts.UseWispsTable)
_, statusChanging := updates["status"]
mergeOps := issueops.HasMergeOps(updates)
// When the status changes we need the prior row to reproduce the embedded
// lifecycle side effects (issueops.updateIssueInTx): closed_at is set on
// close and cleared on reopen, started_at is set on the in_progress
// transition, the audit event type is derived from the transition, and
// is_blocked is recomputed for neighbors. Read the full old issue once so
// all four use the same snapshot; the ErrNoRows contract is preserved.
// Merge operations (metadata edits, note appends) need the same read: they
// are resolved against the row as seen by THIS unit-of-work transaction.
var oldIssue *types.Issue
if statusChanging || mergeOps {
var err error
oldIssue, err = r.Get(ctx, id, opts)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("db: Update %s: %w", id, sql.ErrNoRows)
}
return fmt.Errorf("db: Update %s: read old issue: %w", id, err)
// Read the prior row once. Status and merge updates need it for their
// transaction-local resolution, and every update uses it to suppress true
// no-ops before changing row_lock or recording an event.
oldIssue, err := r.Get(ctx, id, opts)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("db: Update %s: %w", id, sql.ErrNoRows)
}
return fmt.Errorf("db: Update %s: read old issue: %w", id, err)
}
// Resolve read-merge-write operation keys (issueops.OpMergeMetadata,
@ -149,6 +165,18 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates
updates = resolved
}
filteredUpdates, err := issueops.DiscardNoopIssueUpdates(oldIssue, updates)
if err != nil {
return fmt.Errorf("db: Update %s: compare updates: %w", id, err)
}
updates = filteredUpdates
if len(updates) == 0 {
return nil
}
// A status that matched the row was already dropped as a no-op, so the
// lifecycle side effects below only fire on a real transition.
_, statusChanging := updates["status"]
setClauses := make([]string, 0, len(updates)+3)
args := make([]any, 0, len(updates)+4)
for key, value := range updates {
@ -167,11 +195,12 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates
// Lifecycle parity with issueops.updateIssueInTx: auto-manage closed_at and
// started_at from the status transition unless the caller set them
// explicitly. Both helpers no-op when the status is unchanged.
// explicitly.
if statusChanging {
setClauses, args = issueops.ManageClosedAt(oldIssue, updates, setClauses, args)
setClauses, args = issueops.ManageStartedAt(oldIssue, updates, setClauses, args)
}
clearLease := issueops.ManageLeaseOnUpdate(oldIssue, updates)
// Rewrite row_lock on every generic update, mirroring the classic
// issueops.updateIssueInTx invariant (update.go): a concurrent
@ -198,6 +227,11 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates
if rows == 0 {
return fmt.Errorf("db: Update %s: %w", id, sql.ErrNoRows)
}
if clearLease && !opts.UseWispsTable {
if err := issueops.DeleteLeaseInTx(ctx, r.runner, id); err != nil {
return fmt.Errorf("db: Update %s: clear lease: %w", id, err)
}
}
// Event-type parity: embedded records EventClosed / EventReopened /
// EventStatusChanged for status transitions (issueops.DetermineEventType),
@ -239,6 +273,14 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates
return nil
}
func cloneUpdateFields(updates map[string]any) map[string]any {
cloned := make(map[string]any, len(updates))
for key, value := range updates {
cloned[key] = value
}
return cloned
}
func coerceStatus(v any) types.Status {
switch s := v.(type) {
case string:
@ -896,13 +938,26 @@ func (r *issueSQLRepositoryImpl) Close(ctx context.Context, id string, params do
}, nil
}
func (r *issueSQLRepositoryImpl) CloseChecked(ctx context.Context, id string, params domain.CloseRowParams, actor string, force bool) (domain.CloseRowResult, error) {
res, err := issueops.CloseIssueCheckedInTx(ctx, r.runner, id, params.Reason, actor, params.Session, force, nil)
if err != nil {
return domain.CloseRowResult{}, fmt.Errorf("db: IssueSQLRepository.CloseChecked %s: %w", id, err)
}
return domain.CloseRowResult{
Updated: !res.AlreadyClosed,
AlreadyClosed: res.AlreadyClosed,
IsWisp: res.IsWisp,
OpenChildren: res.OpenChildren,
}, nil
}
func (r *issueSQLRepositoryImpl) Reopen(ctx context.Context, id string, params domain.ReopenRowParams, actor string, opts domain.IssueTableOpts) (domain.ReopenRowResult, error) {
res, err := issueops.ReopenIssueInTx(ctx, r.runner, id, params.Reason, actor)
if err != nil {
return domain.ReopenRowResult{}, fmt.Errorf("db: IssueSQLRepository.Reopen %s: %w", id, err)
}
return domain.ReopenRowResult{
Updated: !res.AlreadyOpen,
Updated: res.Changed,
AlreadyOpen: res.AlreadyOpen,
IsWisp: res.IsWisp,
}, nil

View file

@ -0,0 +1,97 @@
package db
import (
"strings"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
func (s *testSuite) TestParentTierControlsInheritedLabels() {
s.Run("durable parent to wisp child", func() {
s.resetMintConfig("tier-durable-parent", "")
uc := s.issueUseCase()
parent, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "durable parent", IssueType: types.TypeEpic, Priority: 2},
Labels: []string{"durable-parent-label"},
}, "tester")
s.Require().NoError(err)
child, err := uc.CreateWisp(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "wisp child", IssueType: types.TypeTask, Priority: 2, Ephemeral: true},
ParentID: parent.Issue.ID,
InheritLabelsFromParent: true,
}, "tester")
s.Require().NoError(err)
s.True(strings.HasPrefix(child.Issue.ID, parent.Issue.ID+"."), "child ID %q must use canonical parent child minting", child.Issue.ID)
s.Equal([]string{"durable-parent-label"}, child.InheritedLabels)
labels, err := s.labelUseCase().GetWispLabels(s.Ctx(), child.Issue.ID)
s.Require().NoError(err)
s.Equal([]string{"durable-parent-label"}, labels)
})
s.Run("wisp parent to durable child", func() {
s.resetMintConfig("tier-wisp-parent", "")
uc := s.issueUseCase()
parent, err := uc.CreateWisp(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "wisp parent", IssueType: types.TypeEpic, Priority: 2, Ephemeral: true},
Labels: []string{"wisp-parent-label"},
}, "tester")
s.Require().NoError(err)
child, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "durable child", IssueType: types.TypeTask, Priority: 2},
ParentID: parent.Issue.ID,
InheritLabelsFromParent: true,
}, "tester")
s.Require().NoError(err)
s.True(strings.HasPrefix(child.Issue.ID, parent.Issue.ID+"."), "child ID %q must use canonical parent child minting", child.Issue.ID)
s.Equal([]string{"wisp-parent-label"}, child.InheritedLabels)
labels, err := s.labelUseCase().GetLabels(s.Ctx(), child.Issue.ID)
s.Require().NoError(err)
s.Equal([]string{"wisp-parent-label"}, labels)
})
}
func (s *testSuite) TestReverseCreateDependencyUsesActualSourceTier() {
s.resetMintConfig("tier-reverse-dependency", "")
uc := s.issueUseCase()
wispSource, err := uc.CreateWisp(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "wisp source", IssueType: types.TypeTask, Priority: 2, Ephemeral: true},
}, "tester")
s.Require().NoError(err)
durableTarget, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "durable target", IssueType: types.TypeTask, Priority: 2},
Dependencies: []domain.DependencySpec{{
Type: types.DepRelated, TargetID: wispSource.Issue.ID, SwapDirection: true,
Metadata: `{"from":"wisp"}`, ThreadID: "wisp-thread",
}},
}, "tester")
s.Require().NoError(err)
wispRecords, err := s.depUseCase().GetWispDependencyRecords(s.Ctx(), []string{wispSource.Issue.ID})
s.Require().NoError(err)
s.Require().Len(wispRecords[wispSource.Issue.ID], 1)
s.Equal(durableTarget.Issue.ID, wispRecords[wispSource.Issue.ID][0].DependsOnID)
s.Equal(`{"from":"wisp"}`, wispRecords[wispSource.Issue.ID][0].Metadata)
s.Equal("wisp-thread", wispRecords[wispSource.Issue.ID][0].ThreadID)
durableSource, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "durable source", IssueType: types.TypeTask, Priority: 2},
}, "tester")
s.Require().NoError(err)
wispTarget, err := uc.CreateWisp(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "wisp target", IssueType: types.TypeTask, Priority: 2, Ephemeral: true},
Dependencies: []domain.DependencySpec{{
Type: types.DepRelated, TargetID: durableSource.Issue.ID, SwapDirection: true,
Metadata: `{"from":"durable"}`, ThreadID: "durable-thread",
}},
}, "tester")
s.Require().NoError(err)
durableRecords, err := s.depUseCase().GetIssueDependencyRecords(s.Ctx(), []string{durableSource.Issue.ID})
s.Require().NoError(err)
s.Require().Len(durableRecords[durableSource.Issue.ID], 1)
s.Equal(wispTarget.Issue.ID, durableRecords[durableSource.Issue.ID][0].DependsOnID)
s.Equal(`{"from":"durable"}`, durableRecords[durableSource.Issue.ID][0].Metadata)
s.Equal("durable-thread", durableRecords[durableSource.Issue.ID][0].ThreadID)
}

View file

@ -42,13 +42,13 @@ func TestScanIssue_StringTimestamps(t *testing.T) {
for i := range cols {
cols[i] = strings.TrimSpace(cols[i])
}
require.Len(t, cols, 51)
require.Len(t, cols, 52)
row := []driver.Value{
"bd-test.1", nil, "title", "desc", "", "", "", // id..notes
"open", 1, "task", nil, nil, // status..estimated_minutes
"2026-06-12 10:00:00", nil, nil, "2026-06-12T10:00:01Z", nil, nil, nil, nil, // created_at..spec_id
0, nil, nil, nil, nil, nil, // compaction_level..close_reason
0, nil, nil, nil, nil, nil, nil, // compaction_level..closed_by_session
nil, nil, nil, nil, nil, nil, // sender..is_template
nil, nil, nil, nil, // await_type..waiters
nil, // mol_type
@ -59,7 +59,7 @@ func TestScanIssue_StringTimestamps(t *testing.T) {
nil, // storage_class
nil, nil, nil, // lease_expires_at, heartbeat_at, granted_node
}
require.Len(t, row, 51)
require.Len(t, row, 52)
mock.ExpectQuery("SELECT").WillReturnRows(sqlmock.NewRows(cols).AddRow(row...))

View file

@ -31,6 +31,8 @@ func (s *testSuite) TestIssueSQLRepository() {
s.Run("NormalizesStatusType", s.issueUpdateStatusType)
s.Run("NormalizesTimestampToUTC", s.issueUpdateNormalizesTimestamp)
s.Run("MissingIDWithStatusChangeReturnsErrNoRows", s.issueUpdateMissingIDWithStatus)
s.Run("SameStatusInUnitOfWork", s.issueUpdateSameStatusInUnitOfWork)
s.Run("PreservesCallerMap", s.issueUpdatePreservesCallerMap)
})
s.Run("RowVersion", func() {
s.Run("NonZeroAfterCreate", s.issueRowVersionNonZeroOnCreate)
@ -696,8 +698,8 @@ func (s *testSuite) issueClaimConflict() {
func (s *testSuite) issueClaimClosed() {
r := s.issueRepo()
s.Require().NoError(r.Insert(s.Ctx(), newTestIssue("bd-claim-closed", "x"), "tester", domain.InsertIssueOpts{}))
s.Require().NoError(r.Update(s.Ctx(), "bd-claim-closed",
map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{}))
_, err := r.Close(s.Ctx(), "bd-claim-closed", domain.CloseRowParams{}, "tester", domain.IssueTableOpts{})
s.Require().NoError(err)
res, err := r.Claim(s.Ctx(), "bd-claim-closed", "alice", domain.IssueTableOpts{})
s.Require().NoError(err)

View file

@ -0,0 +1,236 @@
package db
import (
"errors"
"strings"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
func (s *testSuite) TestIssueUpdateRejectsInvalidCanonicalFields() {
created, err := s.issueUseCase().CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{
ID: "bd-domain-invalid-update",
Title: "valid incumbent",
IssueType: types.TypeTask,
Priority: 2,
},
}, "tester")
s.Require().NoError(err)
incumbent, err := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID)
s.Require().NoError(err)
var eventCount int
s.Require().NoError(s.Runner().QueryRowContext(
s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ?",
created.Issue.ID,
).Scan(&eventCount))
checks := []struct {
name string
updates map[string]any
}{
{"empty title", map[string]any{"title": ""}},
{"overlong title", map[string]any{"title": strings.Repeat("x", 501)}},
{"negative priority", map[string]any{"priority": -1}},
{"priority above maximum", map[string]any{"priority": 5}},
{"negative estimated minutes", map[string]any{"estimated_minutes": -1}},
}
for _, check := range checks {
s.Run(check.name, func() {
err := s.issueUseCase().UpdateIssue(s.Ctx(), created.Issue.ID, check.updates, "tester")
s.ErrorIs(err, storage.ErrValidation)
stored, getErr := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID)
s.Require().NoError(getErr)
s.Equal("valid incumbent", stored.Title)
s.Equal(2, stored.Priority)
s.Nil(stored.EstimatedMinutes)
s.Equal(incumbent.RowVersion, stored.RowVersion)
var afterEvents int
s.Require().NoError(s.Runner().QueryRowContext(
s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ?",
created.Issue.ID,
).Scan(&afterEvents))
s.True(errors.Is(err, storage.ErrValidation))
s.Equal(eventCount, afterEvents)
})
}
}
func (s *testSuite) TestIssueUpdateRejectsUnsupportedCanonicalFieldTypes() {
checks := []struct {
name string
id string
updates map[string]any
}{
{"non-string title", "bd-domain-title-type", map[string]any{"title": 7}},
{"int64 priority", "bd-domain-priority-type", map[string]any{"priority": int64(-1)}},
{"int64 estimated minutes", "bd-domain-estimate-type", map[string]any{"estimated_minutes": int64(-1)}},
}
for _, check := range checks {
s.Run(check.name, func() {
created, err := s.issueUseCase().CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{
ID: check.id,
Title: "valid incumbent",
IssueType: types.TypeTask,
Priority: 2,
},
}, "tester")
s.Require().NoError(err)
before, err := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID)
s.Require().NoError(err)
var beforeEvents int
s.Require().NoError(s.Runner().QueryRowContext(
s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ?",
created.Issue.ID,
).Scan(&beforeEvents))
err = s.issueUseCase().UpdateIssue(s.Ctx(), created.Issue.ID, check.updates, "tester")
s.ErrorIs(err, storage.ErrValidation)
after, getErr := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID)
s.Require().NoError(getErr)
s.Equal(before.Title, after.Title)
s.Equal(before.Priority, after.Priority)
s.Equal(before.EstimatedMinutes, after.EstimatedMinutes)
s.Equal(before.Status, after.Status)
s.Equal(before.Assignee, after.Assignee)
s.Equal(before.RowVersion, after.RowVersion)
var afterEvents int
s.Require().NoError(s.Runner().QueryRowContext(
s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ?",
created.Issue.ID,
).Scan(&afterEvents))
s.Equal(beforeEvents, afterEvents)
})
}
}
func (s *testSuite) TestApplyUpdateValidatesFieldsBeforeClaim() {
created, err := s.issueUseCase().CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{
ID: "bd-domain-validate-before-claim",
Title: "valid incumbent",
IssueType: types.TypeTask,
Priority: 2,
},
}, "tester")
s.Require().NoError(err)
before, err := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID)
s.Require().NoError(err)
var beforeEvents int
s.Require().NoError(s.Runner().QueryRowContext(
s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ?",
created.Issue.ID,
).Scan(&beforeEvents))
_, err = s.issueUseCase().ApplyUpdate(s.Ctx(), created.Issue.ID, domain.UpdateSpec{
Claim: true,
Fields: map[string]any{"title": ""},
}, "claimant")
s.ErrorIs(err, storage.ErrValidation)
after, getErr := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID)
s.Require().NoError(getErr)
s.Equal(before.Title, after.Title)
s.Equal(before.Priority, after.Priority)
s.Equal(before.EstimatedMinutes, after.EstimatedMinutes)
s.Equal(before.Status, after.Status)
s.Equal(before.Assignee, after.Assignee)
s.Equal(before.RowVersion, after.RowVersion)
var afterEvents int
s.Require().NoError(s.Runner().QueryRowContext(
s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ?",
created.Issue.ID,
).Scan(&afterEvents))
s.Equal(beforeEvents, afterEvents)
}
func (s *testSuite) TestApplyUpdateValidatesIssueTypeBeforeClaim() {
created, err := s.issueUseCase().CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{
ID: "bd-domain-validate-type-before-claim",
Title: "valid incumbent",
IssueType: types.TypeTask,
Priority: 2,
},
}, "tester")
s.Require().NoError(err)
before, err := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID)
s.Require().NoError(err)
var beforeEvents int
s.Require().NoError(s.Runner().QueryRowContext(
s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ?",
created.Issue.ID,
).Scan(&beforeEvents))
_, err = s.issueUseCase().ApplyUpdate(s.Ctx(), created.Issue.ID, domain.UpdateSpec{
Claim: true,
Fields: map[string]any{"issue_type": "bogus"},
}, "claimant")
s.ErrorIs(err, storage.ErrValidation)
after, getErr := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID)
s.Require().NoError(getErr)
s.Equal(before.IssueType, after.IssueType)
s.Equal(before.Status, after.Status)
s.Equal(before.Assignee, after.Assignee)
s.Equal(before.RowVersion, after.RowVersion)
var afterEvents int
s.Require().NoError(s.Runner().QueryRowContext(
s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ?",
created.Issue.ID,
).Scan(&afterEvents))
s.Equal(beforeEvents, afterEvents)
}
func (s *testSuite) TestIssueUpdateAcceptsLegacyIssueTypeRepresentations() {
checks := []struct {
name string
id string
issueType any
want types.IssueType
}{
{"string", "bd-domain-type-string", "bug", types.TypeBug},
{"typed", "bd-domain-type-typed", types.TypeFeature, types.TypeFeature},
}
for _, check := range checks {
s.Run(check.name, func() {
created, err := s.issueUseCase().CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{
ID: check.id,
Title: "legacy type representation",
IssueType: types.TypeTask,
Priority: 2,
},
}, "tester")
s.Require().NoError(err)
err = s.issueUseCase().UpdateIssue(s.Ctx(), created.Issue.ID, map[string]any{
"issue_type": check.issueType,
}, "tester")
s.Require().NoError(err)
updated, err := s.issueUseCase().GetIssue(s.Ctx(), created.Issue.ID)
s.Require().NoError(err)
s.Equal(check.want, updated.IssueType)
})
}
}

View file

@ -1,6 +1,8 @@
package db
import (
"database/sql"
"encoding/json"
"errors"
"github.com/steveyegge/beads/internal/storage"
@ -25,12 +27,15 @@ func (s *testSuite) TestIssueUseCase_ApplyUpdate() {
s.Run("ClaimAndFieldsRunTogether", s.iucApplyUpdateClaimPlusFields)
s.Run("AddRemoveLabelPaths", s.iucApplyUpdateAddRemoveLabels)
s.Run("SetLabelsDiffsAgainstCurrent", s.iucApplyUpdateSetLabels)
s.Run("SetLabelsTakesPrecedenceOverAddRemove", s.iucApplyUpdateSetLabelsBeatsAddRemove)
s.Run("SetLabelsThenAddsThenRemoves", s.iucApplyUpdateSetLabelsThenAddRemove)
s.Run("SameScalarAndMetadataAreNoops", s.iucApplyUpdateSameScalarAndMetadataAreNoops)
s.Run("ReparentReplacesParent", s.iucApplyUpdateReparent)
s.Run("ReparentEmptyUnparents", s.iucApplyUpdateUnparent)
s.Run("NoSpecBitsIsHarmless", s.iucApplyUpdateEmptySpec)
s.Run("WispIDDispatchesToWispTables", s.iucApplyUpdateDispatchesToWisp)
s.Run("ClaimAgainstWispDispatches", s.iucClaimDispatchesToWisp)
s.Run("ExpectedVersionRefusesStaleWrite", s.iucApplyUpdateExpectedVersion)
s.Run("PersistenceMovesNoOpsAndRollsBack", s.iucApplyUpdatePersistence)
}
func (s *testSuite) seedOpenIssue(id string) {
@ -91,11 +96,10 @@ func (s *testSuite) iucClaimOpenAssignedCopy() {
func (s *testSuite) iucClaimClosed() {
s.seedOpenIssue("bd-iuc-cl-closed")
r := s.issueRepo()
s.Require().NoError(r.Update(s.Ctx(), "bd-iuc-cl-closed",
map[string]any{"status": string(types.StatusClosed)}, "seeder", domain.IssueTableOpts{}))
_, err := s.issueUseCase().CloseIssue(s.Ctx(), "bd-iuc-cl-closed", domain.CloseIssueParams{}, "seeder")
s.Require().NoError(err)
_, err := s.issueUseCase().ClaimIssue(s.Ctx(), "bd-iuc-cl-closed", "alice")
_, err = s.issueUseCase().ClaimIssue(s.Ctx(), "bd-iuc-cl-closed", "alice")
s.Require().Error(err)
s.True(errors.Is(err, storage.ErrNotClaimable), "expected ErrNotClaimable, got %v", err)
}
@ -175,21 +179,37 @@ func (s *testSuite) iucApplyUpdateSetLabels() {
s.Equal([]string{"y", "z"}, labels)
}
func (s *testSuite) iucApplyUpdateSetLabelsBeatsAddRemove() {
s.seedOpenIssue("bd-iuc-au-sl-prec")
uc := s.issueUseCase()
desired := []string{"only-this"}
_, err := uc.ApplyUpdate(s.Ctx(), "bd-iuc-au-sl-prec", domain.UpdateSpec{
AddLabels: []string{"add-me"},
RemoveLabels: []string{"remove-me"},
func (s *testSuite) iucApplyUpdateSetLabelsThenAddRemove() {
s.seedOpenIssue("bd-iuc-au-sl-order")
desired := []string{"replace", "remove"}
_, err := s.issueUseCase().ApplyUpdate(s.Ctx(), "bd-iuc-au-sl-order", domain.UpdateSpec{
SetLabels: &desired,
AddLabels: []string{"add", "remove"},
RemoveLabels: []string{"remove"},
}, "tester")
s.Require().NoError(err)
labels, err := s.labelUseCase().GetLabels(s.Ctx(), "bd-iuc-au-sl-prec")
labels, err := s.labelUseCase().GetLabels(s.Ctx(), "bd-iuc-au-sl-order")
s.Require().NoError(err)
s.Equal([]string{"only-this"}, labels)
s.Equal([]string{"add", "replace"}, labels)
}
func (s *testSuite) iucApplyUpdateSameScalarAndMetadataAreNoops() {
s.seedOpenIssue("bd-iuc-au-noop")
uc := s.issueUseCase()
before, err := uc.GetIssue(s.Ctx(), "bd-iuc-au-noop")
s.Require().NoError(err)
var beforeEvents int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), "SELECT COUNT(*) FROM events WHERE issue_id = ?", before.ID).Scan(&beforeEvents))
updated, err := uc.ApplyUpdate(s.Ctx(), before.ID, domain.UpdateSpec{Fields: map[string]any{
"priority": before.Priority,
"metadata": json.RawMessage(`{}`),
}}, "tester")
s.Require().NoError(err)
s.Equal(before.RowVersion, updated.RowVersion)
var afterEvents int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), "SELECT COUNT(*) FROM events WHERE issue_id = ?", before.ID).Scan(&afterEvents))
s.Equal(beforeEvents, afterEvents)
}
func (s *testSuite) iucApplyUpdateReparent() {
@ -232,6 +252,53 @@ func (s *testSuite) iucApplyUpdateEmptySpec() {
s.Equal("bd-iuc-au-empty", updated.ID)
}
func (s *testSuite) iucApplyUpdateExpectedVersion() {
s.seedOpenIssue("bd-iuc-au-version")
current, err := s.issueUseCase().GetIssue(s.Ctx(), "bd-iuc-au-version")
s.Require().NoError(err)
staleVersion := current.RowVersion + 1
_, err = s.issueUseCase().ApplyUpdate(s.Ctx(), "bd-iuc-au-version", domain.UpdateSpec{
ExpectedVersion: &staleVersion,
Fields: map[string]any{"title": "must not persist"},
}, "tester")
s.Require().Error(err)
s.True(errors.Is(err, storage.ErrVersionMismatch), "want ErrVersionMismatch, got %v", err)
stored, err := s.issueUseCase().GetIssue(s.Ctx(), "bd-iuc-au-version")
s.Require().NoError(err)
s.Equal("seed", stored.Title)
}
func (s *testSuite) iucApplyUpdatePersistence() {
s.seedOpenIssue("bd-iuc-au-persist")
mode := types.PersistenceModeEphemeral
moved, err := s.issueUseCase().ApplyUpdate(s.Ctx(), "bd-iuc-au-persist", domain.UpdateSpec{Persistence: &mode}, "tester")
s.Require().NoError(err)
s.True(moved.Ephemeral)
_, err = s.issueRepo().Get(s.Ctx(), "bd-iuc-au-persist", domain.IssueTableOpts{})
s.True(errors.Is(err, sql.ErrNoRows), "durable source must be removed, got %v", err)
stored, err := s.issueRepo().Get(s.Ctx(), "bd-iuc-au-persist", domain.IssueTableOpts{UseWispsTable: true})
s.Require().NoError(err)
version := stored.RowVersion
unchanged, err := s.issueUseCase().ApplyUpdate(s.Ctx(), "bd-iuc-au-persist", domain.UpdateSpec{Persistence: &mode}, "tester")
s.Require().NoError(err)
s.Equal(version, unchanged.RowVersion, "same persistence mode must not rewrite the row")
s.seedOpenIssue("bd-iuc-au-persist-rollback")
_, err = s.issueUseCase().ApplyUpdate(s.Ctx(), "bd-iuc-au-persist-rollback", domain.UpdateSpec{
Fields: map[string]any{"not_a_column": "bad"},
Persistence: &mode,
}, "tester")
s.Require().Error(err)
_, err = s.issueRepo().Get(s.Ctx(), "bd-iuc-au-persist-rollback", domain.IssueTableOpts{})
s.Require().NoError(err)
_, err = s.issueRepo().Get(s.Ctx(), "bd-iuc-au-persist-rollback", domain.IssueTableOpts{UseWispsTable: true})
s.True(errors.Is(err, sql.ErrNoRows), "failed update must not move persistence plane, got %v", err)
}
func (s *testSuite) seedOpenWisp(id string) {
r := s.issueRepo()
w := newTestIssue(id, "seed wisp")

View file

@ -2,8 +2,11 @@ package db
import (
"database/sql"
"errors"
"strings"
"time"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
@ -16,6 +19,9 @@ func (s *testSuite) TestIssueUseCase_MintTopLevelID() {
s.Run("IDPrefixSubprefixHonored", s.useCaseMintRespectsIDPrefix)
s.Run("WispUsesWispPrefix", s.useCaseMintWispPrefix)
s.Run("MissingConfigPrefixErrors", s.useCaseMintMissingPrefix)
s.Run("ExplicitIDRequiresConfiguredPrefixUnlessForced", s.useCaseExplicitIDPrefixGuard)
s.Run("CreateOnlyRefusesOccupiedID", s.useCaseCreateOnlyRefusesOccupiedID)
s.Run("CreateAttachesNormalizedComments", s.useCaseCreateAttachesNormalizedComments)
}
func (s *testSuite) issueUseCase() domain.IssueUseCase {
@ -152,6 +158,91 @@ func (s *testSuite) useCaseMintMissingPrefix() {
s.Contains(err.Error(), "issue_prefix")
}
func (s *testSuite) useCaseExplicitIDPrefixGuard() {
s.resetMintConfig("prefixguard", "")
uc := s.issueUseCase()
upsert, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "foreign upsert", IssueType: types.TypeTask, Priority: 2},
ExplicitID: "foreign-upsert-1",
}, "tester")
s.Require().NoError(err)
s.Equal("foreign-upsert-1", upsert.Issue.ID)
_, err = uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "foreign", IssueType: types.TypeTask, Priority: 2},
ExplicitID: "foreign-1",
CreateOnly: true,
}, "tester")
s.Require().Error(err)
s.True(errors.Is(err, storage.ErrPrefixMismatch), "want ErrPrefixMismatch, got %v", err)
s.Require().NoError(NewConfigSQLRepository(s.Runner()).SetConfig(s.Ctx(), "allowed_prefixes", "allowed"))
allowed, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "allowed", IssueType: types.TypeTask, Priority: 2},
ExplicitID: "allowed-1",
CreateOnly: true,
}, "tester")
s.Require().NoError(err)
s.Equal("allowed-1", allowed.Issue.ID)
created, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "forced", IssueType: types.TypeTask, Priority: 2},
ExplicitID: "foreign-1",
ForcePrefix: true,
CreateOnly: true,
}, "tester")
s.Require().NoError(err)
s.Equal("foreign-1", created.Issue.ID)
}
func (s *testSuite) useCaseCreateOnlyRefusesOccupiedID() {
s.resetMintConfig("createonly", "")
uc := s.issueUseCase()
params := domain.CreateIssueParams{
Issue: &types.Issue{Title: "first", IssueType: types.TypeTask, Priority: 2},
ExplicitID: "createonly-1",
CreateOnly: true,
}
_, err := uc.CreateIssue(s.Ctx(), params, "tester")
s.Require().NoError(err)
params.Issue = &types.Issue{Title: "replacement", IssueType: types.TypeTask, Priority: 2}
_, err = uc.CreateIssue(s.Ctx(), params, "tester")
s.Require().Error(err)
s.True(errors.Is(err, storage.ErrAlreadyExists), "want ErrAlreadyExists, got %v", err)
stored, err := uc.GetIssue(s.Ctx(), "createonly-1")
s.Require().NoError(err)
s.Equal("first", stored.Title)
}
func (s *testSuite) useCaseCreateAttachesNormalizedComments() {
s.resetMintConfig("comments", "")
createdAt := time.Date(2025, time.February, 3, 4, 5, 6, 0, time.UTC)
params := domain.CreateIssueParams{
Issue: &types.Issue{Title: "with comments", IssueType: types.TypeTask, Priority: 2},
ExplicitID: "comments-1",
Comments: []*types.Comment{
{Text: "defaulted"},
{ID: "imported-comment", Author: "importer", Text: "preserved", CreatedAt: createdAt},
},
}
created, err := s.issueUseCase().CreateIssue(s.Ctx(), params, "actor")
s.Require().NoError(err)
s.Require().Len(created.Issue.Comments, 2)
s.Equal("comments-1", created.Issue.Comments[0].IssueID)
s.Equal("actor", created.Issue.Comments[0].Author)
s.NotEmpty(created.Issue.Comments[0].ID)
s.False(created.Issue.Comments[0].CreatedAt.IsZero())
s.Equal("imported-comment", created.Issue.Comments[1].ID)
s.Equal("importer", created.Issue.Comments[1].Author)
s.Equal(createdAt, created.Issue.Comments[1].CreatedAt)
s.Equal("", params.Comments[0].IssueID, "create must not mutate caller comments")
}
func (s *testSuite) TestIssueUseCase_ApplyGraph() {
s.Run("ChildrenBeforeParentsSucceed", s.applyGraphChildrenBeforeParents)
s.Run("ExplicitParentChildEdgeIsDeduped", s.applyGraphParentChildEdgeDedup)
@ -171,6 +262,33 @@ func (s *testSuite) TestIssueUseCase_ApplyGraph() {
func (s *testSuite) TestIssueUseCase_MixedParentChildRouting() {
s.Run("WispChildOfRegularParent", s.mixedWispChildOfRegularParent)
s.Run("DepTargetClassification", s.mixedDepTargetClassification)
s.Run("ReverseDependencyUsesResultingSourceTierAndPreservesThread", s.mixedReverseDependencySourceTier)
}
func (s *testSuite) mixedReverseDependencySourceTier() {
s.resetMintConfig("reverse", "")
uc := s.issueUseCase()
regular, err := uc.CreateIssue(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "regular source", IssueType: types.TypeTask, Priority: 2},
}, "tester")
s.Require().NoError(err)
wisp, err := uc.CreateWisp(s.Ctx(), domain.CreateIssueParams{
Issue: &types.Issue{Title: "wisp target", IssueType: types.TypeTask, Priority: 2, Ephemeral: true},
Dependencies: []domain.DependencySpec{{
Type: types.DepRelated,
TargetID: regular.Issue.ID,
SwapDirection: true,
ThreadID: "thread-1",
}},
}, "tester")
s.Require().NoError(err)
records, err := s.depUseCase().GetIssueDependencyRecords(s.Ctx(), []string{regular.Issue.ID})
s.Require().NoError(err)
s.Require().Len(records[regular.Issue.ID], 1)
s.Equal(wisp.Issue.ID, records[regular.Issue.ID][0].DependsOnID)
s.Equal("thread-1", records[regular.Issue.ID][0].ThreadID)
}
func (s *testSuite) mixedWispChildOfRegularParent() {

View file

@ -48,12 +48,32 @@ func (r *labelSQLRepositoryImpl) Insert(ctx context.Context, issueID, label, act
}
table := pickLabelTable(opts.UseWispsTable)
//nolint:gosec // G201: table is one of two hardcoded constants
if _, err := r.runner.ExecContext(ctx,
result, err := r.runner.ExecContext(ctx,
fmt.Sprintf("INSERT IGNORE INTO %s (issue_id, label) VALUES (?, ?)", table),
issueID, label,
); err != nil {
)
if err != nil {
return fmt.Errorf("db: LabelSQLRepository.Insert %s/%s: %w", issueID, label, err)
}
rows, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("db: LabelSQLRepository.Insert %s/%s: rows affected: %w", issueID, label, err)
}
if rows == 0 {
issueTable := "issues"
if opts.UseWispsTable {
issueTable = "wisps"
}
var count int
//nolint:gosec // G201: issueTable is one of two hardcoded constants.
if err := r.runner.QueryRowContext(ctx, fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE id = ?", issueTable), issueID).Scan(&count); err != nil {
return fmt.Errorf("db: LabelSQLRepository.Insert %s/%s: verify issue: %w", issueID, label, err)
}
if count == 0 {
return fmt.Errorf("db: LabelSQLRepository.Insert %s/%s: issue does not exist", issueID, label)
}
return nil
}
return r.events.Record(ctx, domain.Event{
IssueID: issueID,
Type: types.EventLabelAdded,
@ -71,12 +91,20 @@ func (r *labelSQLRepositoryImpl) Delete(ctx context.Context, issueID, label, act
}
table := pickLabelTable(opts.UseWispsTable)
//nolint:gosec // G201: table is one of two hardcoded constants
if _, err := r.runner.ExecContext(ctx,
result, err := r.runner.ExecContext(ctx,
fmt.Sprintf("DELETE FROM %s WHERE issue_id = ? AND label = ?", table),
issueID, label,
); err != nil {
)
if err != nil {
return fmt.Errorf("db: LabelSQLRepository.Delete %s/%s: %w", issueID, label, err)
}
rows, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("db: LabelSQLRepository.Delete %s/%s: rows affected: %w", issueID, label, err)
}
if rows == 0 {
return nil
}
return r.events.Record(ctx, domain.Event{
IssueID: issueID,
Type: types.EventLabelRemoved,

View file

@ -69,7 +69,7 @@ func (s *testSuite) labelInsertIdempotent() {
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?",
"bd-lbl-dup", string(types.EventLabelAdded),
).Scan(&count))
s.Equal(2, count)
s.Equal(1, count)
}
func (s *testSuite) labelInsertRecordsEvent() {
@ -259,6 +259,12 @@ func (s *testSuite) labelDeleteMissingNoop() {
out, err := r.List(s.Ctx(), "bd-lbl-del-miss", domain.LabelOpts{})
s.Require().NoError(err)
s.Empty(out)
var count int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?",
"bd-lbl-del-miss", string(types.EventLabelRemoved),
).Scan(&count))
s.Equal(0, count)
}
func (s *testSuite) labelDeleteSpecificLabel() {

View file

@ -210,8 +210,8 @@ func (s *testSuite) blockedExcludesClosed() {
s.Require().NoError(r.Insert(s.Ctx(), tgt, "tester", domain.InsertIssueOpts{}))
s.Require().NoError(dr.Insert(s.Ctx(),
newDep("bd-blc-src", "bd-blc-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{}))
s.Require().NoError(r.Update(s.Ctx(), "bd-blc-src",
map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{}))
_, err := r.Close(s.Ctx(), "bd-blc-src", domain.CloseRowParams{}, "tester", domain.IssueTableOpts{})
s.Require().NoError(err)
out, err := r.GetBlockedIssues(s.Ctx(), types.WorkFilter{})
s.Require().NoError(err)
@ -230,8 +230,8 @@ func (s *testSuite) blockedUnblocksOnClose() {
s.Require().NoError(dr.Insert(s.Ctx(),
newDep("bd-bluc-src", "bd-bluc-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{}))
s.Require().NoError(r.Update(s.Ctx(), "bd-bluc-tgt",
map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{}))
_, err := r.Close(s.Ctx(), "bd-bluc-tgt", domain.CloseRowParams{}, "tester", domain.IssueTableOpts{})
s.Require().NoError(err)
out, err := r.GetBlockedIssues(s.Ctx(), types.WorkFilter{})
s.Require().NoError(err)

View file

@ -1,6 +1,9 @@
package db
import (
"database/sql"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
@ -13,6 +16,10 @@ func (s *testSuite) TestIssueSQLRepositoryReopen() {
s.Run("RoutesWisp", s.reopenRoutesWisp)
s.Run("AppendsCommentOnReason", s.reopenAppendsComment)
s.Run("NoCommentOnEmptyReason", s.reopenNoCommentEmptyReason)
s.Run("ReopensCustomDonePermanentAndClearsLifecycleFields", s.reopenCustomDonePermanent)
s.Run("ReopensCustomDoneWisp", s.reopenCustomDoneWisp)
s.Run("LeavesCustomNonDoneAndUnspecifiedStatusesUntouched", s.reopenLeavesIneligibleStatusesUntouched)
s.Run("ConfigurationFailureRollsBack", s.reopenConfigurationFailureRollsBack)
}
func (s *testSuite) reopenMutatesRow() {
@ -21,6 +28,11 @@ func (s *testSuite) reopenMutatesRow() {
_, err := r.Close(s.Ctx(), "bd-ro-row",
domain.CloseRowParams{Reason: "done", Session: "sess-1"}, "tester", domain.IssueTableOpts{})
s.Require().NoError(err)
_, err = s.Runner().ExecContext(s.Ctx(), `
INSERT INTO leases (issue_id, holder, granted_at, lease_expires_at, heartbeat_at)
VALUES (?, ?, UTC_TIMESTAMP(), DATE_ADD(UTC_TIMESTAMP(), INTERVAL 5 MINUTE), UTC_TIMESTAMP())
`, "bd-ro-row", "stale-worker")
s.Require().NoError(err)
res, err := r.Reopen(s.Ctx(), "bd-ro-row",
domain.ReopenRowParams{Reason: "not really done"}, "tester", domain.IssueTableOpts{})
@ -44,6 +56,11 @@ func (s *testSuite) reopenMutatesRow() {
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?",
"bd-ro-row", string(types.EventReopened)).Scan(&evtCount))
s.Equal(1, evtCount)
var leaseCount int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM leases WHERE issue_id = ?", "bd-ro-row").Scan(&leaseCount))
s.Equal(0, leaseCount, "reopen must remove a seeded lease")
}
func (s *testSuite) reopenIdempotent() {
@ -86,6 +103,7 @@ func (s *testSuite) reopenMissingID() {
_, err := r.Reopen(s.Ctx(), "bd-ro-missing",
domain.ReopenRowParams{}, "tester", domain.IssueTableOpts{})
s.Require().Error(err)
s.ErrorIs(err, storage.ErrNotFound)
}
func (s *testSuite) reopenRoutesWisp() {
@ -148,3 +166,158 @@ func (s *testSuite) reopenNoCommentEmptyReason() {
"bd-ro-nocmt", string(types.EventCommented)).Scan(&cmtCount))
s.Equal(0, cmtCount)
}
func (s *testSuite) reopenCustomDonePermanent() {
const customStatus = "archived-permanent"
s.seedIssueRow("bd-ro-custom-done")
_, err := s.Runner().ExecContext(s.Ctx(),
"INSERT INTO custom_statuses (name, category) VALUES (?, ?)", customStatus, string(types.CategoryDone))
s.Require().NoError(err)
_, err = s.Runner().ExecContext(s.Ctx(), `
UPDATE issues
SET status = ?, closed_at = UTC_TIMESTAMP(), close_reason = ?, closed_by_session = ?,
defer_until = DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 DAY)
WHERE id = ?
`, customStatus, "completed", "session-1", "bd-ro-custom-done")
s.Require().NoError(err)
res, err := NewIssueSQLRepository(s.Runner()).Reopen(s.Ctx(), "bd-ro-custom-done",
domain.ReopenRowParams{Reason: "needs another pass"}, "tester", domain.IssueTableOpts{})
s.Require().NoError(err)
s.True(res.Updated)
var status, closeReason, closedBySession string
var closedAt, deferUntil sql.NullTime
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), `
SELECT status, closed_at, close_reason, closed_by_session, defer_until
FROM issues WHERE id = ?
`, "bd-ro-custom-done").Scan(&status, &closedAt, &closeReason, &closedBySession, &deferUntil))
s.Equal(string(types.StatusOpen), status)
s.False(closedAt.Valid, "closed_at must be cleared")
s.Equal("", closeReason)
s.Equal("", closedBySession)
s.False(deferUntil.Valid, "defer_until must be cleared")
var reopened, comments int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", "bd-ro-custom-done", string(types.EventReopened)).Scan(&reopened))
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", "bd-ro-custom-done", string(types.EventCommented)).Scan(&comments))
s.Equal(1, reopened)
s.Equal(1, comments)
}
func (s *testSuite) reopenCustomDoneWisp() {
const customStatus = "archived-wisp"
s.seedWispRow("bd-ro-custom-done-wisp")
_, err := s.Runner().ExecContext(s.Ctx(),
"INSERT INTO custom_statuses (name, category) VALUES (?, ?)", customStatus, string(types.CategoryDone))
s.Require().NoError(err)
_, err = s.Runner().ExecContext(s.Ctx(), `
UPDATE wisps
SET status = ?, closed_at = UTC_TIMESTAMP(), close_reason = ?, closed_by_session = ?,
defer_until = DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 DAY)
WHERE id = ?
`, customStatus, "completed", "session-1", "bd-ro-custom-done-wisp")
s.Require().NoError(err)
res, err := NewIssueSQLRepository(s.Runner()).Reopen(s.Ctx(), "bd-ro-custom-done-wisp",
domain.ReopenRowParams{}, "tester", domain.IssueTableOpts{UseWispsTable: true})
s.Require().NoError(err)
s.True(res.Updated)
s.True(res.IsWisp)
var status, closeReason, closedBySession string
var closedAt, deferUntil sql.NullTime
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), `
SELECT status, closed_at, close_reason, closed_by_session, defer_until
FROM wisps WHERE id = ?
`, "bd-ro-custom-done-wisp").Scan(&status, &closedAt, &closeReason, &closedBySession, &deferUntil))
s.Equal(string(types.StatusOpen), status)
s.False(closedAt.Valid, "closed_at must be cleared")
s.Equal("", closeReason)
s.Equal("", closedBySession)
s.False(deferUntil.Valid, "defer_until must be cleared")
}
func (s *testSuite) reopenLeavesIneligibleStatusesUntouched() {
r := NewIssueSQLRepository(s.Runner())
statuses := []struct {
id string
status string
category types.StatusCategory
}{
{id: "bd-ro-custom-active", status: "triaged", category: types.CategoryActive},
{id: "bd-ro-custom-wip", status: "testing", category: types.CategoryWIP},
{id: "bd-ro-custom-frozen", status: "on-ice", category: types.CategoryFrozen},
{id: "bd-ro-custom-unknown", status: "queued", category: types.CategoryUnspecified},
}
var err error
for _, status := range statuses[:3] {
s.seedIssueRow(status.id)
_, err = s.Runner().ExecContext(s.Ctx(),
"INSERT INTO custom_statuses (name, category) VALUES (?, ?)", status.status, string(status.category))
s.Require().NoError(err)
_, err = s.Runner().ExecContext(s.Ctx(),
"UPDATE issues SET status = ?, close_reason = ? WHERE id = ?", status.status, "keep", status.id)
s.Require().NoError(err)
}
s.seedIssueRow(statuses[3].id)
_, err = s.Runner().ExecContext(s.Ctx(),
"INSERT INTO config (`key`, value) VALUES (?, ?)", "status.custom", "queued")
s.Require().NoError(err)
_, err = s.Runner().ExecContext(s.Ctx(),
"UPDATE issues SET status = ?, close_reason = ? WHERE id = ?", "queued", "keep", statuses[3].id)
s.Require().NoError(err)
for _, want := range statuses {
res, err := r.Reopen(s.Ctx(), want.id, domain.ReopenRowParams{Reason: "ignored"}, "tester", domain.IssueTableOpts{})
s.Require().NoError(err)
s.False(res.Updated, "%s should not reopen", want.id)
s.False(res.AlreadyOpen, "%s is not literally open", want.id)
var status, closeReason string
var events int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT status, close_reason FROM issues WHERE id = ?", want.id).Scan(&status, &closeReason))
s.Equal(want.status, status)
s.Equal("keep", closeReason)
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ?", want.id).Scan(&events))
s.Equal(0, events, "%s must not emit reopen or comment events", want.id)
}
}
func (s *testSuite) reopenConfigurationFailureRollsBack() {
const customStatus = "missing-config-status"
s.seedIssueRow("bd-ro-config-failure")
_, err := NewIssueSQLRepository(s.Runner()).Close(s.Ctx(), "bd-ro-config-failure",
domain.CloseRowParams{Reason: "done"}, "tester", domain.IssueTableOpts{})
s.Require().NoError(err)
_, err = s.Runner().ExecContext(s.Ctx(),
"UPDATE issues SET status = ? WHERE id = ?", customStatus, "bd-ro-config-failure")
s.Require().NoError(err)
_, err = s.Runner().ExecContext(s.Ctx(), "DELETE FROM custom_statuses")
s.Require().NoError(err)
_, err = s.Runner().ExecContext(s.Ctx(), "DROP TABLE config")
s.Require().NoError(err)
_, err = NewIssueSQLRepository(s.Runner()).Reopen(s.Ctx(), "bd-ro-config-failure",
domain.ReopenRowParams{Reason: "must roll back"}, "tester", domain.IssueTableOpts{})
s.Require().Error(err)
var status string
var reopened, comments int
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT status FROM issues WHERE id = ?", "bd-ro-config-failure").Scan(&status))
s.Equal(customStatus, status)
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", "bd-ro-config-failure", string(types.EventReopened)).Scan(&reopened))
s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(),
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", "bd-ro-config-failure", string(types.EventCommented)).Scan(&comments))
s.Equal(0, reopened)
s.Equal(0, comments)
}

View file

@ -1,6 +1,7 @@
package db
import (
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
@ -13,6 +14,7 @@ func (s *testSuite) TestIssueUseCase_ReopenIssue() {
s.Run("MissingIDErrors", s.uccReopenMissingID)
s.Run("WispVariantRoutesToWispsTable", s.uccReopenWispRoutes)
s.Run("ReasonRecordedAsComment", s.uccReopenReasonComment)
s.Run("CustomNonDoneReportsNotReopened", s.uccReopenCustomNonDoneReportsNotReopened)
}
func (s *testSuite) uccReopenReturnsIssue() {
@ -60,6 +62,7 @@ func (s *testSuite) uccReopenMissingID() {
_, err := s.issueUseCase().ReopenIssue(s.Ctx(), "bd-ucc-ro-missing",
domain.ReopenIssueParams{}, "tester")
s.Require().Error(err)
s.ErrorIs(err, storage.ErrNotFound)
}
func (s *testSuite) uccReopenWispRoutes() {
@ -99,3 +102,20 @@ func (s *testSuite) uccReopenReasonComment() {
"bd-ucc-ro-cmt", string(types.EventCommented)).Scan(&comment))
s.Equal("qa found a regression", comment)
}
func (s *testSuite) uccReopenCustomNonDoneReportsNotReopened() {
const id = "bd-ucc-ro-custom-active"
s.seedIssueRow(id)
_, err := s.Runner().ExecContext(s.Ctx(),
"INSERT INTO custom_statuses (name, category) VALUES (?, ?)", "triaged", string(types.CategoryActive))
s.Require().NoError(err)
_, err = s.Runner().ExecContext(s.Ctx(), "UPDATE issues SET status = ? WHERE id = ?", "triaged", id)
s.Require().NoError(err)
res, err := s.issueUseCase().ReopenIssue(s.Ctx(), id,
domain.ReopenIssueParams{}, "tester")
s.Require().NoError(err)
s.False(res.Reopened)
s.Require().NotNil(res.Issue)
s.Equal(types.Status("triaged"), res.Issue.Status)
}

View file

@ -0,0 +1,51 @@
package db
import (
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
func (s *testSuite) issueUpdateSameStatusInUnitOfWork() {
ctx := s.Ctx()
issue := newTestIssue("same-status-uow", "before")
s.Require().NoError(s.issueRepo().Insert(ctx, issue, "tester", domain.InsertIssueOpts{}))
var eventsBefore int
s.Require().NoError(s.Runner().QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE issue_id = ?", issue.ID).Scan(&eventsBefore))
tx, err := s.db.BeginTx(ctx, nil)
s.Require().NoError(err)
repo := NewIssueSQLRepository(tx)
before, err := repo.Get(ctx, issue.ID, domain.IssueTableOpts{})
s.Require().NoError(err)
s.Require().NoError(repo.Update(ctx, issue.ID, map[string]any{"status": types.StatusOpen}, "tester", domain.IssueTableOpts{}))
afterNoop, err := repo.Get(ctx, issue.ID, domain.IssueTableOpts{})
s.Require().NoError(err)
s.Equal(before.RowVersion, afterNoop.RowVersion)
var eventsAfterNoop, statusChangedAfterNoop int
s.Require().NoError(tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE issue_id = ?", issue.ID).Scan(&eventsAfterNoop))
s.Require().NoError(tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", issue.ID, string(types.EventStatusChanged)).Scan(&statusChangedAfterNoop))
s.Equal(eventsBefore, eventsAfterNoop)
s.Zero(statusChangedAfterNoop)
s.Require().NoError(repo.Update(ctx, issue.ID, map[string]any{"status": types.StatusOpen, "title": "after"}, "tester", domain.IssueTableOpts{}))
afterScalar, err := repo.Get(ctx, issue.ID, domain.IssueTableOpts{})
s.Require().NoError(err)
s.Equal("after", afterScalar.Title)
s.NotEqual(afterNoop.RowVersion, afterScalar.RowVersion)
var updated, statusChanged int
s.Require().NoError(tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", issue.ID, string(types.EventUpdated)).Scan(&updated))
s.Require().NoError(tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", issue.ID, string(types.EventStatusChanged)).Scan(&statusChanged))
s.Equal(1, updated)
s.Zero(statusChanged)
s.Require().NoError(tx.Commit())
}
func (s *testSuite) issueUpdatePreservesCallerMap() {
ctx := s.Ctx()
issue := newTestIssue("preserve-caller-map", "before")
s.Require().NoError(s.issueRepo().Insert(ctx, issue, "tester", domain.InsertIssueOpts{}))
updates := map[string]any{"status": types.StatusOpen}
s.Require().NoError(s.issueRepo().Update(ctx, issue.ID, updates, "tester", domain.IssueTableOpts{}))
s.Equal(map[string]any{"status": types.StatusOpen}, updates)
}

View file

@ -8,20 +8,17 @@ import (
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dberrors"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// ErrSelfDependency is returned when a dependency edge would point an issue at
// itself. It is the static prefix of the formatted message, wrapped so callers
// can errors.Is it while the human-readable text is preserved byte-for-byte.
var ErrSelfDependency = errors.New("cannot add self-dependency")
// ErrDependencyCycle is returned when adding a dependency edge would introduce a
// scheduling cycle. It is scoped to the dependency-add family — the single and
// bulk add paths (add/addBulk) and the dolt cross-tier check — so callers can
// errors.Is any dependency-add cycle rejection. The whole-graph construction
// paths (ApplyIssueGraph/ApplyWispGraph) are a separate family and deliberately
// do not carry this sentinel yet.
var ErrDependencyCycle = errors.New("adding dependency would create a cycle")
// The dependency-edge refusals are declared and documented by the public
// contract package, github.com/steveyegge/beads/issueops. These are the same
// values, so every domain.ErrX reference and every errors.Is site keeps
// matching the identical error.
var (
ErrSelfDependency = issueops.ErrSelfDependency
ErrDependencyCycle = issueops.ErrDependencyCycle
)
// cycleError carries a fully-formatted cycle-rejection message while unwrapping
// to ErrDependencyCycle. The bulk dependency-add path surfaces this text
@ -52,41 +49,14 @@ func NewCycleError(format string, args ...any) error {
return cycleErrorf(format, args...)
}
// DependencyTypeConflictError is returned when an edge already exists between
// the same pair with a DIFFERENT type. Its message is byte-identical to the
// embedded issueops path (issueops/dependencies.go) so `bd dep add` surfaces
// the same user-facing retype error on the domain/db seam as on the embedded
// store. It is a typed error so the use-case can pass it through
// unwrapped instead of burying it under an "add dep: insert:" prefix.
type DependencyTypeConflictError struct {
IssueID string
DependsOnID string
ExistingType string
RequestedType string
}
// DependencyTypeConflictError reports a duplicate dependency pair with a
// conflicting requested type. See issueops.DependencyTypeConflictError.
type DependencyTypeConflictError = issueops.DependencyTypeConflictError
// DependencyHierarchyConflictError is returned when a blocking dependency
// would gate an issue on one of its own ancestors or descendants. Either shape
// can never clear under the parent-child close/blocking semantics.
type DependencyHierarchyConflictError struct {
IssueID string
BlockerID string
BlockerIsAncestor bool
}
func (e *DependencyHierarchyConflictError) Error() string {
if e.BlockerIsAncestor {
return fmt.Sprintf("%s cannot be blocked by its ancestor %s: %s cannot close until its descendants finish, so the gate would never clear",
e.IssueID, e.BlockerID, e.BlockerID)
}
return fmt.Sprintf("%s cannot be blocked by its descendant %s: blocked status cascades to descendants, so %s would inherit the block and never close",
e.IssueID, e.BlockerID, e.BlockerID)
}
func (e *DependencyTypeConflictError) Error() string {
return fmt.Sprintf("dependency %s -> %s already exists with type %q (requested %q); remove it first with 'bd dep remove' then re-add",
e.IssueID, e.DependsOnID, e.ExistingType, e.RequestedType)
}
// DependencyHierarchyConflictError reports a dependency that would make a
// blocking hierarchy impossible to complete. See
// issueops.DependencyHierarchyConflictError.
type DependencyHierarchyConflictError = issueops.DependencyHierarchyConflictError
type DepDirection int

View file

@ -14,6 +14,7 @@ import (
type InsertIssueOpts struct {
UseWispsTable bool
CreateOnly bool
}
type IssueTableOpts struct {
@ -36,6 +37,7 @@ type ClaimRowResult struct {
type IssueSQLRepository interface {
Insert(ctx context.Context, issue *types.Issue, actor string, opts InsertIssueOpts) error
InsertBatch(ctx context.Context, issues []*types.Issue, actor string, opts InsertIssueOpts) error
MovePersistence(ctx context.Context, id string, mode types.PersistenceMode) (changed bool, err error)
Update(ctx context.Context, id string, updates map[string]any, actor string, opts IssueTableOpts) error
Claim(ctx context.Context, id, actor string, opts IssueTableOpts) (ClaimRowResult, error)
Get(ctx context.Context, id string, opts IssueTableOpts) (*types.Issue, error)
@ -58,6 +60,7 @@ type IssueSQLRepository interface {
AffectedByDeletion(ctx context.Context, issueIDs, wispIDs []string) (affectedIssues, affectedWisps []string, err error)
RecomputeIsBlocked(ctx context.Context, issueIDs, wispIDs []string) error
Close(ctx context.Context, id string, params CloseRowParams, actor string, opts IssueTableOpts) (CloseRowResult, error)
CloseChecked(ctx context.Context, id string, params CloseRowParams, actor string, force bool) (CloseRowResult, error)
Reopen(ctx context.Context, id string, params ReopenRowParams, actor string, opts IssueTableOpts) (ReopenRowResult, error)
GetNewlyUnblockedByClose(ctx context.Context, closedID string) ([]*types.Issue, error)
ClaimReadyIssue(ctx context.Context, filter types.WorkFilter, actor string) (*types.Issue, error)
@ -83,6 +86,7 @@ type CloseRowResult struct {
Updated bool
AlreadyClosed bool
IsWisp bool
OpenChildren int
}
type ReopenRowParams struct {
@ -152,6 +156,8 @@ type CreateIssueParams struct {
WaitsFor *WaitsForSpec
DiscoveredFromParent string
ForcePrefix bool
CreateOnly bool
Comments []*types.Comment
}
type DependencySpec struct {
@ -159,6 +165,7 @@ type DependencySpec struct {
TargetID string
SwapDirection bool
Metadata string
ThreadID string
}
type WaitsForSpec struct {
@ -230,12 +237,16 @@ type ClaimReadyResult struct {
}
type UpdateSpec struct {
Fields map[string]any
Claim bool
AddLabels []string
RemoveLabels []string
SetLabels *[]string
Reparent *string
Fields map[string]any
Claim bool
// ExpectedVersion requires the current row version to match before any
// claim or field writes.
ExpectedVersion *int64
Persistence *types.PersistenceMode
AddLabels []string
RemoveLabels []string
SetLabels *[]string
Reparent *string
// ExpectedAssignee and ExpectedStatus are the bd-wsqvw compare-and-set
// guards (`bd update --if-assignee/--if-status`): when non-nil, the whole
@ -314,8 +325,9 @@ type CloseIssueParams struct {
}
type CloseIssueResult struct {
Issue *types.Issue
Closed bool
Issue *types.Issue
Closed bool
OpenChildren int
}
type ReopenIssueParams struct {
@ -433,20 +445,88 @@ func (u *issueUseCaseImpl) update(ctx context.Context, id string, updates map[st
if len(updates) == 0 {
return nil
}
if rawType, ok := updates["issue_type"]; ok {
if issueType, ok := rawType.(string); ok && issueType != "" {
customTypes, err := u.cfgRepo.GetCustomTypes(ctx)
if err != nil {
return fmt.Errorf("update: read custom types: %w", err)
}
if !types.IssueType(issueType).IsValidWithCustom(customTypes) {
return fmt.Errorf("invalid issue type: %s", issueType)
}
}
if err := validateCanonicalIssueUpdates(updates); err != nil {
return err
}
if err := u.validateIssueTypeUpdate(ctx, updates); err != nil {
return err
}
return u.issueRepo.Update(ctx, id, updates, actor, IssueTableOpts{UseWispsTable: useWisp})
}
// validateIssueTypeUpdate rejects an issue_type the configuration does not
// define. It reads the configured custom types, so unlike
// validateCanonicalIssueUpdates it needs the use case and a context.
func (u *issueUseCaseImpl) validateIssueTypeUpdate(ctx context.Context, updates map[string]any) error {
rawType, ok := updates["issue_type"]
if !ok {
return nil
}
issueType, ok := rawType.(string)
if !ok {
return nil
}
customTypes, err := u.cfgRepo.GetCustomTypes(ctx)
if err != nil {
return fmt.Errorf("update: read custom types: %w", err)
}
if !types.IssueType(issueType).IsValidWithCustom(customTypes) {
return fmt.Errorf("%w: invalid issue type: %s", storage.ErrValidation, issueType)
}
return nil
}
// validateCanonicalIssueUpdates rejects out-of-range values for the canonical
// scalar columns, and rejects values whose Go type the column cannot carry. An
// unsupported type used to fall through unvalidated and reach the SQL layer,
// which coerced it silently -- a title of 7 was stored as "7", and an int64
// priority or estimate skipped its range check entirely.
func validateCanonicalIssueUpdates(updates map[string]any) error {
if value, ok := updates["title"]; ok {
title, isString := value.(string)
if !isString {
return canonicalIssueUpdateTypeError("title", value, "string")
}
if err := types.ValidateIssueTitle(title); err != nil {
return canonicalIssueUpdateValidationError("title", err)
}
}
if value, ok := updates["priority"]; ok {
priority, isInt := value.(int)
if !isInt {
return canonicalIssueUpdateTypeError("priority", value, "int")
}
if err := types.ValidateIssuePriority(priority); err != nil {
return canonicalIssueUpdateValidationError("priority", err)
}
}
if value, ok := updates["estimated_minutes"]; ok {
var estimatedMinutes *int
switch value := value.(type) {
case int:
estimatedMinutes = &value
case *int:
estimatedMinutes = value
case nil:
// Clearing the estimate; a nil estimate validates.
default:
return canonicalIssueUpdateTypeError("estimated_minutes", value, "int or *int")
}
if err := types.ValidateIssueEstimatedMinutes(estimatedMinutes); err != nil {
return canonicalIssueUpdateValidationError("estimated_minutes", err)
}
}
return nil
}
func canonicalIssueUpdateValidationError(field string, err error) error {
return fmt.Errorf("%w: update field %q: %w", storage.ErrValidation, field, err)
}
func canonicalIssueUpdateTypeError(field string, value any, want string) error {
return fmt.Errorf("%w: update field %q: expected %s, got %T", storage.ErrValidation, field, want, value)
}
func (u *issueUseCaseImpl) ClaimIssue(ctx context.Context, id, actor string) (ClaimResult, error) {
return u.claim(ctx, id, actor, false)
}
@ -501,13 +581,7 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda
return nil, fmt.Errorf("ApplyUpdate %s: %w", id, err)
}
// bd-wsqvw field guards: refuse the whole spec atomically on a stale
// assignee/status. The read shares this unit of work's transaction, and
// every field update rewrites row_lock, so a writer that commits during
// the attempt collides at commit time and the caller's whole-attempt
// retry re-checks here on the redo — same CAS invariant as the store-level
// UpdateIssueChecked path.
if spec.ExpectedAssignee != nil || spec.ExpectedStatus != nil {
if spec.ExpectedVersion != nil || spec.ExpectedAssignee != nil || spec.ExpectedStatus != nil {
var current *types.Issue
if useWisp {
current, err = u.GetWisp(ctx, id)
@ -520,6 +594,9 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda
if current == nil {
return nil, fmt.Errorf("%w: issue %s", storage.ErrNotFound, id)
}
if spec.ExpectedVersion != nil && current.RowVersion != *spec.ExpectedVersion {
return nil, fmt.Errorf("%w: expected %d, got %d", storage.ErrVersionMismatch, *spec.ExpectedVersion, current.RowVersion)
}
if spec.ExpectedAssignee != nil && current.Assignee != *spec.ExpectedAssignee {
return nil, fmt.Errorf("%w: %s is held by %q, expected %q",
storage.ErrAssigneeMismatch, id, current.Assignee, *spec.ExpectedAssignee)
@ -530,6 +607,17 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda
}
}
// Validate the requested field values before anything mutates. The claim
// below writes assignee and status, so a spec that pairs Claim with an
// invalid field used to leave the issue claimed by an update that never
// applied.
if err := validateCanonicalIssueUpdates(spec.Fields); err != nil {
return nil, err
}
if err := u.validateIssueTypeUpdate(ctx, spec.Fields); err != nil {
return nil, err
}
if spec.Claim {
if useWisp {
if _, err := u.ClaimWisp(ctx, id, actor); err != nil {
@ -564,27 +652,26 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda
return nil, err
}
}
} else {
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.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 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
}
}
}
@ -601,6 +688,16 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda
}
}
if spec.Persistence != nil {
if _, err := u.issueRepo.MovePersistence(ctx, id, *spec.Persistence); err != nil {
return nil, fmt.Errorf("ApplyUpdate: move persistence for %s: %w", id, err)
}
useWisp, err = u.isWispID(ctx, id)
if err != nil {
return nil, fmt.Errorf("ApplyUpdate: re-locate %s after persistence move: %w", id, err)
}
}
var issue *types.Issue
if useWisp {
issue, err = u.GetWisp(ctx, id)
@ -718,17 +815,50 @@ func (u *issueUseCaseImpl) create(ctx context.Context, params CreateIssueParams,
issue.ID = minted
}
if params.CreateOnly && params.ExplicitID != "" && !params.ForcePrefix {
configuredPrefix, err := u.cfgRepo.GetConfig(ctx, "issue_prefix")
if err != nil {
return CreateIssueResult{}, fmt.Errorf("create: read issue prefix: %w", err)
}
allowedPrefixes, err := u.cfgRepo.GetConfig(ctx, "allowed_prefixes")
if err != nil {
return CreateIssueResult{}, fmt.Errorf("create: read allowed prefixes: %w", err)
}
if err := validateExplicitIDPrefix(issue.ID, strings.TrimSuffix(configuredPrefix, "-"), allowedPrefixes); err != nil {
return CreateIssueResult{}, fmt.Errorf("create: explicit ID prefix: %w", err)
}
}
if params.DiscoveredFromParent != "" {
if parent, err := u.GetIssue(ctx, params.DiscoveredFromParent); err == nil && parent.SourceRepo != "" {
issue.SourceRepo = parent.SourceRepo
}
}
insertOpts := InsertIssueOpts{UseWispsTable: useWisp}
insertOpts := InsertIssueOpts{UseWispsTable: useWisp, CreateOnly: params.CreateOnly}
if err := u.issueRepo.Insert(ctx, issue, actor, insertOpts); err != nil {
return CreateIssueResult{}, fmt.Errorf("create: insert: %w", err)
}
if len(params.Comments) > 0 {
issue.Comments = make([]*types.Comment, 0, len(params.Comments))
for _, comment := range params.Comments {
if comment == nil {
return CreateIssueResult{}, fmt.Errorf("create: comment must not be nil")
}
copy := *comment
copy.IssueID = issue.ID
if copy.Author == "" {
copy.Author = actor
}
inserted, err := u.commentRepo.InsertRecord(ctx, &copy, CommentOpts{UseWispsTable: useWisp})
if err != nil {
return CreateIssueResult{}, fmt.Errorf("create: insert comment: %w", err)
}
issue.Comments = append(issue.Comments, inserted)
}
}
result := CreateIssueResult{Issue: issue}
if params.ParentID != "" {
@ -744,7 +874,11 @@ func (u *issueUseCaseImpl) create(ctx context.Context, params CreateIssueParams,
}
if params.InheritLabelsFromParent && params.ParentID != "" {
parentLabels, err := u.labelRepo.List(ctx, params.ParentID, LabelOpts{UseWispsTable: useWisp})
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.
@ -785,11 +919,16 @@ func (u *issueUseCaseImpl) create(ctx context.Context, params CreateIssueParams,
DependsOnID: spec.TargetID,
Type: spec.Type,
Metadata: spec.Metadata,
ThreadID: spec.ThreadID,
}
if spec.SwapDirection {
dep.IssueID, dep.DependsOnID = dep.DependsOnID, dep.IssueID
}
if err := u.depRepo.Insert(ctx, dep, actor, DepInsertOpts{UseWispsTable: useWisp}); err != nil {
depSourceIsWisp, err := u.isWispID(ctx, dep.IssueID)
if err != nil {
return result, fmt.Errorf("create: determine dep source tier for %s: %w", dep.IssueID, err)
}
if err := u.depRepo.Insert(ctx, dep, actor, DepInsertOpts{UseWispsTable: depSourceIsWisp}); err != nil {
return result, fmt.Errorf("create: add dep %s -> %s: %w", dep.IssueID, dep.DependsOnID, err)
}
result.PostCreateWrites = true
@ -810,6 +949,19 @@ func (u *issueUseCaseImpl) create(ctx context.Context, params CreateIssueParams,
return result, nil
}
func validateExplicitIDPrefix(id, prefix, allowedPrefixes string) error {
if strings.HasPrefix(id, prefix+"-") {
return nil
}
for _, allowed := range strings.Split(allowedPrefixes, ",") {
allowed = strings.TrimSpace(allowed)
if allowed != "" && strings.HasPrefix(id, allowed+"-") {
return nil
}
}
return fmt.Errorf("%w: issue ID %s does not match configured prefix %s", storage.ErrPrefixMismatch, id, prefix)
}
func (u *issueUseCaseImpl) CreateIssues(ctx context.Context, params []CreateIssueParams, actor string) (CreateIssuesResult, error) {
return u.createMany(ctx, params, actor, false)
}
@ -1388,82 +1540,32 @@ func (u *issueUseCaseImpl) CloseWisp(ctx context.Context, id string, params Clos
return u.close(ctx, id, params, actor, true)
}
// CloseIssueChecked closes an issue, refusing with storage.ErrCloseBlocked when
// the issue has a live, open direct blocker unless force is set. The blocker
// check (IsBlocked) and the close (CloseIssue) run through the same unit-of-work
// transaction, so this is a single enforcement point rather than a re-check of
// separate reads. When force is set or the guard passes it delegates to the
// unchecked CloseIssue, preserving its CloseIssueResult semantics exactly.
// CloseIssueChecked closes an issue through the shared guarded close path.
func (u *issueUseCaseImpl) CloseIssueChecked(ctx context.Context, id string, params CloseIssueParams, actor string, force bool) (CloseIssueResult, error) {
return u.closeChecked(ctx, id, params, actor, force, false)
}
// CloseWispChecked is the wisp twin of CloseIssueChecked: it applies the same
// live-direct-blocker guard (via IsWispBlocked) before delegating to the
// unchecked CloseWisp.
// CloseWispChecked is the wisp twin of CloseIssueChecked.
func (u *issueUseCaseImpl) CloseWispChecked(ctx context.Context, id string, params CloseIssueParams, actor string, force bool) (CloseIssueResult, error) {
return u.closeChecked(ctx, id, params, actor, force, true)
}
// isClosed reports whether the issue (or wisp) identified by id is already in
// the closed status, read in the same unit of work as the close so the check
// and the close cannot straddle a concurrent state change. A missing row (or,
// for a wisp source, a missing optional wisps table) reports not-closed so
// closeChecked falls through to u.close, whose repo Close surfaces the not-found
// result — mirroring issueops.isClosedInTx on the embedded checked-close path.
func (u *issueUseCaseImpl) isClosed(ctx context.Context, id string, useWisp bool) (bool, error) {
issue, err := u.issueRepo.Get(ctx, id, IssueTableOpts{UseWispsTable: useWisp})
if err != nil {
if dberrors.IsNoRows(err) || dberrors.IsTableNotExist(err) {
return false, nil
}
return false, err
}
if issue == nil {
return false, nil
}
return issue.Status == types.StatusClosed, nil
}
func (u *issueUseCaseImpl) closeChecked(ctx context.Context, id string, params CloseIssueParams, actor string, force, useWisp bool) (CloseIssueResult, error) {
if !force {
// The blocked guard only has meaning for an open→closed transition. An
// already-closed row is an idempotent no-op (Closed=false per the
// Storage.CloseIssueChecked contract), so detect that first: a closed row
// can still carry a stale is_blocked=1 (e.g. after a cross-clone Dolt
// merge, a state GetStatistics filters as `is_blocked = 1 AND status <>
// 'closed'`) whose live direct blocker would otherwise refuse the
// idempotent re-close with ErrCloseBlocked. This mirrors
// issueops.CloseIssueCheckedInTx, which runs isClosedInTx before the
// is_blocked guard; u.close below is the sole detector of the
// already-closed no-op (matching the Force path, which reaches
// Closed=false by skipping the guard).
closed, err := u.isClosed(ctx, id, useWisp)
if err != nil {
return CloseIssueResult{}, err
}
if !closed {
var (
blocked bool
blockers []string
)
if useWisp {
blocked, blockers, err = u.depUC.IsWispBlocked(ctx, id)
} else {
blocked, blockers, err = u.depUC.IsBlocked(ctx, id)
}
if err != nil {
return CloseIssueResult{}, err
}
// Refuse only on a live, open direct blocker. A bare is_blocked=1 with no
// live direct blocker (a purely transitive block) closes — matching the
// historical `bd close` predicate and the embedded checked-close path.
if blocked && len(blockers) > 0 {
return CloseIssueResult{}, fmt.Errorf("%w: %s is blocked by %v", storage.ErrCloseBlocked, id, blockers)
}
}
if id == "" {
return CloseIssueResult{}, fmt.Errorf("close: id must not be empty")
}
return u.close(ctx, id, params, actor, useWisp)
if actor == "" {
return CloseIssueResult{}, fmt.Errorf("close: actor must not be empty")
}
row, err := u.issueRepo.CloseChecked(ctx, id, CloseRowParams{Reason: params.Reason, Session: params.Session}, actor, force)
if err != nil {
return CloseIssueResult{}, fmt.Errorf("close %s: %w", id, err)
}
issue, err := u.issueRepo.Get(ctx, id, IssueTableOpts{UseWispsTable: row.IsWisp || useWisp})
if err != nil {
return CloseIssueResult{}, fmt.Errorf("close %s: reload: %w", id, err)
}
return CloseIssueResult{Issue: issue, Closed: !row.AlreadyClosed, OpenChildren: row.OpenChildren}, nil
}
func (u *issueUseCaseImpl) close(ctx context.Context, id string, params CloseIssueParams, actor string, useWisp bool) (CloseIssueResult, error) {
@ -1512,7 +1614,7 @@ func (u *issueUseCaseImpl) reopen(ctx context.Context, id string, params ReopenI
}
return ReopenIssueResult{
Issue: issue,
Reopened: !row.AlreadyOpen,
Reopened: row.Updated,
}, nil
}

View file

@ -77,6 +77,28 @@ func TestEmbeddedCloseIssueChecked(t *testing.T) {
if iss.Status != types.StatusClosed {
t.Fatalf("cic-target status = %q after force, want closed", iss.Status)
}
parent := &types.Issue{ID: "cicoc-parent", Title: "parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
child := &types.Issue{ID: "cicoc-child", Title: "child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
for _, issue := range []*types.Issue{parent, child} {
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue(%s): %v", issue.ID, err)
}
}
if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "tester"); err != nil {
t.Fatalf("AddDependency: %v", err)
}
res, err = te.store.CloseIssueChecked(ctx, parent.ID, "tester", storage.CloseIssueOptions{Reason: "done"})
if !errors.Is(err, storage.ErrCloseOpenChildren) {
t.Fatalf("close error = %v, want errors.Is(_, ErrCloseOpenChildren)", err)
}
if iss, getErr := te.store.GetIssue(ctx, parent.ID); getErr != nil || iss.Status != types.StatusOpen {
t.Fatalf("GetIssue after refusal = (%+v, %v), want open parent", iss, getErr)
}
res, err = te.store.CloseIssueChecked(ctx, parent.ID, "tester", storage.CloseIssueOptions{Reason: "override", Force: true})
if err != nil || res.Unchanged || res.OpenChildren != 1 {
t.Fatalf("force result = %+v, err = %v; want changed close with 1 child", res, err)
}
}
// TestEmbeddedCloseIssueCheckedTransitiveBlockedCloses proves the guard refuses

View file

@ -0,0 +1,31 @@
//go:build cgo
package embeddeddolt
import (
"errors"
"testing"
"github.com/steveyegge/beads/internal/storage"
)
func TestEmbeddedDoltStoreIssueLifecycleBuildsOperations(t *testing.T) {
lifecycle, err := (&EmbeddedDoltStore{}).IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle() error = %v", err)
}
if lifecycle == nil {
t.Fatal("IssueLifecycle() returned nil operations")
}
}
func TestEmbeddedDoltStoreIssueLifecycleRejectsNilStore(t *testing.T) {
lifecycle, err := (*EmbeddedDoltStore)(nil).IssueLifecycle()
if lifecycle != nil {
t.Fatalf("IssueLifecycle() lifecycle = %T, want nil", lifecycle)
}
var unsupported *storage.ErrUnsupported
if !errors.As(err, &unsupported) {
t.Fatalf("IssueLifecycle() error = %v, want *storage.ErrUnsupported", err)
}
}

View file

@ -0,0 +1,87 @@
//go:build cgo
package embeddeddolt
import (
"context"
"database/sql"
"github.com/steveyegge/beads/internal/storage"
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/issueops"
)
// IssueLifecycle returns the guarded issue-lifecycle surface for this store.
func (s *EmbeddedDoltStore) IssueLifecycle() (issueops.Lifecycle, error) {
return NewIssueOperations(s)
}
// NewIssueOperations returns guarded issue operations backed by store.
func NewIssueOperations(store *EmbeddedDoltStore) (issueops.Lifecycle, error) {
if store == nil {
return nil, &storage.ErrUnsupported{Op: "NewIssueOperations", Backend: "nil"}
}
return &issueOperations{store: store}, nil
}
type issueOperations struct{ store *EmbeddedDoltStore }
// updateCommitMessage names the updated issue in the Dolt commit message.
func updateCommitMessage(issueID string) string {
if issueID == "" {
return "bd: update issue"
}
return "bd: update " + issueID
}
func (o *issueOperations) Create(ctx context.Context, request issueops.CreateRequest) (issueops.CreateResult, error) {
snapshot := storageissueops.CloneCreateRequest(request)
var result issueops.CreateResult
err := o.store.runIssueOperationTx(ctx, "bd: create issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) {
var err error
var tables storageissueops.ChangedTables
result, tables, err = storageissueops.ExecuteCreate(ctx, tx, snapshot)
return tables, err
})
return result, err
}
func (o *issueOperations) Update(ctx context.Context, request issueops.UpdateRequest) (issueops.UpdateResult, error) {
snapshot := storageissueops.CloneUpdateRequest(request)
var result issueops.UpdateResult
// Same ID-bearing commit message as the server-backed store, so `bd dolt
// log` reads the same on both backends.
err := o.store.runIssueOperationTx(ctx, updateCommitMessage(snapshot.IssueID), func(tx *sql.Tx) (storageissueops.ChangedTables, error) {
var err error
var tables storageissueops.ChangedTables
result, tables, err = storageissueops.ExecuteUpdate(ctx, tx, snapshot)
return tables, err
})
return result, err
}
func (o *issueOperations) Close(ctx context.Context, request issueops.CloseRequest) (issueops.CloseResult, error) {
snapshot := storageissueops.CloneCloseRequest(request)
var result issueops.CloseResult
err := o.store.runIssueOperationTx(ctx, "bd: close issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) {
var err error
var tables storageissueops.ChangedTables
result, tables, err = storageissueops.ExecuteClose(ctx, tx, snapshot)
return tables, err
})
return result, err
}
func (o *issueOperations) Reopen(ctx context.Context, request issueops.ReopenRequest) (issueops.ReopenResult, error) {
snapshot := storageissueops.CloneReopenRequest(request)
var result issueops.ReopenResult
err := o.store.runIssueOperationTx(ctx, "bd: reopen issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) {
var err error
var tables storageissueops.ChangedTables
result, tables, err = storageissueops.ExecuteReopen(ctx, tx, snapshot)
return tables, err
})
return result, err
}
var _ issueops.Lifecycle = (*issueOperations)(nil)

View file

@ -0,0 +1,589 @@
//go:build cgo
package embeddeddolt_test
import (
"encoding/json"
"errors"
"reflect"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// TestEmbeddedIssueOperationsGuardedVerbs gives the embedded adapter the same
// public guarded-operation coverage as the direct implementation.
func TestEmbeddedIssueOperationsGuardedVerbs(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops")
ctx := t.Context()
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatalf("NewIssueOperations: %v", err)
}
create := func(t *testing.T, id string) *types.Issue {
t.Helper()
issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed %s: %v", id, err)
}
return issue
}
t.Run("create rejects occupied ID", func(t *testing.T) {
create(t, "ops-duplicate")
_, err := operations.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: &types.Issue{ID: "ops-duplicate", Title: "replacement", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}})
if !errors.Is(err, publicops.ErrAlreadyExists) {
t.Fatalf("Create error = %v, want ErrAlreadyExists", err)
}
got, getErr := te.store.GetIssue(ctx, "ops-duplicate")
if getErr != nil || got.Title != "ops-duplicate" {
t.Fatalf("stored duplicate = %#v, %v; want original title", got, getErr)
}
})
t.Run("create validates prefix and aggregates relations", func(t *testing.T) {
parent := create(t, "ops-parent")
spawner := create(t, "ops-spawner")
if err := te.store.AddLabel(ctx, parent.ID, "parent-label", "seed"); err != nil {
t.Fatal(err)
}
target := create(t, "ops-target")
request := publicops.CreateRequest{Actor: "writer", Issue: &types.Issue{ID: "foreign-aggregate", Title: "aggregate", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, ParentID: parent.ID, InheritLabelsFromParent: true, Dependencies: []publicops.CreateDependency{{TargetID: target.ID, Type: types.DepRelated, ThreadID: "thread"}, {TargetID: target.ID, Type: types.DepRelatesTo, Reverse: true, ThreadID: "reverse-thread"}}, WaitsFor: &publicops.WaitsFor{SpawnerID: spawner.ID}}
_, err := operations.Create(ctx, request)
if !errors.Is(err, publicops.ErrPrefixMismatch) {
t.Fatalf("unforced foreign prefix error = %v, want ErrPrefixMismatch", err)
}
request.ForceIDPrefix = true
result, err := operations.Create(ctx, request)
if err != nil {
t.Fatalf("forced Create: %v", err)
}
if len(result.Issue.Labels) != 1 || result.Issue.Labels[0] != "parent-label" || len(result.Issue.Dependencies) != 3 {
t.Fatalf("Create result aggregate = %#v", result.Issue)
}
inbound, err := te.store.GetDependentRecords(ctx, result.Issue.ID, "", 10, "")
if err != nil || len(inbound) != 1 || inbound[0].IssueID != target.ID || inbound[0].ThreadID != "reverse-thread" {
t.Fatalf("reverse dependency = %#v, %v", inbound, err)
}
})
t.Run("update enforces version and claim", func(t *testing.T) {
issue := create(t, "ops-update")
stale := issue.RowVersion + 1
_, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedVersion: &stale, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must not persist"}}})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("stale Update error = %v, want ErrVersionMismatch", err)
}
result, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Claim: true})
if err != nil || !result.Changed || result.Issue.Assignee != "writer" || result.Issue.Status != publicops.StatusInProgress {
t.Fatalf("claim result = %#v, %v", result, err)
}
})
t.Run("close and reopen enforce versions and children", func(t *testing.T) {
parent := create(t, "ops-close-parent")
child := create(t, "ops-close-child")
if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil {
t.Fatal(err)
}
stale := parent.RowVersion + 1
_, err := operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, ExpectedVersion: &stale})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("stale Close error = %v, want ErrVersionMismatch", err)
}
_, err = operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID})
if !errors.Is(err, publicops.ErrCloseOpenChildren) {
t.Fatalf("unforced close error = %v, want ErrCloseOpenChildren", err)
}
closed, err := operations.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, Force: true})
if err != nil || !closed.Changed || closed.OpenChildren != 1 {
t.Fatalf("forced close = %#v, %v", closed, err)
}
stale = closed.Issue.RowVersion + 1
_, err = operations.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: parent.ID, ExpectedVersion: &stale})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("stale Reopen error = %v, want ErrVersionMismatch", err)
}
})
}
func TestEmbeddedIssueOperationsUpdateMetadataPatchOrderingAndReplacementGuard(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_metadata_order")
ctx := t.Context()
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatalf("NewIssueOperations: %v", err)
}
issue := &types.Issue{ID: "ops-metadata-order", Title: "metadata", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Metadata: json.RawMessage(`{"keep":"old","remove":"old"}`)}
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{
Merge: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"keep":"merged","merge":true}`)},
Set: map[string]json.RawMessage{"after": json.RawMessage(`"set"`), "keep": json.RawMessage(`"set"`)},
Unset: []string{"keep", "remove"},
}}})
if err != nil || !updated.Changed || !sameEmbeddedMetadataJSON(updated.Issue.Metadata, json.RawMessage(`{"after":"set","merge":true}`)) {
t.Fatalf("ordered metadata update = %#v, %v", updated, err)
}
replaced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{Replace: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"replacement":true}`)}}}})
if err != nil || !replaced.Changed || !sameEmbeddedMetadataJSON(replaced.Issue.Metadata, json.RawMessage(`{"replacement":true}`)) {
t.Fatalf("metadata replacement = %#v, %v", replaced, err)
}
_, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{
Replace: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"replacement":true}`)},
Set: map[string]json.RawMessage{"must_not_persist": json.RawMessage(`true`)},
}}})
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("combined replacement error = %v, want ErrValidation", err)
}
stored, err := te.store.GetIssue(ctx, issue.ID)
if err != nil || !sameEmbeddedMetadataJSON(stored.Metadata, json.RawMessage(`{"replacement":true}`)) {
t.Fatalf("replacement guard persisted metadata = %#v, %v", stored, err)
}
}
func TestEmbeddedIssueOperationsUpdateLabelPatchOrderingAndNoop(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_label_order")
ctx := t.Context()
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatalf("NewIssueOperations: %v", err)
}
issue := &types.Issue{ID: "ops-label-order", Title: "labels", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"old", "shared"}}
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
patch := publicops.LabelPatch{Replace: publicops.Field[[]string]{Set: true, Value: []string{"replace", "shared"}}, Add: []string{"add", "shared"}, Remove: []string{"old", "shared"}}
updated, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Labels: patch}})
if err != nil || !updated.Changed || strings.Join(updated.Issue.Labels, ",") != "add,replace" {
t.Fatalf("ordered labels update = %#v, %v", updated, err)
}
noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Labels: publicops.LabelPatch{Replace: publicops.Field[[]string]{Set: true, Value: []string{"replace", "add"}}, Add: []string{"add"}, Remove: []string{"missing"}}}})
if err != nil || noOp.Changed || strings.Join(noOp.Issue.Labels, ",") != "add,replace" {
t.Fatalf("same labels update = %#v, %v", noOp, err)
}
}
func TestEmbeddedIssueOperationsUpdateParentReplacementClearAndNoop(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_parent_order")
ctx := t.Context()
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatalf("NewIssueOperations: %v", err)
}
create := func(id string) *types.Issue {
issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
return issue
}
parentA, parentB, parentC := create("ops-parent-a"), create("ops-parent-b"), create("ops-parent-c")
child := create("ops-parent-child")
for _, parent := range []*types.Issue{parentA, parentB} {
if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil {
t.Fatal(err)
}
}
replaced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: parentC.ID}}})
if err != nil || !replaced.Changed || embeddedIssueParentIDs(replaced.Issue) != parentC.ID {
t.Fatalf("parent replacement = %#v, %v", replaced, err)
}
noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: parentC.ID}}})
if err != nil || noOp.Changed || embeddedIssueParentIDs(noOp.Issue) != parentC.ID {
t.Fatalf("same parent replacement = %#v, %v", noOp, err)
}
cleared, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true}}})
if err != nil || !cleared.Changed || embeddedIssueParentIDs(cleared.Issue) != "" {
t.Fatalf("parent clear = %#v, %v", cleared, err)
}
noOp, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: child.ID, Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true}}})
if err != nil || noOp.Changed || embeddedIssueParentIDs(noOp.Issue) != "" {
t.Fatalf("same parent clear = %#v, %v", noOp, err)
}
}
func TestEmbeddedIssueOperationsUpdateClaimCASAndTransferMatrix(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_claim_matrix")
ctx := t.Context()
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatal(err)
}
create := func(id, assignee string, status types.Status, wisp bool) *types.Issue {
issue := &types.Issue{ID: id, Title: id, Assignee: assignee, Status: status, Priority: 2, IssueType: types.TypeTask, Ephemeral: wisp}
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
return issue
}
t.Run("version and field CAS refuse before mutation", func(t *testing.T) {
issue := create("ops-cas", "owner", types.StatusOpen, false)
stale := issue.RowVersion + 1
_, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedVersion: &stale, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("version error = %v", err)
}
expectedAssignee, expectedStatus := "other", publicops.StatusOpen
_, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expectedAssignee, ExpectedStatus: &expectedStatus, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}})
if !errors.Is(err, publicops.ErrAssigneeMismatch) {
t.Fatalf("assignee error = %v", err)
}
expectedAssignee = "owner"
wrongStatus := publicops.StatusInProgress
_, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expectedAssignee, ExpectedStatus: &wrongStatus, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "no"}}})
if !errors.Is(err, publicops.ErrStatusMismatch) {
t.Fatalf("status error = %v", err)
}
expectedStatus = publicops.StatusOpen
matched, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, ExpectedAssignee: &expectedAssignee, ExpectedStatus: &expectedStatus, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "matched"}}})
if err != nil || !matched.Changed || matched.Issue.Title != "matched" {
t.Fatalf("matching CAS = %#v, %v", matched, err)
}
got, getErr := te.store.GetIssue(ctx, issue.ID)
if getErr != nil || got.Title != "matched" {
t.Fatalf("CAS mutation = %#v, %v", got, getErr)
}
})
t.Run("claim eligibility and overrides", func(t *testing.T) {
claimable := create("ops-claim", "", types.StatusOpen, false)
claimed, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: claimable.ID, Claim: true})
if err != nil || !claimed.Changed || claimed.Issue.Assignee != "worker" || claimed.Issue.Status != publicops.StatusInProgress {
t.Fatalf("claim = %#v, %v", claimed, err)
}
noOp, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: claimable.ID, Claim: true})
if err != nil || noOp.Changed {
t.Fatalf("same actor claim = %#v, %v", noOp, err)
}
foreign := create("ops-foreign", "owner", types.StatusOpen, false)
_, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: foreign.ID, Claim: true})
if !errors.Is(err, publicops.ErrAlreadyClaimed) {
t.Fatalf("foreign claim = %v", err)
}
if err := te.store.SetConfig(ctx, "claim.pools", "crew"); err != nil {
t.Fatal(err)
}
pool := create("ops-pool", "crew", types.StatusOpen, false)
pooled, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: pool.ID, Claim: true})
if err != nil || !pooled.Changed || pooled.Issue.Assignee != "worker" {
t.Fatalf("pool claim = %#v, %v", pooled, err)
}
poolTransfer := create("ops-pool-transfer", "crew", types.StatusInProgress, false)
transferred, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: poolTransfer.ID, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}})
if err != nil || !transferred.Changed || transferred.Issue.Assignee != "next" {
t.Fatalf("pool transfer = %#v, %v", transferred, err)
}
override := create("ops-override", "", types.StatusOpen, false)
result, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: override.ID, Claim: true, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "reviewer"}, Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusOpen}}})
if err != nil || !result.Changed || result.Issue.Assignee != "reviewer" || result.Issue.Status != publicops.StatusOpen {
t.Fatalf("claim override = %#v, %v", result, err)
}
})
t.Run("transfer fence, force, expected assignee, and wisp routing", func(t *testing.T) {
foreign := create("ops-transfer", "owner", types.StatusInProgress, false)
_, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: foreign.ID, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}})
if !errors.Is(err, publicops.ErrAlreadyClaimed) {
t.Fatalf("unforced transfer = %v", err)
}
forced, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: foreign.ID, ForceAssigneeTransfer: true, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}})
if err != nil || !forced.Changed || forced.Issue.Assignee != "next" {
t.Fatalf("forced transfer = %#v, %v", forced, err)
}
expected := "owner"
authorized := create("ops-authorized", "owner", types.StatusInProgress, false)
result, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: authorized.ID, ExpectedAssignee: &expected, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}})
if err != nil || !result.Changed || result.Issue.Assignee != "next" {
t.Fatalf("authorized transfer = %#v, %v", result, err)
}
wisp := create("ops-wisp", "", types.StatusOpen, true)
wispResult, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "worker", IssueID: wisp.ID, Claim: true})
if err != nil || !wispResult.Changed || wispResult.Issue.Assignee != "worker" {
t.Fatalf("wisp claim = %#v, %v", wispResult, err)
}
})
t.Run("invalid claim combinations fail without mutation", func(t *testing.T) {
issue := create("ops-invalid", "", types.StatusOpen, false)
expected := ""
status := publicops.StatusOpen
for _, request := range []publicops.UpdateRequest{
{Actor: "worker", IssueID: issue.ID, Claim: true, ExpectedAssignee: &expected},
{Actor: "worker", IssueID: issue.ID, Claim: true, ExpectedStatus: &status},
{Actor: "worker", IssueID: issue.ID, Claim: true, ForceAssigneeTransfer: true},
{Actor: "worker", IssueID: issue.ID, ForceAssigneeTransfer: true},
{Actor: "worker", IssueID: issue.ID, ForceAssigneeTransfer: true, ExpectedAssignee: &expected, Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "next"}}},
} {
_, err := operations.Update(ctx, request)
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("invalid request error = %v", err)
}
}
got, err := te.store.GetIssue(ctx, issue.ID)
if err != nil || got.Assignee != "" || got.Status != types.StatusOpen {
t.Fatalf("invalid request mutated = %#v, %v", got, err)
}
})
}
func TestEmbeddedIssueOperationsLifecycleContractMatrix(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_lifecycle")
ctx := t.Context()
ops, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatal(err)
}
makeIssue := func(id string, status types.Status, wisp bool) *types.Issue {
issue := &types.Issue{ID: id, Title: id, Status: status, Priority: 2, IssueType: types.TypeTask, Ephemeral: wisp}
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
return issue
}
t.Run("close session and reclose", func(t *testing.T) {
issue := makeIssue("ops-life", types.StatusOpen, false)
result, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: issue.ID, Reason: "because", Session: "session-1"})
if err != nil || !result.Changed || result.Issue.ClosedBySession != "session-1" || result.Issue.CloseReason != "because" {
t.Fatalf("first close session=%q reason=%q changed=%t error=%v", result.Issue.ClosedBySession, result.Issue.CloseReason, result.Changed, err)
}
reclose, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: issue.ID})
if err != nil || reclose.Changed {
t.Fatalf("idempotent reclose = %#v, %v; want unchanged", reclose, err)
}
})
t.Run("force reopen wisp", func(t *testing.T) {
parent, child := makeIssue("ops-parent", types.StatusOpen, false), makeIssue("ops-child", types.StatusOpen, false)
if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild}, "seed"); err != nil {
t.Fatal(err)
}
_, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID})
if !errors.Is(err, publicops.ErrCloseOpenChildren) {
t.Fatalf("children=%v", err)
}
forced, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent.ID, Force: true})
if err != nil || forced.OpenChildren != 1 {
t.Fatalf("force=%#v,%v", forced, err)
}
opened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: parent.ID})
if err != nil || !opened.Changed {
t.Fatalf("reopen=%#v,%v", opened, err)
}
wisp := makeIssue("ops-wisp", types.StatusOpen, true)
if _, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: wisp.ID}); err != nil {
t.Fatal(err)
}
})
}
func TestEmbeddedIssueOperationsLifecycleRemainingCausalCases(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_life_remaining")
ctx := t.Context()
ops, _ := embeddeddolt.NewIssueOperations(te.store)
makeIssue := func(id string, status types.Status) *types.Issue {
issue := &types.Issue{ID: id, Title: id, Status: status, Priority: 2, IssueType: types.TypeTask}
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
return issue
}
t.Run("blocker refusal and force leave no partial mutation", func(t *testing.T) {
blocker, target := makeIssue("ops-blocker", types.StatusOpen), makeIssue("ops-blocked", types.StatusOpen)
if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: target.ID, DependsOnID: blocker.ID, Type: types.DepBlocks}, "seed"); err != nil {
t.Fatal(err)
}
_, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: target.ID})
if !errors.Is(err, publicops.ErrCloseBlocked) {
t.Fatalf("blocker=%v", err)
}
got, _ := te.store.GetIssue(ctx, target.ID)
if got.Status != types.StatusOpen {
t.Fatalf("refusal mutated=%#v", got)
}
forced, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: target.ID, Force: true})
if err != nil || !forced.Changed {
t.Fatalf("force=%#v,%v", forced, err)
}
})
t.Run("reopen version before non-done noop and custom done", func(t *testing.T) {
open := makeIssue("ops-open", types.StatusOpen)
stale := open.RowVersion + 1
_, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: open.ID, ExpectedVersion: &stale})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("reopen version=%v", err)
}
if err := te.store.SetConfig(ctx, "status.custom", "archived:done"); err != nil {
t.Fatal(err)
}
custom := makeIssue("ops-custom", types.Status("archived"))
reopened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: custom.ID})
if err != nil || !reopened.Changed || reopened.Issue.Status != types.StatusOpen {
t.Fatalf("custom=%#v,%v", reopened, err)
}
})
}
func embeddedIssueParentIDs(issue *types.Issue) string {
parents := make([]string, 0)
for _, dependency := range issue.Dependencies {
if dependency.Type == types.DepParentChild {
parents = append(parents, dependency.DependsOnID)
}
}
return strings.Join(parents, ",")
}
func sameEmbeddedMetadataJSON(left, right json.RawMessage) bool {
var leftValue, rightValue any
return json.Unmarshal(left, &leftValue) == nil && json.Unmarshal(right, &rightValue) == nil && reflect.DeepEqual(leftValue, rightValue)
}
func TestEmbeddedIssueOperationsUpdateAllScalarAndPointerFieldsReportChanged(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_scalar_changed")
ctx := t.Context()
ops, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatal(err)
}
when := time.Date(2026, 7, 30, 12, 0, 0, 0, time.UTC)
minutes, external := 15, "external"
base := func(id string) *types.Issue {
return &types.Issue{ID: id, Title: "title", Description: "description", Design: "design", AcceptanceCriteria: "criteria", Notes: "notes", SpecID: "spec", AwaitID: "await", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Assignee: "worker", Owner: "owner", ClosedBySession: "session", EstimatedMinutes: &minutes, ExternalRef: &external, DueAt: &when, DeferUntil: &when}
}
cases := []struct {
name string
patch publicops.IssuePatch
check func(*types.Issue) bool
}{
{"title", publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "changed"}}, func(i *types.Issue) bool { return i.Title == "changed" }},
{"description clear", publicops.IssuePatch{Description: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Description == "" }},
{"design clear", publicops.IssuePatch{Design: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Design == "" }},
{"acceptance criteria clear", publicops.IssuePatch{AcceptanceCriteria: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.AcceptanceCriteria == "" }},
{"notes clear", publicops.IssuePatch{Notes: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Notes == "" }},
{"append notes", publicops.IssuePatch{AppendNotes: publicops.Field[string]{Set: true, Value: "later"}}, func(i *types.Issue) bool { return i.Notes == "notes\nlater" }},
{"spec ID clear", publicops.IssuePatch{SpecID: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.SpecID == "" }},
{"await ID clear", publicops.IssuePatch{AwaitID: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.AwaitID == "" }},
{"status", publicops.IssuePatch{Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusInProgress}}, func(i *types.Issue) bool { return i.Status == publicops.StatusInProgress }},
{"priority zero", publicops.IssuePatch{Priority: publicops.Field[int]{Set: true}}, func(i *types.Issue) bool { return i.Priority == 0 }},
{"issue type", publicops.IssuePatch{IssueType: publicops.Field[publicops.IssueType]{Set: true, Value: types.TypeBug}}, func(i *types.Issue) bool { return i.IssueType == types.TypeBug }},
{"assignee clear", publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Assignee == "" }},
{"owner clear", publicops.IssuePatch{Owner: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.Owner == "" }},
{"closed by session clear", publicops.IssuePatch{ClosedBySession: publicops.Field[string]{Set: true}}, func(i *types.Issue) bool { return i.ClosedBySession == "" }},
{"estimated minutes clear", publicops.IssuePatch{EstimatedMinutes: publicops.Field[*int]{Set: true}}, func(i *types.Issue) bool { return i.EstimatedMinutes == nil }},
{"external ref clear", publicops.IssuePatch{ExternalRef: publicops.Field[*string]{Set: true}}, func(i *types.Issue) bool { return i.ExternalRef == nil }},
{"due at clear", publicops.IssuePatch{DueAt: publicops.Field[*time.Time]{Set: true}}, func(i *types.Issue) bool { return i.DueAt == nil }},
{"defer until clear", publicops.IssuePatch{DeferUntil: publicops.Field[*time.Time]{Set: true}}, func(i *types.Issue) bool { return i.DeferUntil == nil }},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
issue := base("ops-scalars-" + strings.ReplaceAll(tc.name, " ", "-"))
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
result, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: tc.patch})
if err != nil || !result.Changed || !tc.check(result.Issue) {
t.Fatalf("Update(%s) = %#v, %v", tc.name, result, err)
}
stored, err := te.store.GetIssue(ctx, issue.ID)
if err != nil || !tc.check(stored) {
t.Fatalf("stored %s = %#v, %v", tc.name, stored, err)
}
if tc.name != "append notes" {
noOp, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: tc.patch})
if err != nil || noOp.Changed {
t.Fatalf("same-value %s = %#v, %v", tc.name, noOp, err)
}
after, err := te.store.GetIssue(ctx, issue.ID)
if err != nil || after.RowVersion != stored.RowVersion {
t.Fatalf("same-value %s wrote row version %d -> %d, %v", tc.name, stored.RowVersion, after.RowVersion, err)
}
}
})
}
issue := base("ops-notes-conflict")
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
_, err = ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must rollback"}, Notes: publicops.Field[string]{Set: true, Value: "replace"}, AppendNotes: publicops.Field[string]{Set: true, Value: "append"}}})
if err == nil {
t.Fatal("Notes plus AppendNotes succeeded")
}
stored, err := te.store.GetIssue(ctx, issue.ID)
if err != nil || stored.Title != "title" || stored.Notes != "notes" {
t.Fatalf("notes conflict persisted %#v, %v", stored, err)
}
}
func TestEmbeddedIssueOperationsPersistenceRollbackWispAndDetachedResults(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_persistence_aggregate")
ctx := t.Context()
ops, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatal(err)
}
for _, transition := range []struct{ from, to publicops.PersistenceMode }{{publicops.PersistenceModePersistent, publicops.PersistenceModeEphemeral}, {publicops.PersistenceModeEphemeral, publicops.PersistenceModeNoHistory}, {publicops.PersistenceModeNoHistory, publicops.PersistenceModePersistent}} {
id := "ops-persistence-" + string(transition.from) + "-" + string(transition.to)
if err := te.store.CreateIssue(ctx, &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: transition.from == publicops.PersistenceModeEphemeral, NoHistory: transition.from == publicops.PersistenceModeNoHistory}, "seed"); err != nil {
t.Fatal(err)
}
result, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: transition.to}}})
if err != nil || !result.Changed || result.Issue.Ephemeral != (transition.to == publicops.PersistenceModeEphemeral) || result.Issue.NoHistory != (transition.to == publicops.PersistenceModeNoHistory) {
t.Fatalf("transition %s->%s = %#v, %v", transition.from, transition.to, result, err)
}
noOp, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: transition.to}}})
if err != nil || noOp.Changed {
t.Fatalf("same persistence %s = %#v, %v", transition.to, noOp, err)
}
}
unversioned := &types.Issue{ID: "ops-persistence-rollback", Title: "original", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, StorageClass: types.StorageClassUnversioned, Labels: []string{"keep"}, Metadata: json.RawMessage(`{"keep":true}`)}
if err := te.store.CreateIssue(ctx, unversioned, "seed"); err != nil {
t.Fatal(err)
}
_, err = ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: unversioned.ID, Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "must rollback"}, Labels: publicops.LabelPatch{Add: []string{"must-rollback"}}, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"must_rollback": json.RawMessage(`true`)}}, Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: publicops.PersistenceModeEphemeral}}})
if err == nil {
t.Fatal("unversioned demotion succeeded")
}
stored, err := te.store.GetIssue(ctx, unversioned.ID)
if err != nil || stored.Title != "original" || strings.Join(stored.Labels, ",") != "keep" || !sameEmbeddedMetadataJSON(stored.Metadata, json.RawMessage(`{"keep":true}`)) || stored.Ephemeral || stored.NoHistory {
t.Fatalf("failed demotion left state %#v, %v", stored, err)
}
external := "external"
wisp := &types.Issue{ID: "ops-wisp-detached", Title: "wisp", Notes: "before", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true, Labels: []string{"keep"}, Metadata: json.RawMessage(`{"keep":true}`), ExternalRef: &external}
if err := te.store.CreateIssue(ctx, wisp, "seed"); err != nil {
t.Fatal(err)
}
updated, err := ops.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: wisp.ID, Patch: publicops.IssuePatch{AppendNotes: publicops.Field[string]{Set: true, Value: "after"}, Labels: publicops.LabelPatch{Add: []string{"added"}}, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"added": json.RawMessage(`true`)}}}})
if err != nil || !updated.Changed || updated.Issue.Notes != "before\nafter" || strings.Join(updated.Issue.Labels, ",") != "added,keep" {
t.Fatalf("wisp update = %#v, %v", updated, err)
}
updated.Issue.Labels[0], updated.Issue.Metadata[2], *updated.Issue.ExternalRef = "corrupt", 'X', "corrupt"
stored, err = te.store.GetIssue(ctx, wisp.ID)
if err != nil || strings.Join(stored.Labels, ",") != "added,keep" || !sameEmbeddedMetadataJSON(stored.Metadata, json.RawMessage(`{"added":true,"keep":true}`)) || stored.ExternalRef == nil || *stored.ExternalRef != "external" {
t.Fatalf("update result aliases store %#v, %v", stored, err)
}
closed, err := ops.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: wisp.ID})
if err != nil || !closed.Changed || closed.Issue.Status != publicops.StatusClosed {
t.Fatalf("wisp close = %#v, %v", closed, err)
}
closed.Issue.Metadata[2] = 'X'
reopened, err := ops.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: wisp.ID})
if err != nil || !reopened.Changed || reopened.Issue.Status != publicops.StatusOpen {
t.Fatalf("wisp reopen = %#v, %v", reopened, err)
}
reopened.Issue.Labels[0] = "corrupt"
stored, err = te.store.GetIssue(ctx, wisp.ID)
if err != nil || strings.Join(stored.Labels, ",") != "added,keep" || !sameEmbeddedMetadataJSON(stored.Metadata, json.RawMessage(`{"added":true,"keep":true}`)) {
t.Fatalf("lifecycle result aliases store %#v, %v", stored, err)
}
}

View file

@ -0,0 +1,50 @@
//go:build cgo
package embeddeddolt_test
import (
"context"
"testing"
"github.com/steveyegge/beads/internal/storage/conformance"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
)
func TestEmbeddedIssueOperationsCreateRoutesInfraTypesToWisps(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "infra")
ctx := t.Context()
conformance.RunIssueOperationsCreateRoutesInfraTypesToWisps(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "infra"))
}
func TestEmbeddedIssueOperationsCreateRejectsMissingDependencyTargets(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "skipdep")
ctx := t.Context()
conformance.RunIssueOperationsCreateRejectsMissingDependencyTargets(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "skipdep"))
}
func TestEmbeddedIssueOperationsUpdateFoldsMetadataIntoOneEvent(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "metaevent")
ctx := t.Context()
conformance.RunIssueOperationsUpdateFoldsMetadataIntoOneEvent(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "metaevent"))
}
func newEmbeddedIssueOperationsFixture(t *testing.T, ctx context.Context, te *testEnv, prefix string) conformance.IssueOperationsStagingFixture {
t.Helper()
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatalf("NewIssueOperations: %v", err)
}
return conformance.IssueOperationsStagingFixture{
IssuePrefix: prefix,
Operations: operations,
CreateIssue: te.store.CreateIssue,
SetConfig: te.store.SetConfig,
QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error {
te.queryScalar(t, ctx, query, args, dest...)
return nil
},
}
}

View file

@ -0,0 +1,45 @@
//go:build cgo
package embeddeddolt
import (
"context"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
)
func TestEmbeddedMoveIssuePersistenceEphemeralNoHistorySmoke(t *testing.T) {
ctx := context.Background()
store, err := Open(ctx, filepath.Join(t.TempDir(), ".beads"), "persist", "main")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = store.Close() })
if err := store.SetConfig(ctx, "issue_prefix", "persist"); err != nil {
t.Fatal(err)
}
issue := &types.Issue{ID: "persist-embedded", Title: "embedded", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if err := store.runTransaction(ctx, "persistence", func(tx *embeddedTransaction) error {
current, err := issueops.GetIssueInTx(ctx, tx.tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx.tx, current, types.PersistenceModeNoHistory)
return err
}); err != nil {
t.Fatal(err)
}
got, err := store.GetIssue(ctx, issue.ID)
if err != nil {
t.Fatal(err)
}
if got.Ephemeral || !got.NoHistory {
t.Fatalf("persistence = (%t,%t), want (false,true)", got.Ephemeral, got.NoHistory)
}
}

View file

@ -0,0 +1,287 @@
//go:build cgo
package embeddeddolt_test
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/steveyegge/beads/internal/storage/conformance"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
func TestEmbeddedIssueOperationsUpdateClaimPatchAppliesAfterClaim(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_staging_claim_patch")
ctx := t.Context()
issue := &types.Issue{ID: "ops-staging-claim-patch", Title: "claim patch", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatal(err)
}
result, err := operations.Update(ctx, publicops.UpdateRequest{
Actor: "worker",
IssueID: issue.ID,
Claim: true,
Patch: publicops.IssuePatch{
Status: publicops.Field[publicops.Status]{Set: true, Value: publicops.StatusOpen},
Assignee: publicops.Field[string]{Set: true},
},
})
if err != nil {
t.Fatal(err)
}
if !result.Changed || result.Issue.Status != publicops.StatusOpen || result.Issue.Assignee != "" {
t.Fatalf("claim then patch = %#v, want open and unassigned", result)
}
}
func TestEmbeddedIssueOperationsCreateEmptyIDPreservesParentAndReverseDependencies(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_staging_create_reverse")
ctx := t.Context()
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatal(err)
}
parent := &types.Issue{ID: "ops-staging-embedded-parent", Title: "parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic}
durableSource := &types.Issue{ID: "test-staging-embedded-durable", Title: "durable source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
wispSource := &types.Issue{ID: "test-staging-embedded-wisp", Title: "wisp source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true}
for _, issue := range []*types.Issue{parent, durableSource, wispSource} {
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
}
child, err := operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
ForceIDPrefix: true,
Issue: &types.Issue{Title: "child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
ParentID: parent.ID,
})
if err != nil {
t.Fatal(err)
}
if child.Issue.ID != parent.ID+".1" || len(child.Issue.Dependencies) != 1 || child.Issue.Dependencies[0].IssueID != child.Issue.ID || child.Issue.Dependencies[0].DependsOnID != parent.ID || child.Issue.Dependencies[0].Type != types.DepParentChild || child.Issue.Dependencies[0].Metadata != "{}" {
t.Fatalf("child aggregate = %#v", child.Issue)
}
generatedWisp, err := operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
ForceIDPrefix: true,
Issue: &types.Issue{Title: "generated wisp", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true},
Dependencies: []publicops.CreateDependency{{TargetID: durableSource.ID, Type: types.DepRelatesTo, Reverse: true, Metadata: `{"direction":"durable"}`, ThreadID: "durable-thread"}},
})
if err != nil {
t.Fatal(err)
}
durableDependencies, err := te.store.GetDependencyRecords(ctx, durableSource.ID)
if err != nil || len(durableDependencies) != 1 {
t.Fatalf("durable reverse dependency = %#v, %v", durableDependencies, err)
}
durableDependency := durableDependencies[0]
if durableDependency.IssueID != durableSource.ID || durableDependency.DependsOnID != generatedWisp.Issue.ID || durableDependency.Type != types.DepRelatesTo || !sameEmbeddedMetadataJSON(json.RawMessage(durableDependency.Metadata), json.RawMessage(`{"direction":"durable"}`)) || durableDependency.ThreadID != "durable-thread" {
t.Fatalf("durable reverse dependency = %+v", durableDependency)
}
generatedDurable, err := operations.Create(ctx, publicops.CreateRequest{
Actor: "writer",
ForceIDPrefix: true,
Issue: &types.Issue{Title: "generated durable", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
Dependencies: []publicops.CreateDependency{{TargetID: wispSource.ID, Type: types.DepRelatesTo, Reverse: true, Metadata: `{"direction":"wisp"}`, ThreadID: "wisp-thread"}},
})
if err != nil {
t.Fatal(err)
}
wispDependencies, err := te.store.GetDependencyRecords(ctx, wispSource.ID)
if err != nil || len(wispDependencies) != 1 {
t.Fatalf("wisp reverse dependency = %#v, %v", wispDependencies, err)
}
wispDependency := wispDependencies[0]
if wispDependency.IssueID != wispSource.ID || wispDependency.DependsOnID != generatedDurable.Issue.ID || wispDependency.Type != types.DepRelatesTo || !sameEmbeddedMetadataJSON(json.RawMessage(wispDependency.Metadata), json.RawMessage(`{"direction":"wisp"}`)) || wispDependency.ThreadID != "wisp-thread" {
t.Fatalf("wisp reverse dependency = %+v", wispDependency)
}
}
func TestEmbeddedIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops")
ctx := t.Context()
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatal(err)
}
conformance.RunIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t, ctx, conformance.IssueOperationsStagingFixture{
IssuePrefix: "ops",
Operations: operations,
CreateIssue: te.store.CreateIssue,
Commit: te.store.Commit,
Exec: func(ctx context.Context, query string, args ...any) error {
te.exec(t, ctx, query, args...)
return nil
},
QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error {
te.queryScalar(t, ctx, query, args, dest...)
return nil
},
})
}
func TestEmbeddedIssueOperationsCreateParentChildRecomputesWaitsForClosure(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops")
ctx := t.Context()
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatal(err)
}
conformance.RunIssueOperationsCreateParentChildRecomputesWaitsForClosure(t, ctx, conformance.IssueOperationsStagingFixture{
IssuePrefix: "ops",
Operations: operations,
CreateIssue: te.store.CreateIssue,
AddDependency: te.store.AddDependency,
GetReadyWork: te.store.GetReadyWork,
Commit: te.store.Commit,
QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error {
te.queryScalar(t, ctx, query, args, dest...)
return nil
},
})
}
func TestEmbeddedIssueOperationsUpdateInvalidIssueTypePreservesValidationSentinel(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_staging_invalid_type")
ctx := t.Context()
issue := &types.Issue{ID: "ops-staging-invalid-type", Title: "invalid type", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatal(err)
}
_, err = operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: publicops.IssuePatch{IssueType: publicops.Field[publicops.IssueType]{Set: true, Value: "not-a-type"}}})
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("invalid issue type error = %v, want ErrValidation", err)
}
}
func TestEmbeddedIssueOperationsUpdateNotesConflictPreservesValidationSentinel(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_staging_notes_conflict")
ctx := t.Context()
issue := &types.Issue{ID: "ops-staging-notes-conflict", Title: "notes conflict", Notes: "before", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatal(err)
}
_, err = operations.Update(ctx, publicops.UpdateRequest{
Actor: "writer",
IssueID: issue.ID,
Patch: publicops.IssuePatch{
Notes: publicops.Field[string]{Set: true, Value: "replacement"},
AppendNotes: publicops.Field[string]{Set: true, Value: "append"},
},
})
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("notes conflict error = %v, want ErrValidation", err)
}
stored, err := te.store.GetIssue(ctx, issue.ID)
if err != nil || stored.Notes != "before" {
t.Fatalf("notes conflict persisted notes = %q, %v; want before", stored.Notes, err)
}
}
func TestEmbeddedIssueOperationsUpdateParentStagesBlockedStateAndRollsBackFailure(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_staging_parent_state")
ctx := t.Context()
issues := []*types.Issue{
{ID: "ops-staging-parent-blocker", Title: "blocker", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
{ID: "ops-staging-parent-clean", Title: "clean parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic},
{ID: "ops-staging-parent-blocked", Title: "blocked parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeEpic},
{ID: "ops-staging-parent-child", Title: "child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
{ID: "ops-staging-parent-rollback", Title: "rollback child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
}
for _, issue := range issues {
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatal(err)
}
}
for _, dependency := range []*types.Dependency{
{IssueID: "ops-staging-parent-blocked", DependsOnID: "ops-staging-parent-blocker", Type: types.DepBlocks},
{IssueID: "ops-staging-parent-child", DependsOnID: "ops-staging-parent-clean", Type: types.DepParentChild},
{IssueID: "ops-staging-parent-rollback", DependsOnID: "ops-staging-parent-blocked", Type: types.DepParentChild},
} {
if err := te.store.AddDependency(ctx, dependency, "seed"); err != nil {
t.Fatal(err)
}
}
if err := te.store.Commit(ctx, "seed blocked parent state"); err != nil {
t.Fatal(err)
}
operations, err := embeddeddolt.NewIssueOperations(te.store)
if err != nil {
t.Fatal(err)
}
result, err := operations.Update(ctx, publicops.UpdateRequest{
Actor: "writer",
IssueID: "ops-staging-parent-child",
Patch: publicops.IssuePatch{ParentID: publicops.Field[string]{Set: true, Value: "ops-staging-parent-blocked"}},
})
if err != nil || !result.Changed || embeddedIssueParentIDs(result.Issue) != "ops-staging-parent-blocked" {
t.Fatalf("blocked parent replacement = %#v, %v", result, err)
}
var workingBlocked, headBlocked bool
te.queryScalar(t, ctx, "SELECT is_blocked FROM issues WHERE id = ?", []any{"ops-staging-parent-child"}, &workingBlocked)
te.queryScalar(t, ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{"ops-staging-parent-child"}, &headBlocked)
if !workingBlocked || !headBlocked {
t.Fatalf("blocked child state = working %t, HEAD %t; want both true", workingBlocked, headBlocked)
}
_, err = operations.Update(ctx, publicops.UpdateRequest{
Actor: "writer",
IssueID: "ops-staging-parent-rollback",
Patch: publicops.IssuePatch{
Title: publicops.Field[string]{Set: true, Value: "must rollback"},
ParentID: publicops.Field[string]{Set: true, Value: "ops-staging-parent-missing"},
},
})
if err == nil {
t.Fatal("missing parent replacement succeeded")
}
rolledBack, err := te.store.GetIssue(ctx, "ops-staging-parent-rollback")
if err != nil {
t.Fatal(err)
}
dependencies, err := te.store.GetDependencyRecords(ctx, rolledBack.ID)
if err != nil {
t.Fatal(err)
}
if rolledBack.Title != "rollback child" || len(dependencies) != 1 || dependencies[0].IssueID != rolledBack.ID || dependencies[0].DependsOnID != "ops-staging-parent-blocked" || dependencies[0].Type != types.DepParentChild {
t.Fatalf("failed parent replacement persisted issue = %#v, dependencies %#v", rolledBack, dependencies)
}
var rollbackWorkingTitle, rollbackHeadTitle string
te.queryScalar(t, ctx, "SELECT title, is_blocked FROM issues WHERE id = ?", []any{rolledBack.ID}, &rollbackWorkingTitle, &workingBlocked)
te.queryScalar(t, ctx, "SELECT title, is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{rolledBack.ID}, &rollbackHeadTitle, &headBlocked)
if rollbackWorkingTitle != "rollback child" || rollbackHeadTitle != "rollback child" || !workingBlocked || !headBlocked {
t.Fatalf("failed parent replacement state = working (%q, %t), HEAD (%q, %t)", rollbackWorkingTitle, workingBlocked, rollbackHeadTitle, headBlocked)
}
}

View file

@ -0,0 +1,29 @@
//go:build cgo
package embeddeddolt
import (
"context"
"database/sql"
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
)
func (s *EmbeddedDoltStore) runIssueOperationTx(ctx context.Context, commitMsg string, fn func(*sql.Tx) (storageissueops.ChangedTables, error)) error {
// An empty message is runTransaction's existing "write, but do not version
// commit" signal — the same one CLI batch mode already uses for its
// RunInTransaction writes.
if storageissueops.VersionCommitDeferred(ctx) {
commitMsg = ""
}
return s.runTransaction(ctx, commitMsg, func(tx *embeddedTransaction) error {
tables, err := fn(tx.tx)
if err != nil {
return err
}
for table := range tables {
tx.dirty.MarkDirty(table)
}
return nil
})
}

View file

@ -0,0 +1,61 @@
//go:build cgo
package embeddeddolt_test
import (
"encoding/json"
"errors"
"testing"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// TestEmbeddedIssueOperationsRejectsInvalidUpdatesWithoutMutation pins the
// shared update validation on this backend's own lifecycle, so a request the
// unit-of-work backend refuses is refused here too — and refused before any
// field in the same patch reaches the row.
func TestEmbeddedIssueOperationsRejectsInvalidUpdatesWithoutMutation(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "ops_validation")
ctx := t.Context()
operations, err := te.store.IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle: %v", err)
}
issue := &types.Issue{ID: "ops_validation-1", Title: "original", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Metadata: json.RawMessage(`{"keep":"yes"}`)}
if err := te.store.CreateIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed: %v", err)
}
mutation := publicops.Field[string]{Set: true, Value: "mutated"}
for _, tc := range []struct {
name string
patch publicops.IssuePatch
}{
{"priority above range", publicops.IssuePatch{Title: mutation, Priority: publicops.Field[int]{Set: true, Value: 9}}},
{"metadata set key with unsafe characters", publicops.IssuePatch{Title: mutation, Metadata: publicops.MetadataPatch{Set: map[string]json.RawMessage{"bad-key": json.RawMessage(`"value"`)}}}},
} {
t.Run(tc.name, func(t *testing.T) {
if _, err := operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: issue.ID, Patch: tc.patch}); !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("Update error = %v, want ErrValidation", err)
}
stored, err := te.store.GetIssue(ctx, issue.ID)
if err != nil {
t.Fatalf("GetIssue: %v", err)
}
if stored.Title != "original" || stored.Priority != 2 {
t.Fatalf("rejected update mutated the row: title %q, priority %d", stored.Title, stored.Priority)
}
metadata := map[string]json.RawMessage{}
if len(stored.Metadata) > 0 {
if err := json.Unmarshal(stored.Metadata, &metadata); err != nil {
t.Fatalf("unmarshal stored metadata %s: %v", stored.Metadata, err)
}
}
if _, ok := metadata["bad-key"]; ok {
t.Fatalf("rejected update wrote metadata: %s", stored.Metadata)
}
})
}
}

View file

@ -137,23 +137,13 @@ func (s *EmbeddedDoltStore) ReclaimExpiredLeases(ctx context.Context, olderThan
return reclaimed, err
}
// ReopenIssue reopens a closed issue, setting status to open and clearing
// closed_at and defer_until. If reason is non-empty, it is recorded as a comment.
// Wraps UpdateIssue; EmbeddedDolt auto-commits the transaction.
// ReopenIssue reopens a done-category issue atomically. EmbeddedDolt commits
// the issue, event, comment, lease, and dependency changes together.
func (s *EmbeddedDoltStore) ReopenIssue(ctx context.Context, id string, reason string, actor string) error {
updates := map[string]interface{}{
"status": string(types.StatusOpen),
"defer_until": nil,
}
if err := s.UpdateIssue(ctx, id, updates, actor); err != nil {
return s.withConn(ctx, true, func(tx *sql.Tx) error {
_, err := issueops.ReopenIssueInTx(ctx, tx, id, reason, actor)
return err
}
if reason != "" {
if err := s.AddComment(ctx, id, actor, reason); err != nil {
return fmt.Errorf("reopen comment: %w", err)
}
}
return nil
})
}
// UpdateIssueType changes the issue_type field of an issue.
@ -185,7 +175,7 @@ func (s *EmbeddedDoltStore) CloseIssueChecked(ctx context.Context, id string, ac
if err != nil {
return err
}
result = storage.CloseIssueResult{Unchanged: res.AlreadyClosed}
result = storage.CloseIssueResult{Unchanged: res.AlreadyClosed, OpenChildren: res.OpenChildren}
return nil
})
if err != nil {

View file

@ -0,0 +1,164 @@
//go:build cgo
package embeddeddolt_test
import (
"errors"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
func TestEmbeddedReopenIssueCategorySemantics(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "rct")
ctx := t.Context()
create := func(id string, ephemeral bool) {
t.Helper()
if err := te.store.CreateIssue(ctx, &types.Issue{
ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: ephemeral,
}, "tester"); err != nil {
t.Fatalf("CreateIssue(%s): %v", id, err)
}
}
setStatus := func(table, id, status string) {
t.Helper()
te.exec(t, ctx, `
UPDATE `+table+`
SET status = ?, closed_at = UTC_TIMESTAMP(), close_reason = ?, closed_by_session = ?,
defer_until = DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 DAY)
WHERE id = ?
`, status, "completed", "session-1", id)
}
assertReopened := func(id string) {
t.Helper()
issue, err := te.store.GetIssue(ctx, id)
if err != nil {
t.Fatalf("GetIssue(%s): %v", id, err)
}
if issue.Status != types.StatusOpen || issue.ClosedAt != nil || issue.CloseReason != "" || issue.ClosedBySession != "" || issue.DeferUntil != nil {
t.Fatalf("reopened issue = %+v", issue)
}
}
assertReopenEvents := func(id string) {
t.Helper()
events, err := te.store.GetEvents(ctx, id, 0)
if err != nil {
t.Fatalf("GetEvents(%s): %v", id, err)
}
var reopened, commented, statusChanged int
for _, event := range events {
switch event.EventType {
case types.EventReopened:
reopened++
case types.EventCommented:
commented++
case types.EventStatusChanged:
statusChanged++
}
}
if reopened != 1 || commented != 1 || statusChanged != 0 {
t.Fatalf(
"reopen events for %s = reopened:%d commented:%d status_changed:%d, want 1, 1, 0",
id, reopened, commented, statusChanged,
)
}
}
te.exec(t, ctx, "INSERT INTO custom_statuses (name, category) VALUES (?, ?)", "archived", string(types.CategoryDone))
create("rct-permanent", false)
create("rct-wisp", true)
setStatus("issues", "rct-permanent", "archived")
setStatus("wisps", "rct-wisp", "archived")
for _, id := range []string{"rct-permanent", "rct-wisp"} {
if err := te.store.ReopenIssue(ctx, id, "needs work", "tester"); err != nil {
t.Fatalf("ReopenIssue(%s): %v", id, err)
}
assertReopened(id)
assertReopenEvents(id)
}
for _, status := range []struct {
id string
name string
category types.StatusCategory
}{
{id: "rct-active", name: "triaged", category: types.CategoryActive},
{id: "rct-wip", name: "testing", category: types.CategoryWIP},
{id: "rct-frozen", name: "on-ice", category: types.CategoryFrozen},
{id: "rct-unknown", name: "unknown-status", category: types.CategoryUnspecified},
} {
if status.category != types.CategoryUnspecified {
te.exec(t, ctx, "INSERT INTO custom_statuses (name, category) VALUES (?, ?)", status.name, string(status.category))
}
create(status.id, false)
setStatus("issues", status.id, status.name)
if err := te.store.ReopenIssue(ctx, status.id, "ignored", "tester"); err != nil {
t.Fatalf("ReopenIssue(%s): %v", status.name, err)
}
issue, err := te.store.GetIssue(ctx, status.id)
if err != nil {
t.Fatalf("GetIssue(%s): %v", status.name, err)
}
if issue.Status != types.Status(status.name) || issue.CloseReason != "completed" {
t.Fatalf("non-done issue %s changed: %+v", status.name, issue)
}
}
create("rct-open", false)
beforeEvents, err := te.store.GetEvents(ctx, "rct-open", 0)
if err != nil {
t.Fatalf("GetEvents(open) before reopen: %v", err)
}
if err := te.store.ReopenIssue(ctx, "rct-open", "ignored", "tester"); err != nil {
t.Fatalf("ReopenIssue(open): %v", err)
}
afterEvents, err := te.store.GetEvents(ctx, "rct-open", 0)
if err != nil {
t.Fatalf("GetEvents(open) after reopen: %v", err)
}
if len(afterEvents) != len(beforeEvents) {
t.Fatalf("literal-open no-op events = %+v, want no new events", afterEvents)
}
err = te.store.ReopenIssue(ctx, "rct-missing", "", "tester")
if !errors.Is(err, storage.ErrNotFound) {
t.Fatalf("missing reopen err = %v, want ErrNotFound", err)
}
}
func TestEmbeddedReopenCustomDoneFallsBackWhenNormalizedTableMissing(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "rcf")
ctx := t.Context()
const id = "rcf-legacy-done"
if err := te.store.CreateIssue(ctx, &types.Issue{
ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask,
}, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if err := te.store.SetConfig(ctx, "status.custom", "archived:done"); err != nil {
t.Fatalf("SetConfig(status.custom): %v", err)
}
te.exec(t, ctx, `
UPDATE issues
SET status = ?, closed_at = UTC_TIMESTAMP(), close_reason = ?
WHERE id = ?
`, "archived", "completed", id)
te.exec(t, ctx, "DROP TABLE custom_statuses")
if err := te.store.ReopenIssue(ctx, id, "", "tester"); err != nil {
t.Fatalf("ReopenIssue: %v", err)
}
issue, err := te.store.GetIssue(ctx, id)
if err != nil {
t.Fatalf("GetIssue: %v", err)
}
if issue.Status != types.StatusOpen || issue.ClosedAt != nil || issue.CloseReason != "" {
t.Fatalf("reopened issue = %+v", issue)
}
}

View file

@ -18,6 +18,16 @@ import (
// After the SQL transaction commits, dirty tables are selectively staged
// and a Dolt version commit is created with the given message.
func (s *EmbeddedDoltStore) RunInTransaction(ctx context.Context, commitMsg string, fn func(tx storage.Transaction) error) error {
return s.runTransaction(ctx, commitMsg, func(tx *embeddedTransaction) error { return fn(tx) })
}
// RunInIssueLifecycleTransaction keeps lifecycle work on the embedded store's
// one transaction and stages only durable rows changed by that work.
func (s *EmbeddedDoltStore) RunInIssueLifecycleTransaction(ctx context.Context, commitMsg string, fn func(tx storage.IssueLifecycleTransaction) error) error {
return s.runTransaction(ctx, commitMsg, func(tx *embeddedTransaction) error { return fn(tx) })
}
func (s *EmbeddedDoltStore) runTransaction(ctx context.Context, commitMsg string, fn func(tx *embeddedTransaction) error) error {
var tracker versioncontrolops.DirtyTableTracker
if err := s.withConn(ctx, true, func(tx *sql.Tx) error {
@ -70,17 +80,49 @@ func (t *embeddedTransaction) CreateIssues(ctx context.Context, issues []*types.
}
func (t *embeddedTransaction) UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error {
t.dirty.MarkDirty("issues")
t.dirty.MarkDirty("events")
_, err := issueops.UpdateIssueInTx(ctx, t.tx, id, updates, actor)
return err
issueTable, _, eventTable, _ := issueops.WispTableRouting(issueops.IsActiveWispInTx(ctx, t.tx, id))
result, err := issueops.UpdateIssueInTx(ctx, t.tx, id, updates, actor)
if err != nil {
return err
}
if !result.Changed {
return nil
}
t.dirty.MarkDirty(issueTable)
t.dirty.MarkDirty(eventTable)
return nil
}
func (t *embeddedTransaction) CloseIssue(ctx context.Context, id string, reason string, actor string, session string) error {
t.dirty.MarkDirty("issues")
t.dirty.MarkDirty("events")
_, err := issueops.CloseIssueInTx(ctx, t.tx, id, reason, actor, session)
return err
issueTable, _, eventTable, _ := issueops.WispTableRouting(issueops.IsActiveWispInTx(ctx, t.tx, id))
result, err := issueops.CloseIssueInTx(ctx, t.tx, id, reason, actor, session)
if err != nil || result.AlreadyClosed {
return err
}
t.dirty.MarkDirty(issueTable)
t.dirty.MarkDirty(eventTable)
if result.IssueRowsChanged {
t.dirty.MarkDirty("issues")
}
return nil
}
// ReopenIssueWithResult lets transaction-scoped callers preserve lifecycle
// semantics when an update crosses the done boundary.
func (t *embeddedTransaction) ReopenIssueWithResult(ctx context.Context, id string, reason string, actor string) (bool, error) {
issueTable, _, eventTable, _ := issueops.WispTableRouting(issueops.IsActiveWispInTx(ctx, t.tx, id))
result, err := issueops.ReopenIssueInTx(ctx, t.tx, id, reason, actor)
if err != nil {
return false, err
}
if result.Changed {
t.dirty.MarkDirty(issueTable)
t.dirty.MarkDirty(eventTable)
if result.IssueRowsChanged {
t.dirty.MarkDirty("issues")
}
}
return result.Changed, nil
}
func (t *embeddedTransaction) DeleteIssue(ctx context.Context, id string) error {
@ -173,13 +215,23 @@ func (t *embeddedTransaction) GetDependencyRecords(ctx context.Context, issueID
}
func (t *embeddedTransaction) AddLabel(ctx context.Context, issueID, label, actor string) error {
t.dirty.MarkDirty("labels")
return issueops.AddLabelInTx(ctx, t.tx, "", "", issueID, label, actor)
_, labelTable, eventTable, _ := issueops.WispTableRouting(issueops.IsActiveWispInTx(ctx, t.tx, issueID))
if err := issueops.AddLabelInTx(ctx, t.tx, labelTable, eventTable, issueID, label, actor); err != nil {
return err
}
t.dirty.MarkDirty(labelTable)
t.dirty.MarkDirty(eventTable)
return nil
}
func (t *embeddedTransaction) RemoveLabel(ctx context.Context, issueID, label, actor string) error {
t.dirty.MarkDirty("labels")
return issueops.RemoveLabelInTx(ctx, t.tx, "", "", issueID, label, actor)
_, labelTable, eventTable, _ := issueops.WispTableRouting(issueops.IsActiveWispInTx(ctx, t.tx, issueID))
if err := issueops.RemoveLabelInTx(ctx, t.tx, labelTable, eventTable, issueID, label, actor); err != nil {
return err
}
t.dirty.MarkDirty(labelTable)
t.dirty.MarkDirty(eventTable)
return nil
}
func (t *embeddedTransaction) GetLabels(ctx context.Context, issueID string) ([]string, error) {

View file

@ -0,0 +1,387 @@
//go:build cgo
package embeddeddolt_test
import (
"context"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
)
// TestEmbeddedTransactionWispLifecyclePersistsDurableDependent verifies that
// a transactional wisp lifecycle transition publishes the durable dependent's
// recomputed blocked state into the versioned history.
func TestEmbeddedTransactionWispLifecyclePersistsDurableDependent(t *testing.T) {
skipUnlessEmbeddedDolt(t)
ctx := t.Context()
for _, test := range []struct {
name string
wispID string
dependerID string
wantBlocked bool
run func(t *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error
}{
{
name: "close",
wispID: "embedded-tx-wisp-close",
dependerID: "embedded-tx-close-depender",
run: func(_ *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error {
return store.RunInIssueLifecycleTransaction(ctx, "test: close wisp blocker", func(tx storage.IssueLifecycleTransaction) error {
return tx.CloseIssue(ctx, wispID, "done", "tester", "session")
})
},
},
{
name: "reopen",
wispID: "embedded-tx-wisp-reopen",
dependerID: "embedded-tx-reopen-depender",
wantBlocked: true,
run: func(t *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error {
return store.RunInIssueLifecycleTransaction(ctx, "test: reopen wisp blocker", func(tx storage.IssueLifecycleTransaction) error {
changed, err := tx.ReopenIssueWithResult(ctx, wispID, "", "tester")
if err != nil {
return err
}
if !changed {
t.Fatal("transactional reopen reported Changed=false")
}
return nil
})
},
},
} {
t.Run(test.name, func(t *testing.T) {
te := newTestEnv(t, "txwisp")
seedEmbeddedTransactionWispBlocker(t, te, ctx, test.dependerID, test.wispID)
if err := te.store.Commit(ctx, "test: seed wisp blocker"); err != nil {
t.Fatalf("Commit seed: %v", err)
}
if test.name == "reopen" {
if err := te.store.CloseIssue(ctx, test.wispID, "done", "tester", "session"); err != nil {
t.Fatalf("seed CloseIssue: %v", err)
}
if err := te.store.Commit(ctx, "test: seed closed wisp blocker"); err != nil {
t.Fatalf("Commit closed seed: %v", err)
}
}
before, err := te.store.GetCurrentCommit(ctx)
if err != nil {
t.Fatalf("GetCurrentCommit before: %v", err)
}
if err := test.run(t, te.store, ctx, test.wispID); err != nil {
t.Fatalf("RunInTransaction: %v", err)
}
after, err := te.store.GetCurrentCommit(ctx)
if err != nil {
t.Fatalf("GetCurrentCommit after: %v", err)
}
if after == before {
t.Errorf("transactional wisp lifecycle did not publish durable dependent; HEAD remained %s", before)
}
var working, committed bool
te.queryScalar(t, ctx, "SELECT is_blocked FROM issues WHERE id = ?", []any{test.dependerID}, &working)
te.queryScalar(t, ctx, "SELECT is_blocked FROM issues AS OF 'HEAD' WHERE id = ?", []any{test.dependerID}, &committed)
if working != test.wantBlocked {
t.Errorf("working durable depender is_blocked = %t, want %t", working, test.wantBlocked)
}
if committed != test.wantBlocked {
t.Errorf("committed durable depender is_blocked = %t, want %t", committed, test.wantBlocked)
}
})
}
}
func TestEmbeddedTransactionStandaloneWispLifecyclePersistsWithoutDoltCommit(t *testing.T) {
skipUnlessEmbeddedDolt(t)
ctx := t.Context()
for _, test := range []struct {
name string
wispID string
wantStatus types.Status
run func(t *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error
}{
{
name: "close",
wispID: "embedded-tx-standalone-wisp-close",
wantStatus: types.StatusClosed,
run: func(_ *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error {
return store.RunInIssueLifecycleTransaction(ctx, "test: close standalone wisp", func(tx storage.IssueLifecycleTransaction) error {
return tx.CloseIssue(ctx, wispID, "done", "tester", "session")
})
},
},
{
name: "reopen",
wispID: "embedded-tx-standalone-wisp-reopen",
wantStatus: types.StatusOpen,
run: func(t *testing.T, store *embeddeddolt.EmbeddedDoltStore, ctx context.Context, wispID string) error {
if err := store.CloseIssue(ctx, wispID, "done", "tester", "session"); err != nil {
return err
}
return store.RunInIssueLifecycleTransaction(ctx, "test: reopen standalone wisp", func(tx storage.IssueLifecycleTransaction) error {
changed, err := tx.ReopenIssueWithResult(ctx, wispID, "", "tester")
if err != nil {
return err
}
if !changed {
t.Fatal("transactional reopen reported Changed=false")
}
return nil
})
},
},
} {
t.Run(test.name, func(t *testing.T) {
te := newTestEnv(t, "txstandalone")
if err := te.store.CreateIssue(ctx, &types.Issue{ID: test.wispID, Title: test.wispID, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true}, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
before, err := te.store.GetCurrentCommit(ctx)
if err != nil {
t.Fatalf("GetCurrentCommit before: %v", err)
}
if err := test.run(t, te.store, ctx, test.wispID); err != nil {
t.Fatalf("RunInIssueLifecycleTransaction: %v", err)
}
after, err := te.store.GetCurrentCommit(ctx)
if err != nil {
t.Fatalf("GetCurrentCommit after: %v", err)
}
if after != before {
t.Fatalf("standalone wisp lifecycle changed HEAD from %s to %s", before, after)
}
issue, err := te.store.GetIssue(ctx, test.wispID)
if err != nil {
t.Fatalf("GetIssue: %v", err)
}
if issue.Status != test.wantStatus {
t.Errorf("wisp status = %q, want %q", issue.Status, test.wantStatus)
}
})
}
}
func TestEmbeddedTransactionSameStatusDoesNotPublishUnrelatedDurableChanges(t *testing.T) {
skipUnlessEmbeddedDolt(t)
ctx := t.Context()
te := newTestEnv(t, "txsamestatus")
const (
targetID = "embedded-tx-same-status-target"
dirtyID = "embedded-tx-same-status-dirty"
)
for _, issue := range []*types.Issue{
{ID: targetID, Title: "target baseline", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
{ID: dirtyID, Title: "dirty baseline", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
} {
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue(%s): %v", issue.ID, err)
}
}
if err := te.store.Commit(ctx, "test: seed same-status baseline"); err != nil {
t.Fatalf("Commit baseline: %v", err)
}
before, err := te.store.GetCurrentCommit(ctx)
if err != nil {
t.Fatalf("GetCurrentCommit before: %v", err)
}
te.exec(t, ctx, "UPDATE issues SET title = ? WHERE id = ?", "working-only title", dirtyID)
te.exec(t, ctx,
"UPDATE events SET comment = ? WHERE issue_id = ? AND event_type = ?",
"working-only event", dirtyID, string(types.EventCreated))
if err := te.store.RunInIssueLifecycleTransaction(ctx, "test: same-status update", func(tx storage.IssueLifecycleTransaction) error {
return tx.UpdateIssue(ctx, targetID, map[string]interface{}{"status": types.StatusOpen}, "tester")
}); err != nil {
t.Fatalf("RunInIssueLifecycleTransaction: %v", err)
}
after, err := te.store.GetCurrentCommit(ctx)
if err != nil {
t.Fatalf("GetCurrentCommit after: %v", err)
}
if after != before {
t.Errorf("same-status transaction changed HEAD from %s to %s", before, after)
}
var workingTitle, headTitle string
te.queryScalar(t, ctx, "SELECT title FROM issues WHERE id = ?", []any{dirtyID}, &workingTitle)
te.queryScalar(t, ctx, "SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", []any{dirtyID}, &headTitle)
if workingTitle != "working-only title" || headTitle != "dirty baseline" {
t.Errorf("unrelated issue titles = working:%q HEAD:%q", workingTitle, headTitle)
}
// events is dolt_ignored since migration 0062 (bd-red8u). On the
// production-shaped database this harness builds, the table is absent from
// committed history entirely, so an AS OF 'HEAD' probe errors rather than
// proving anything; the plane contract itself is pinned by
// TestEmbeddedMigration0062FlipsEventsToIgnoredPlane. "Nothing was
// published" is already carried by the HEAD-unchanged assertion above, so
// what is left is that the unrelated audit edit survives in the working set.
var workingEvent int
te.queryScalar(t, ctx,
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND comment = ?",
[]any{dirtyID, string(types.EventCreated), "working-only event"}, &workingEvent)
if workingEvent != 1 {
t.Errorf("unrelated working-set event edit count = %d, want 1", workingEvent)
}
}
func TestEmbeddedTransactionStandaloneWispMutationDoesNotPublishUnrelatedDurableChanges(t *testing.T) {
skipUnlessEmbeddedDolt(t)
ctx := t.Context()
te := newTestEnv(t, "txwispisolation")
const (
durableID = "tx-wisp-isolation-durable"
wispID = "tx-wisp-isolation-wisp"
baselineLabel = "durable-baseline"
workingLabel = "durable-working-only"
removeWispLabel = "remove-from-wisp"
addWispLabel = "add-to-wisp"
)
if err := te.store.CreateIssue(ctx, &types.Issue{
ID: durableID, Title: "durable baseline", Status: types.StatusOpen,
Priority: 2, IssueType: types.TypeTask,
}, "tester"); err != nil {
t.Fatalf("CreateIssue durable: %v", err)
}
if err := te.store.AddLabel(ctx, durableID, baselineLabel, "tester"); err != nil {
t.Fatalf("AddLabel durable baseline: %v", err)
}
if err := te.store.CreateIssue(ctx, &types.Issue{
ID: wispID, Title: "wisp baseline", Status: types.StatusOpen,
Priority: 2, IssueType: types.TypeTask, Ephemeral: true,
}, "tester"); err != nil {
t.Fatalf("CreateIssue wisp: %v", err)
}
if err := te.store.AddLabel(ctx, wispID, removeWispLabel, "tester"); err != nil {
t.Fatalf("AddLabel wisp baseline: %v", err)
}
if err := te.store.Commit(ctx, "test: seed durable baseline"); err != nil {
t.Fatalf("Commit baseline: %v", err)
}
before, err := te.store.GetCurrentCommit(ctx)
if err != nil {
t.Fatalf("GetCurrentCommit before: %v", err)
}
te.exec(t, ctx, "UPDATE issues SET title = ? WHERE id = ?", "durable working-only", durableID)
te.exec(t, ctx, "UPDATE events SET comment = ? WHERE issue_id = ? AND event_type = ?",
"durable working-only", durableID, string(types.EventCreated))
te.exec(t, ctx, "UPDATE labels SET label = ? WHERE issue_id = ? AND label = ?",
workingLabel, durableID, baselineLabel)
if err := te.store.RunInIssueLifecycleTransaction(ctx, "test: mutate standalone wisp", func(tx storage.IssueLifecycleTransaction) error {
if err := tx.UpdateIssue(ctx, wispID, map[string]interface{}{"title": "wisp updated"}, "tester"); err != nil {
return err
}
if err := tx.RemoveLabel(ctx, wispID, removeWispLabel, "tester"); err != nil {
return err
}
return tx.AddLabel(ctx, wispID, addWispLabel, "tester")
}); err != nil {
t.Fatalf("RunInIssueLifecycleTransaction: %v", err)
}
after, err := te.store.GetCurrentCommit(ctx)
if err != nil {
t.Fatalf("GetCurrentCommit after: %v", err)
}
if after != before {
t.Errorf("standalone wisp mutation changed HEAD from %s to %s", before, after)
}
wisp, err := te.store.GetIssue(ctx, wispID)
if err != nil {
t.Fatalf("GetIssue wisp: %v", err)
}
if wisp.Title != "wisp updated" {
t.Errorf("wisp title = %q, want %q", wisp.Title, "wisp updated")
}
labels, err := te.store.GetLabels(ctx, wispID)
if err != nil {
t.Fatalf("GetLabels wisp: %v", err)
}
if len(labels) != 1 || labels[0] != addWispLabel {
t.Errorf("wisp labels = %v, want [%s]", labels, addWispLabel)
}
for _, event := range []struct {
eventType types.EventType
comment string
}{
{eventType: types.EventUpdated},
{eventType: types.EventLabelRemoved, comment: "Removed label: " + removeWispLabel},
{eventType: types.EventLabelAdded, comment: "Added label: " + addWispLabel},
} {
var count int
if event.comment == "" {
te.queryScalar(t, ctx,
"SELECT COUNT(*) FROM wisp_events WHERE issue_id = ? AND event_type = ?",
[]any{wispID, string(event.eventType)}, &count)
} else {
te.queryScalar(t, ctx,
"SELECT COUNT(*) FROM wisp_events WHERE issue_id = ? AND event_type = ? AND comment = ?",
[]any{wispID, string(event.eventType), event.comment}, &count)
}
if count != 1 {
t.Errorf("wisp event %s/%q count = %d, want 1", event.eventType, event.comment, count)
}
}
var workingTitle, headTitle string
te.queryScalar(t, ctx, "SELECT title FROM issues WHERE id = ?", []any{durableID}, &workingTitle)
te.queryScalar(t, ctx, "SELECT title FROM issues AS OF 'HEAD' WHERE id = ?", []any{durableID}, &headTitle)
if workingTitle != "durable working-only" || headTitle != "durable baseline" {
t.Errorf("durable issue titles = working:%q HEAD:%q", workingTitle, headTitle)
}
// events is dolt_ignored since migration 0062 (bd-red8u) and has no HEAD
// state on this production-shaped database (see the same-status test above
// and TestEmbeddedMigration0062FlipsEventsToIgnoredPlane). Publication is
// covered by the HEAD-unchanged assertion; the durable label check below
// still exercises a versioned side table at HEAD.
var workingEvent int
te.queryScalar(t, ctx,
"SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND comment = ?",
[]any{durableID, string(types.EventCreated), "durable working-only"}, &workingEvent)
if workingEvent != 1 {
t.Errorf("durable working-set event edit count = %d, want 1", workingEvent)
}
var workingLabelCount, headLabelCount int
te.queryScalar(t, ctx,
"SELECT COUNT(*) FROM labels WHERE issue_id = ? AND label = ?",
[]any{durableID, workingLabel}, &workingLabelCount)
te.queryScalar(t, ctx,
"SELECT COUNT(*) FROM labels AS OF 'HEAD' WHERE issue_id = ? AND label = ?",
[]any{durableID, workingLabel}, &headLabelCount)
if workingLabelCount != 1 || headLabelCount != 0 {
t.Errorf("durable label edit counts = working:%d HEAD:%d", workingLabelCount, headLabelCount)
}
}
func seedEmbeddedTransactionWispBlocker(t *testing.T, te *testEnv, ctx context.Context, dependerID, wispID string) {
t.Helper()
if err := te.store.CreateIssue(ctx, &types.Issue{ID: dependerID, Title: dependerID, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, "tester"); err != nil {
t.Fatalf("CreateIssue durable: %v", err)
}
if err := te.store.CreateIssue(ctx, &types.Issue{ID: wispID, Title: wispID, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true}, "tester"); err != nil {
t.Fatalf("CreateIssue wisp: %v", err)
}
if err := te.store.AddDependency(ctx, &types.Dependency{IssueID: dependerID, DependsOnID: wispID, Type: types.DepBlocks}, "tester"); err != nil {
t.Fatalf("AddDependency: %v", err)
}
var blocked bool
te.queryScalar(t, ctx, "SELECT is_blocked FROM issues WHERE id = ?", []any{dependerID}, &blocked)
if !blocked {
t.Fatal("seed durable depender is not blocked")
}
}

View file

@ -2,9 +2,7 @@ package storage
import "fmt"
// ErrUnsupported reports that a storage backend does not implement an
// operation. Typed per PROPOSAL-pluggable-storage-backends.md §4.0 error
// taxonomy; this is the embryo of the seam's ErrUnsupported{Op, Backend}.
// ErrUnsupported reports an operation unavailable on a storage backend.
type ErrUnsupported struct {
Op string // method name, e.g. "AddLabel" or "Transaction.CreateIssues"
Backend string // e.g. "sqlite"

View file

@ -259,6 +259,26 @@ func (h *HookFiringStore) RunInTransaction(ctx context.Context, commitMsg string
return nil
}
// RunInIssueLifecycleTransaction tracks lifecycle hooks and fires them only
// after the underlying lifecycle transaction commits.
func (h *HookFiringStore) RunInIssueLifecycleTransaction(ctx context.Context, commitMsg string, fn func(tx IssueLifecycleTransaction) error) error {
var tracked *hookTrackingLifecycleTransaction
err := h.inner.RunInIssueLifecycleTransaction(ctx, commitMsg, func(tx IssueLifecycleTransaction) error {
tracked = &hookTrackingLifecycleTransaction{
hookTrackingTransaction: &hookTrackingTransaction{Transaction: tx},
reopener: tx,
}
return fn(tracked)
})
if err != nil || tracked == nil {
return err
}
for _, p := range tracked.pending {
h.fireHook(p.event, p.issue)
}
return nil
}
// ── Internal helpers ────────────────────────────────────────────────
func (h *HookFiringStore) fireHook(event string, issue *types.Issue) {
@ -268,6 +288,34 @@ func (h *HookFiringStore) fireHook(event string, issue *types.Issue) {
h.runner.Run(event, issue)
}
// CompleteIssueOperationCreate fires hooks for a committed guarded create.
// dependencies is a request-neutral snapshot of the dependency changes whose
// source issues need update hooks.
func (h *HookFiringStore) CompleteIssueOperationCreate(ctx context.Context, issue *types.Issue, dependencies []*types.Dependency) {
for _, pending := range createHookEvents(issue) {
h.fireHook(pending.event, pending.issue)
}
if h.runner == nil || len(dependencies) == 0 {
return
}
request := &types.Issue{Dependencies: cloneDependenciesForHook(dependencies)}
for _, pending := range dependencyHookEvents(ctx, []*types.Issue{request}, h.inner.GetIssue, h.inner.GetDependencyRecords) {
h.fireHook(pending.event, pending.issue)
}
}
// CompleteIssueOperationUpdate fires the update hook for a committed guarded
// operation.
func (h *HookFiringStore) CompleteIssueOperationUpdate(issue *types.Issue) {
h.fireHook(hooks.EventUpdate, issue)
}
// CompleteIssueOperationClose fires the close hook for a committed guarded
// close.
func (h *HookFiringStore) CompleteIssueOperationClose(issue *types.Issue) {
h.fireHook(hooks.EventClose, issue)
}
func (h *HookFiringStore) fireHookByID(ctx context.Context, event, id string) {
if h.runner == nil {
return
@ -523,6 +571,22 @@ func (t *hookTrackingTransaction) CloseIssue(ctx context.Context, id string, rea
return nil
}
type hookTrackingLifecycleTransaction struct {
*hookTrackingTransaction
reopener IssueLifecycleTransaction
}
func (t *hookTrackingLifecycleTransaction) ReopenIssueWithResult(ctx context.Context, id string, reason string, actor string) (bool, error) {
changed, err := t.reopener.ReopenIssueWithResult(ctx, id, reason, actor)
if err != nil || !changed {
return changed, err
}
if issue, getErr := t.Transaction.GetIssue(ctx, id); getErr == nil {
t.pending = append(t.pending, pendingHook{hooks.EventUpdate, issue})
}
return true, nil
}
func (t *hookTrackingTransaction) AddDependency(ctx context.Context, dep *types.Dependency, actor string) error {
return t.AddDependencyWithOptions(ctx, dep, actor, DependencyAddOptions{})
}

View file

@ -27,7 +27,9 @@ type fakeHookStore struct {
dropDependencies bool
// updateCheckedErr, when non-nil, is returned by UpdateIssueChecked so a test
// can simulate an inner refusal (e.g. ErrVersionMismatch). nil = success.
updateCheckedErr error
updateCheckedErr error
transactionReopenError error
transactionAddLabelErr error
}
func (s fakeHookStore) CreateIssue(_ context.Context, issue *types.Issue, _ string) error {
@ -70,13 +72,37 @@ func (s fakeHookStore) UpdateIssueChecked(_ context.Context, _ string, _ map[str
}
func (s fakeHookStore) RunInTransaction(ctx context.Context, _ string, fn func(tx Transaction) error) error {
return fn(fakeHookTransaction{issues: s.issues, dropDependencies: s.dropDependencies})
return fn(fakeHookTransaction{
issues: s.issues,
dropDependencies: s.dropDependencies,
reopenError: s.transactionReopenError,
addLabelError: s.transactionAddLabelErr,
})
}
func (s fakeHookStore) RunInIssueLifecycleTransaction(ctx context.Context, _ string, fn func(tx IssueLifecycleTransaction) error) error {
return fn(fakeHookTransaction{
issues: s.issues,
dropDependencies: s.dropDependencies,
reopenError: s.transactionReopenError,
addLabelError: s.transactionAddLabelErr,
})
}
type fakeHookTransaction struct {
Transaction
issues map[string]*types.Issue
dropDependencies bool
reopenError error
addLabelError error
}
func (tx fakeHookTransaction) ReopenIssueWithResult(_ context.Context, _ string, _ string, _ string) (bool, error) {
return tx.reopenError == nil, tx.reopenError
}
func (tx fakeHookTransaction) AddLabel(_ context.Context, _ string, _ string, _ string) error {
return tx.addLabelError
}
func (tx fakeHookTransaction) CreateIssue(_ context.Context, issue *types.Issue, _ string) error {
@ -505,3 +531,57 @@ func TestHookFiringStoreUpdateIssueCheckedFiresOnSuccessOnly(t *testing.T) {
}
})
}
func TestHookFiringStoreIssueLifecycleTransactionReopenForwardsCommitOnly(t *testing.T) {
t.Run("commit forwards and fires update", func(t *testing.T) {
runner := &recordingHookRunner{}
inner := fakeHookStore{issues: map[string]*types.Issue{"reopen-hook": {ID: "reopen-hook"}}}
store := &HookFiringStore{DoltStorage: inner, inner: inner, runner: runner}
if err := store.RunInIssueLifecycleTransaction(context.Background(), "reopen", func(tx IssueLifecycleTransaction) error {
_, err := tx.ReopenIssueWithResult(context.Background(), "reopen-hook", "", "tester")
return err
}); err != nil {
t.Fatalf("RunInIssueLifecycleTransaction: %v", err)
}
if !reflect.DeepEqual(runner.events, []string{hooks.EventUpdate}) {
t.Fatalf("events = %v, want one on_update after commit", runner.events)
}
})
t.Run("later failure fires no hook", func(t *testing.T) {
runner := &recordingHookRunner{}
labelErr := errors.New("label write failed")
inner := fakeHookStore{
issues: map[string]*types.Issue{"reopen-hook": {ID: "reopen-hook"}},
transactionAddLabelErr: labelErr,
}
store := &HookFiringStore{DoltStorage: inner, inner: inner, runner: runner}
err := store.RunInIssueLifecycleTransaction(context.Background(), "reopen", func(tx IssueLifecycleTransaction) error {
if _, err := tx.ReopenIssueWithResult(context.Background(), "reopen-hook", "", "tester"); err != nil {
return err
}
return tx.AddLabel(context.Background(), "reopen-hook", "remote", "tester")
})
if !errors.Is(err, labelErr) {
t.Fatalf("RunInIssueLifecycleTransaction error = %v, want label failure", err)
}
if len(runner.events) != 0 {
t.Fatalf("events = %v, want none after rollback", runner.events)
}
})
t.Run("ordinary transaction does not expose lifecycle method", func(t *testing.T) {
inner := fakeHookStore{issues: map[string]*types.Issue{"reopen-hook": {ID: "reopen-hook"}}}
store := &HookFiringStore{DoltStorage: inner, inner: inner}
if err := store.RunInTransaction(context.Background(), "reopen", func(tx Transaction) error {
if _, ok := tx.(interface {
ReopenIssueWithResult(context.Context, string, string, string) (bool, error)
}); ok {
t.Fatal("wrapper exposed absent reopener")
}
return nil
}); err != nil {
t.Fatal(err)
}
})
}

View file

@ -0,0 +1,81 @@
package storage
import (
"context"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// IssueLifecycle returns the inner store's lifecycle with this decorator's
// completion hooks layered over it.
//
// It recurses instead of delegating. A blind delegation would hand back the
// inner store's lifecycle unchanged and silently drop every hook this
// decorator exists to fire — the failure would be invisible until someone
// noticed their on_create script had stopped running.
func (h *HookFiringStore) IssueLifecycle() (issueops.Lifecycle, error) {
inner, err := h.inner.IssueLifecycle()
if err != nil {
return nil, err
}
return &hookIssueOperations{inner: inner, hooks: h}, nil
}
// issueOperationHooks is the completion-hook surface hookIssueOperations needs
// from *HookFiringStore. Depending on the interface instead of the concrete
// decorator makes "did this verb fire a hook?" observable at this boundary, so
// the per-verb firing rules below can be tested without a real
// filesystem-backed async hook runner.
type issueOperationHooks interface {
CompleteIssueOperationCreate(ctx context.Context, issue *types.Issue, dependencies []*types.Dependency)
CompleteIssueOperationUpdate(issue *types.Issue)
CompleteIssueOperationClose(issue *types.Issue)
}
var _ issueOperationHooks = (*HookFiringStore)(nil)
type hookIssueOperations struct {
inner issueops.Lifecycle
hooks issueOperationHooks
}
// Create fires the create hook, plus an update hook for every issue on the far
// end of an edge the create wrote. The edge list comes from the request
// because a reverse edge never appears in the created issue's own
// dependencies. Reading the request back after the call is safe: an
// issueops.Lifecycle never mutates caller-owned request values.
func (o *hookIssueOperations) Create(ctx context.Context, request issueops.CreateRequest) (issueops.CreateResult, error) {
result, err := o.inner.Create(ctx, request)
if err == nil && result.Issue != nil {
o.hooks.CompleteIssueOperationCreate(ctx, result.Issue, CreatePublicCreateDependencies(result.Issue.ID, request))
}
return result, err
}
func (o *hookIssueOperations) Update(ctx context.Context, request issueops.UpdateRequest) (issueops.UpdateResult, error) {
result, err := o.inner.Update(ctx, request)
if err == nil {
o.hooks.CompleteIssueOperationUpdate(result.Issue)
}
return result, err
}
func (o *hookIssueOperations) Close(ctx context.Context, request issueops.CloseRequest) (issueops.CloseResult, error) {
result, err := o.inner.Close(ctx, request)
if err == nil {
o.hooks.CompleteIssueOperationClose(result.Issue)
}
return result, err
}
// Reopen suppresses the update hook on a no-op, matching the legacy reopen
// path (hookTrackingLifecycleTransaction.ReopenIssueWithResult). Close and
// Update stay unconditional on success, also matching their legacy paths.
func (o *hookIssueOperations) Reopen(ctx context.Context, request issueops.ReopenRequest) (issueops.ReopenResult, error) {
result, err := o.inner.Reopen(ctx, request)
if err == nil && result.Changed {
o.hooks.CompleteIssueOperationUpdate(result.Issue)
}
return result, err
}

View file

@ -0,0 +1,229 @@
package storage
import (
"context"
"errors"
"reflect"
"testing"
"github.com/steveyegge/beads/internal/hooks"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// fakeIssueOperations records which verbs reached it and can fail or report an
// unchanged result on demand.
type fakeIssueOperations struct {
calls []string
changed bool
err error
}
func (f *fakeIssueOperations) Create(context.Context, issueops.CreateRequest) (issueops.CreateResult, error) {
f.calls = append(f.calls, "create")
return issueops.CreateResult{}, f.err
}
func (f *fakeIssueOperations) Update(context.Context, issueops.UpdateRequest) (issueops.UpdateResult, error) {
f.calls = append(f.calls, "update")
return issueops.UpdateResult{Changed: f.changed}, f.err
}
func (f *fakeIssueOperations) Close(context.Context, issueops.CloseRequest) (issueops.CloseResult, error) {
f.calls = append(f.calls, "close")
return issueops.CloseResult{Changed: f.changed}, f.err
}
func (f *fakeIssueOperations) Reopen(context.Context, issueops.ReopenRequest) (issueops.ReopenResult, error) {
f.calls = append(f.calls, "reopen")
return issueops.ReopenResult{Changed: f.changed}, f.err
}
// recordingIssueOperationHooks records which completion hooks hookIssueOperations
// fired, so tests can assert the per-verb firing rules without a hook runner.
type recordingIssueOperationHooks struct {
completions []string
}
func (r *recordingIssueOperationHooks) CompleteIssueOperationCreate(context.Context, *types.Issue, []*types.Dependency) {
r.completions = append(r.completions, "create")
}
func (r *recordingIssueOperationHooks) CompleteIssueOperationUpdate(*types.Issue) {
r.completions = append(r.completions, "update")
}
func (r *recordingIssueOperationHooks) CompleteIssueOperationClose(*types.Issue) {
r.completions = append(r.completions, "close")
}
// lifecycleStore is a DoltStorage whose only real method is IssueLifecycle.
type lifecycleStore struct {
DoltStorage
lifecycle issueops.Lifecycle
err error
}
func (s lifecycleStore) IssueLifecycle() (issueops.Lifecycle, error) { return s.lifecycle, s.err }
// TestHookFiringStoreIssueLifecycleLayersHooksOverInner pins the recursion.
// Delegating to the inner store instead would still compile and still satisfy
// Storage, and every guarded write would silently stop firing hooks.
func TestHookFiringStoreIssueLifecycleLayersHooksOverInner(t *testing.T) {
inner := &fakeIssueOperations{}
store := &HookFiringStore{inner: lifecycleStore{lifecycle: inner}}
lifecycle, err := store.IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle() error = %v", err)
}
hooked, ok := lifecycle.(*hookIssueOperations)
if !ok {
t.Fatalf("IssueLifecycle() = %T, want *hookIssueOperations", lifecycle)
}
if hooked.inner != issueops.Lifecycle(inner) {
t.Fatalf("hook layer wraps %#v, want the inner store's lifecycle", hooked.inner)
}
if hooked.hooks != issueOperationHooks(store) {
t.Fatalf("hook layer fires into %#v, want the decorator itself", hooked.hooks)
}
}
func TestHookFiringStoreIssueLifecyclePropagatesInnerError(t *testing.T) {
want := errors.New("inner refused")
store := &HookFiringStore{inner: lifecycleStore{err: want}}
lifecycle, err := store.IssueLifecycle()
if !errors.Is(err, want) {
t.Fatalf("IssueLifecycle() error = %v, want %v", err, want)
}
if lifecycle != nil {
t.Fatalf("IssueLifecycle() = %T, want nil", lifecycle)
}
}
// TestHookFiringStoreCompleteIssueOperationsFireOncePerCall pins the completion
// entry points to one hook event per call, in the caller's order. Deciding
// whether a committed change warrants a hook belongs to the caller
// (hookIssueOperations, below), not to these methods.
func TestHookFiringStoreCompleteIssueOperationsFireOncePerCall(t *testing.T) {
runner := &recordingHookRunner{}
store := &HookFiringStore{runner: runner}
issue := &types.Issue{ID: "hook-issue"}
store.CompleteIssueOperationCreate(context.Background(), issue, nil)
store.CompleteIssueOperationUpdate(issue)
store.CompleteIssueOperationClose(issue)
if !reflect.DeepEqual(runner.events, []string{hooks.EventCreate, hooks.EventUpdate, hooks.EventClose}) {
t.Fatalf("hook events = %#v, want create/update/close", runner.events)
}
}
func TestHookFiringStoreCompleteIssueOperationCreateFiresReverseDependencyUpdate(t *testing.T) {
runner := &recordingHookRunner{}
reverse := &types.Dependency{IssueID: "existing-source", DependsOnID: "created", Type: types.DepRelatesTo, Metadata: `{"key":"value"}`, ThreadID: "thread"}
inner := fakeHookStore{issues: map[string]*types.Issue{
"created": {ID: "created"},
"existing-source": {ID: "existing-source", Dependencies: []*types.Dependency{reverse}},
}}
store := &HookFiringStore{DoltStorage: inner, inner: inner, runner: runner}
created := &types.Issue{ID: "created"}
store.CompleteIssueOperationCreate(context.Background(), created, []*types.Dependency{{IssueID: "existing-source", DependsOnID: "created", Type: types.DepRelatesTo}})
if !reflect.DeepEqual(runner.events, []string{hooks.EventCreate, hooks.EventUpdate}) {
t.Fatalf("hook events = %#v, want create then dependency update", runner.events)
}
if runner.issues[1].ID != "existing-source" || !reflect.DeepEqual(runner.issues[1].Dependencies, []*types.Dependency{reverse}) {
t.Fatalf("dependency hook snapshot = %#v", runner.issues[1])
}
if created.Dependencies != nil {
t.Fatalf("created result was mutated: %#v", created.Dependencies)
}
}
func TestHookIssueOperationsForwardsEveryVerbExactlyOnceAndPreservesErrors(t *testing.T) {
ctx := context.Background()
for _, test := range []struct {
name string
call func(issueops.Lifecycle) error
}{
{"create", func(ops issueops.Lifecycle) error { _, err := ops.Create(ctx, issueops.CreateRequest{}); return err }},
{"update", func(ops issueops.Lifecycle) error { _, err := ops.Update(ctx, issueops.UpdateRequest{}); return err }},
{"close", func(ops issueops.Lifecycle) error { _, err := ops.Close(ctx, issueops.CloseRequest{}); return err }},
{"reopen", func(ops issueops.Lifecycle) error { _, err := ops.Reopen(ctx, issueops.ReopenRequest{}); return err }},
} {
t.Run(test.name+" success", func(t *testing.T) {
fake := &fakeIssueOperations{changed: true}
if err := test.call(&hookIssueOperations{inner: fake, hooks: NewHookFiringStore(nil, nil)}); err != nil || len(fake.calls) != 1 {
t.Fatalf("forward = %v, calls=%v", err, fake.calls)
}
})
t.Run(test.name+" error", func(t *testing.T) {
want := errors.New("underlying")
fake := &fakeIssueOperations{changed: true, err: want}
if err := test.call(&hookIssueOperations{inner: fake, hooks: NewHookFiringStore(nil, nil)}); !errors.Is(err, want) || len(fake.calls) != 1 {
t.Fatalf("error=%v calls=%v", err, fake.calls)
}
})
}
}
func TestHookIssueOperationsFiresCompletionHooksPerVerbRules(t *testing.T) {
ctx := context.Background()
for _, test := range []struct {
name string
fake *fakeIssueOperations
call func(issueops.Lifecycle) error
wantErr bool
want []string
}{
{
// Reopen mirrors hookTrackingLifecycleTransaction.ReopenIssueWithResult
// (internal/storage/hook_decorator.go), which queues no hook when the
// reopen changed nothing.
name: "reopen no-op fires nothing",
fake: &fakeIssueOperations{changed: false},
call: func(ops issueops.Lifecycle) error { _, err := ops.Reopen(ctx, issueops.ReopenRequest{}); return err },
want: nil,
},
{
name: "reopen change fires update",
fake: &fakeIssueOperations{changed: true},
call: func(ops issueops.Lifecycle) error { _, err := ops.Reopen(ctx, issueops.ReopenRequest{}); return err },
want: []string{"update"},
},
{
name: "reopen error fires nothing",
fake: &fakeIssueOperations{changed: true, err: errors.New("underlying")},
call: func(ops issueops.Lifecycle) error { _, err := ops.Reopen(ctx, issueops.ReopenRequest{}); return err },
wantErr: true,
want: nil,
},
{
// Update fires on every success, no-op included, mirroring
// HookFiringStore.UpdateIssueChecked (internal/storage/hook_decorator.go).
// Do not "unify" this with reopen's gating.
name: "update no-op still fires update",
fake: &fakeIssueOperations{changed: false},
call: func(ops issueops.Lifecycle) error { _, err := ops.Update(ctx, issueops.UpdateRequest{}); return err },
want: []string{"update"},
},
{
// Close fires on every success, including the idempotent re-close,
// mirroring HookFiringStore.CloseIssueChecked
// (internal/storage/hook_decorator.go). Do not "unify" this either.
name: "close no-op still fires close",
fake: &fakeIssueOperations{changed: false},
call: func(ops issueops.Lifecycle) error { _, err := ops.Close(ctx, issueops.CloseRequest{}); return err },
want: []string{"close"},
},
} {
t.Run(test.name, func(t *testing.T) {
recorder := &recordingIssueOperationHooks{}
err := test.call(&hookIssueOperations{inner: test.fake, hooks: recorder})
if (err != nil) != test.wantErr {
t.Fatalf("call error = %v, wantErr = %v", err, test.wantErr)
}
if !reflect.DeepEqual(recorder.completions, test.want) {
t.Fatalf("completion hooks = %#v, want %#v", recorder.completions, test.want)
}
})
}
}

View file

@ -0,0 +1,37 @@
package storage
import (
"encoding/json"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// CreatePublicCreateDependencies returns the dependency snapshot described by
// a public create request after its issue ID is known.
//
// It is derived from the request rather than from the created issue because a
// reverse edge is not an outgoing edge of the new issue: it belongs to the
// target, whose own hooks still need to see it.
func CreatePublicCreateDependencies(issueID string, request issueops.CreateRequest) []*types.Dependency {
dependencies := make([]*types.Dependency, 0, len(request.Dependencies)+2)
if request.ParentID != "" {
dependencies = append(dependencies, &types.Dependency{IssueID: issueID, DependsOnID: request.ParentID, Type: types.DepParentChild})
}
if request.WaitsFor != nil {
gate := request.WaitsFor.Gate
if gate == "" {
gate = types.WaitsForAllChildren
}
metadata, _ := json.Marshal(types.WaitsForMeta{Gate: gate})
dependencies = append(dependencies, &types.Dependency{IssueID: issueID, DependsOnID: request.WaitsFor.SpawnerID, Type: types.DepWaitsFor, Metadata: string(metadata)})
}
for _, dependency := range request.Dependencies {
source, target := issueID, dependency.TargetID
if dependency.Reverse {
source, target = target, issueID
}
dependencies = append(dependencies, &types.Dependency{IssueID: source, DependsOnID: target, Type: dependency.Type, Metadata: dependency.Metadata, ThreadID: dependency.ThreadID})
}
return dependencies
}

View file

@ -0,0 +1,375 @@
package issueops
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"sort"
"strings"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// ChangedTables records durable tables changed by one guarded operation.
type ChangedTables map[string]bool
// Add records table names, ignoring empty names and wisp-only tables.
func (tables ChangedTables) Add(names ...string) {
for _, name := range names {
if name != "" && name != "wisps" && !strings.HasPrefix(name, "wisp_") {
tables[name] = true
}
}
}
// Merge records every table in other.
func (tables ChangedTables) Merge(other map[string]bool) {
for table := range other {
tables.Add(table)
}
}
// UpdateFields converts the public scalar patch fields to storage updates.
func UpdateFields(patch publicops.IssuePatch) map[string]interface{} {
updates := map[string]interface{}{}
for _, field := range []struct {
set bool
key string
val interface{}
}{
{patch.Title.Set, "title", patch.Title.Value},
{patch.Description.Set, "description", patch.Description.Value},
{patch.Design.Set, "design", patch.Design.Value},
{patch.AcceptanceCriteria.Set, "acceptance_criteria", patch.AcceptanceCriteria.Value},
{patch.Notes.Set, "notes", patch.Notes.Value},
{patch.AppendNotes.Set, "append_notes", patch.AppendNotes.Value},
{patch.SpecID.Set, "spec_id", patch.SpecID.Value},
{patch.AwaitID.Set, "await_id", patch.AwaitID.Value},
{patch.Status.Set, "status", patch.Status.Value},
{patch.Priority.Set, "priority", patch.Priority.Value},
{patch.IssueType.Set, "issue_type", patch.IssueType.Value},
{patch.Assignee.Set, "assignee", patch.Assignee.Value},
{patch.Owner.Set, "owner", patch.Owner.Value},
{patch.ClosedBySession.Set, "closed_by_session", patch.ClosedBySession.Value},
{patch.EstimatedMinutes.Set, "estimated_minutes", patch.EstimatedMinutes.Value},
{patch.ExternalRef.Set, "external_ref", patch.ExternalRef.Value},
{patch.DueAt.Set, "due_at", patch.DueAt.Value},
{patch.DeferUntil.Set, "defer_until", patch.DeferUntil.Value},
} {
if field.set {
updates[field.key] = field.val
}
}
return updates
}
// ValidateUpdateRequest checks mutually exclusive guarded-update options and
// the canonical field values every backend must reject identically. Backends
// call it before touching the row so an invalid patch cannot half-apply.
func ValidateUpdateRequest(request publicops.UpdateRequest) error {
if request.Claim && (request.ExpectedAssignee != nil || request.ExpectedStatus != nil) {
return fmt.Errorf("%w: claim cannot use expected assignee or status", storage.ErrValidation)
}
if request.ForceAssigneeTransfer && (request.Claim || !request.Patch.Assignee.Set || request.ExpectedAssignee != nil) {
return fmt.Errorf("%w: invalid forced assignee transfer", storage.ErrValidation)
}
patch := request.Patch
if patch.Title.Set {
if err := types.ValidateIssueTitle(patch.Title.Value); err != nil {
return fmt.Errorf("%w: update title: %w", storage.ErrValidation, err)
}
}
if patch.Priority.Set {
if err := types.ValidateIssuePriority(patch.Priority.Value); err != nil {
return fmt.Errorf("%w: update priority: %w", storage.ErrValidation, err)
}
}
if patch.EstimatedMinutes.Set {
if err := types.ValidateIssueEstimatedMinutes(patch.EstimatedMinutes.Value); err != nil {
return fmt.Errorf("%w: update estimated_minutes: %w", storage.ErrValidation, err)
}
}
if patch.Persistence.Set && !patch.Persistence.Value.IsValid() {
return fmt.Errorf("%w: invalid persistence mode %q", storage.ErrValidation, patch.Persistence.Value)
}
return nil
}
// ValidateMetadataPatch checks mutually exclusive metadata edits.
func ValidateMetadataPatch(patch publicops.MetadataPatch) error {
if patch.Replace.Set && (patch.Merge.Set || len(patch.Set) > 0 || len(patch.Unset) > 0) {
return fmt.Errorf("%w: cannot combine metadata replacement with incremental metadata edits", storage.ErrValidation)
}
return nil
}
// ValidateScalarUpdates checks typed scalar values before they reach SQL.
func ValidateScalarUpdates(ctx context.Context, tx DBTX, updates map[string]interface{}) error {
if rawType, ok := updates["issue_type"]; ok {
var issueType types.IssueType
switch value := rawType.(type) {
case types.IssueType:
issueType = value
case string:
issueType = types.IssueType(value)
default:
return fmt.Errorf("%w: invalid issue type %v", storage.ErrValidation, rawType)
}
customTypes, err := ResolveCustomTypesInTx(ctx, tx)
if err != nil {
return fmt.Errorf("resolve custom issue types: %w", err)
}
if !issueType.IsValidWithCustom(customTypes) {
return fmt.Errorf("%w: invalid issue type %s", storage.ErrValidation, issueType)
}
}
for _, field := range []string{"assignee", "owner"} {
if raw, ok := updates[field]; ok {
if value, ok := raw.(string); ok {
if err := types.CheckFieldLen(field, value); err != nil {
return err
}
}
}
}
return nil
}
// AuthorizeAssigneeTransfer protects an active assignment from unguarded transfer.
func AuthorizeAssigneeTransfer(ctx context.Context, tx DBTX, before *types.Issue, request publicops.UpdateRequest) error {
if !request.Patch.Assignee.Set || request.Patch.Assignee.Value == before.Assignee || request.ExpectedAssignee != nil || request.ForceAssigneeTransfer || before.Status != types.StatusInProgress || before.Assignee == "" || before.Assignee == request.Actor {
return nil
}
pools, err := ClaimPoolAliasesInTx(ctx, tx)
if err != nil {
return err
}
for _, pool := range pools {
if pool == before.Assignee {
return nil
}
}
return fmt.Errorf("%w: issue %s is assigned to %q", storage.ErrAlreadyClaimed, before.ID, before.Assignee)
}
// ApplyMetadataPatch returns the canonical metadata value and whether it changes.
func ApplyMetadataPatch(current json.RawMessage, patch publicops.MetadataPatch) (json.RawMessage, bool, error) {
if !patch.Replace.Set && !patch.Merge.Set && len(patch.Set) == 0 && len(patch.Unset) == 0 {
return current, false, nil
}
setKeys := make([]string, 0, len(patch.Set))
for key := range patch.Set {
setKeys = append(setKeys, key)
}
sort.Strings(setKeys)
for _, key := range setKeys {
if err := storage.ValidateMetadataKey(key); err != nil {
return nil, false, fmt.Errorf("%w: %w", storage.ErrValidation, err)
}
}
for _, key := range patch.Unset {
if err := storage.ValidateMetadataKey(key); err != nil {
return nil, false, fmt.Errorf("%w: %w", storage.ErrValidation, err)
}
}
var next json.RawMessage
if patch.Replace.Set {
next = append(json.RawMessage(nil), patch.Replace.Value...)
if len(next) == 0 {
next = json.RawMessage(`{}`)
}
if !json.Valid(next) {
return nil, false, fmt.Errorf("%w: metadata replacement is not valid JSON", storage.ErrValidation)
}
} else {
next = append(json.RawMessage(nil), current...)
if patch.Merge.Set {
// A JSON null unmarshals into a nil overlay map, so the merge
// below would silently accept it as "change nothing".
if strings.TrimSpace(string(patch.Merge.Value)) == "null" {
return nil, false, fmt.Errorf("%w: metadata merge must be a JSON object", storage.ErrValidation)
}
merged, err := storage.MergeMetadataJSON(next, patch.Merge.Value)
if err != nil {
return nil, false, fmt.Errorf("%w: metadata merge: %v", storage.ErrValidation, err)
}
next = merged
}
if len(patch.Set) > 0 || len(patch.Unset) > 0 {
values := make(map[string]json.RawMessage)
if len(next) > 0 && string(next) != "null" {
if err := json.Unmarshal(next, &values); err != nil {
return nil, false, fmt.Errorf("%w: metadata edits require an object: %v", storage.ErrValidation, err)
}
}
for _, key := range setKeys {
value := patch.Set[key]
if !json.Valid(value) {
return nil, false, fmt.Errorf("%w: metadata value for key %q is not valid JSON", storage.ErrValidation, key)
}
values[key] = append(json.RawMessage(nil), value...)
}
for _, key := range patch.Unset {
delete(values, key)
}
encoded, err := json.Marshal(values)
if err != nil {
return nil, false, fmt.Errorf("%w: encode metadata edits: %v", storage.ErrValidation, err)
}
next = encoded
}
}
if err := ValidateMetadataIfConfigured(next); err != nil {
return nil, false, err
}
changed, err := metadataChanged(current, next)
if err != nil {
return nil, false, fmt.Errorf("%w: compare metadata: %v", storage.ErrValidation, err)
}
return next, changed, nil
}
func metadataChanged(current, next json.RawMessage) (bool, error) {
canonical := func(raw json.RawMessage) (string, error) {
if len(raw) == 0 || string(raw) == "null" {
return "{}", nil
}
var value any
if err := json.Unmarshal(raw, &value); err != nil {
return "", err
}
encoded, err := json.Marshal(value)
return string(encoded), err
}
left, err := canonical(current)
if err != nil {
return false, err
}
right, err := canonical(next)
if err != nil {
return false, err
}
return left != right, nil
}
// ApplyLabelPatch applies ordered label edits and reports whether rows changed.
func ApplyLabelPatch(ctx context.Context, tx DBTX, current *types.Issue, patch publicops.LabelPatch, actor string) (bool, error) {
if !patch.Replace.Set && len(patch.Add) == 0 && len(patch.Remove) == 0 {
return false, nil
}
existing := stringSet(current.Labels)
target := make(map[string]struct{}, len(existing)+len(patch.Add))
if !patch.Replace.Set {
for label := range existing {
target[label] = struct{}{}
}
}
for _, label := range patch.Replace.Value {
target[label] = struct{}{}
}
for _, label := range patch.Add {
target[label] = struct{}{}
}
for _, label := range patch.Remove {
delete(target, label)
}
if sameStringSet(existing, target) {
return false, nil
}
sqlTx, ok := tx.(*sql.Tx)
if !ok {
return false, fmt.Errorf("apply labels: transaction must be *sql.Tx")
}
for _, label := range stringSetDifference(existing, target) {
if err := RemoveLabelInTx(ctx, sqlTx, "", "", current.ID, label, actor); err != nil {
return false, err
}
}
for _, label := range stringSetDifference(target, existing) {
if err := AddLabelInTx(ctx, sqlTx, "", "", current.ID, label, actor); err != nil {
return false, err
}
}
return true, nil
}
// ParentPatchResult reports the concrete changes made by ApplyParentPatch.
type ParentPatchResult struct {
Changed bool
IssueRowsChanged bool
WispRowsChanged bool
}
// ApplyParentPatch replaces the parent-child targets and reports concrete changes.
func ApplyParentPatch(ctx context.Context, tx DBTX, current *types.Issue, parent publicops.Field[string], actor string) (ParentPatchResult, error) {
if !parent.Set {
return ParentPatchResult{}, nil
}
dependencies, err := GetDependencyRecordsForIssuesInTx(ctx, tx, []string{current.ID})
if err != nil {
return ParentPatchResult{}, err
}
existing := map[string]struct{}{}
for _, dependency := range dependencies[current.ID] {
if dependency.Type == types.DepParentChild {
existing[dependency.DependsOnID] = struct{}{}
}
}
target := map[string]struct{}{}
if parent.Value != "" {
target[parent.Value] = struct{}{}
}
if sameStringSet(existing, target) {
return ParentPatchResult{}, nil
}
sqlTx, ok := tx.(*sql.Tx)
if !ok {
return ParentPatchResult{}, fmt.Errorf("apply parent: transaction must be *sql.Tx")
}
var recomputed RecomputeIsBlockedResult
for _, parentID := range stringSetDifference(existing, target) {
if _, err := removeDependencyInTx(ctx, sqlTx, current.ID, parentID, actor, false, &recomputed); err != nil {
return ParentPatchResult{}, err
}
}
for _, parentID := range stringSetDifference(target, existing) {
if _, err := addDependencyInTx(ctx, sqlTx, &types.Dependency{IssueID: current.ID, DependsOnID: parentID, Type: types.DepParentChild}, actor, AddDependencyOpts{}, &recomputed); err != nil {
return ParentPatchResult{}, err
}
}
return ParentPatchResult{Changed: true, IssueRowsChanged: recomputed.IssueRowsChanged, WispRowsChanged: recomputed.WispRowsChanged}, nil
}
func stringSet(values []string) map[string]struct{} {
set := make(map[string]struct{}, len(values))
for _, value := range values {
set[value] = struct{}{}
}
return set
}
func sameStringSet(left, right map[string]struct{}) bool {
if len(left) != len(right) {
return false
}
for value := range left {
if _, ok := right[value]; !ok {
return false
}
}
return true
}
func stringSetDifference(left, right map[string]struct{}) []string {
values := make([]string, 0)
for value := range left {
if _, ok := right[value]; !ok {
values = append(values, value)
}
}
sort.Strings(values)
return values
}

View file

@ -93,27 +93,48 @@ const waitsForGateBlockedSQL = `
)
`
// RecomputeIsBlockedResult reports which issue tables had rows changed while
// the blocked-state fixpoint converged.
type RecomputeIsBlockedResult struct {
IssueRowsChanged bool
WispRowsChanged bool
}
// RecomputeIsBlockedInTx recomputes blocked state and discards the per-table
// change result retained by RecomputeIsBlockedInTxWithResult.
func RecomputeIsBlockedInTx(ctx context.Context, tx DBTX, issueIDs, wispIDs []string) error {
_, err := RecomputeIsBlockedInTxWithResult(ctx, tx, issueIDs, wispIDs)
return err
}
// RecomputeIsBlockedInTxWithResult recomputes blocked state to a fixpoint and
// reports whether an UPDATE changed rows in each issue table.
func RecomputeIsBlockedInTxWithResult(
ctx context.Context, tx DBTX, issueIDs, wispIDs []string,
) (RecomputeIsBlockedResult, error) {
var result RecomputeIsBlockedResult
if len(issueIDs) == 0 && len(wispIDs) == 0 {
return nil
return result, nil
}
for {
var changed int64
n, err := recomputeIsBlockedPassForIssuesInTx(ctx, tx, issueIDs)
if err != nil {
return err
return result, err
}
changed += n
result.IssueRowsChanged = result.IssueRowsChanged || n > 0
n, err = recomputeIsBlockedPassForWispsInTx(ctx, tx, wispIDs)
if err != nil {
return err
return result, err
}
changed += n
result.WispRowsChanged = result.WispRowsChanged || n > 0
if changed == 0 {
return nil
return result, nil
}
}
}
@ -384,14 +405,20 @@ func runMarkUnmarkBatchedInTx(ctx context.Context, tx DBTX, markTmpl, unmarkTmpl
if err != nil {
return changed, fmt.Errorf("recompute is_blocked (mark): %w", err)
}
n, _ := res.RowsAffected()
n, err := res.RowsAffected()
if err != nil {
return changed, fmt.Errorf("recompute is_blocked (mark rows affected): %w", err)
}
changed += n
res, err = tx.ExecContext(ctx, fmt.Sprintf(unmarkTmpl, placeholders), args...)
if err != nil {
return changed, fmt.Errorf("recompute is_blocked (unmark): %w", err)
}
n, _ = res.RowsAffected()
n, err = res.RowsAffected()
if err != nil {
return changed, fmt.Errorf("recompute is_blocked (unmark rows affected): %w", err)
}
changed += n
}
return changed, nil

View file

@ -0,0 +1,104 @@
package issueops
import (
"context"
"database/sql/driver"
"errors"
"regexp"
"testing"
"github.com/DATA-DOG/go-sqlmock"
)
func newBlockedStateResultMock(t *testing.T) (sqlmock.Sqlmock, DBTX) {
t.Helper()
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("sqlmock.New: %v", err)
}
t.Cleanup(func() {
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet sqlmock expectations: %v", err)
}
_ = db.Close()
})
return mock, db
}
func expectBlockedStatePass(mock sqlmock.Sqlmock, table, alias string, mark, unmark driver.Result) {
mock.ExpectExec(regexp.QuoteMeta("UPDATE " + table + " " + alias + " SET " + alias + ".is_blocked = 1")).
WillReturnResult(mark)
mock.ExpectExec(regexp.QuoteMeta("UPDATE " + table + " " + alias + " SET " + alias + ".is_blocked = 0")).
WillReturnResult(unmark)
}
func TestRecomputeIsBlockedInTxWithResult(t *testing.T) {
t.Run("issue rows changed", func(t *testing.T) {
mock, db := newBlockedStateResultMock(t)
expectBlockedStatePass(mock, "issues", "i", sqlmock.NewResult(0, 1), sqlmock.NewResult(0, 0))
expectBlockedStatePass(mock, "issues", "i", sqlmock.NewResult(0, 0), sqlmock.NewResult(0, 0))
result, err := RecomputeIsBlockedInTxWithResult(context.Background(), db, []string{"issue-1"}, nil)
if err != nil {
t.Fatalf("RecomputeIsBlockedInTxWithResult: %v", err)
}
if !result.IssueRowsChanged || result.WispRowsChanged {
t.Fatalf("result = %+v, want issue change only", result)
}
})
t.Run("wisp rows changed", func(t *testing.T) {
mock, db := newBlockedStateResultMock(t)
expectBlockedStatePass(mock, "wisps", "w", sqlmock.NewResult(0, 0), sqlmock.NewResult(0, 1))
expectBlockedStatePass(mock, "wisps", "w", sqlmock.NewResult(0, 0), sqlmock.NewResult(0, 0))
result, err := RecomputeIsBlockedInTxWithResult(context.Background(), db, nil, []string{"wisp-1"})
if err != nil {
t.Fatalf("RecomputeIsBlockedInTxWithResult: %v", err)
}
if result.IssueRowsChanged || !result.WispRowsChanged {
t.Fatalf("result = %+v, want wisp change only", result)
}
})
t.Run("no rows changed", func(t *testing.T) {
mock, db := newBlockedStateResultMock(t)
expectBlockedStatePass(mock, "issues", "i", sqlmock.NewResult(0, 0), sqlmock.NewResult(0, 0))
expectBlockedStatePass(mock, "wisps", "w", sqlmock.NewResult(0, 0), sqlmock.NewResult(0, 0))
result, err := RecomputeIsBlockedInTxWithResult(
context.Background(), db, []string{"issue-1"}, []string{"wisp-1"},
)
if err != nil {
t.Fatalf("RecomputeIsBlockedInTxWithResult: %v", err)
}
if result.IssueRowsChanged || result.WispRowsChanged {
t.Fatalf("result = %+v, want no changes", result)
}
})
}
func TestRunMarkUnmarkBatchedInTxPropagatesRowsAffectedErrors(t *testing.T) {
sentinel := errors.New("rows affected unavailable")
for _, phase := range []string{"mark", "unmark"} {
t.Run(phase, func(t *testing.T) {
mock, db := newBlockedStateResultMock(t)
if phase == "mark" {
mock.ExpectExec(regexp.QuoteMeta("UPDATE issues i SET i.is_blocked = 1")).
WillReturnResult(sqlmock.NewErrorResult(sentinel))
} else {
mock.ExpectExec(regexp.QuoteMeta("UPDATE issues i SET i.is_blocked = 1")).
WillReturnResult(sqlmock.NewResult(0, 0))
mock.ExpectExec(regexp.QuoteMeta("UPDATE issues i SET i.is_blocked = 0")).
WillReturnResult(sqlmock.NewErrorResult(sentinel))
}
_, err := runMarkUnmarkBatchedInTx(
context.Background(), db, markBlockedTemplateForIssues(), unmarkBlockedTemplateForIssues(), []string{"issue-1"},
)
if !errors.Is(err, sentinel) {
t.Fatalf("err = %v, want rows-affected error", err)
}
})
}
}

View file

@ -5,16 +5,26 @@ import (
"database/sql"
"errors"
"fmt"
"strconv"
"sync/atomic"
"time"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
const closeCheckedSavepointPrefix = "issueops_close_checked_"
var closeCheckedSavepointCounter atomic.Uint64
// CloseResult holds the result of a CloseIssueInTx call.
type CloseResult struct {
IsWisp bool
AlreadyClosed bool
OpenChildren int
// IssueRowsChanged reports whether this close changed a durable issues row,
// either directly or while recomputing a dependent's blocked state.
IssueRowsChanged bool
}
// CloseIssueInTx closes an issue within a transaction, setting status to closed
@ -29,6 +39,7 @@ func CloseIssueWithoutEventInTx(ctx context.Context, tx DBTX, id string, reason,
}
// CloseIssueCheckedInTx closes an issue within a transaction, refusing with
// storage.ErrCloseOpenChildren when it has open parent-child dependents and
// storage.ErrCloseBlocked when it has a LIVE direct blocker unless force is set.
// The guard (IsBlockedInTx) and the close (CloseIssueInTx) share the SAME
// transaction, so no blocker can clear between the check and the close.
@ -46,7 +57,7 @@ func CloseIssueWithoutEventInTx(ctx context.Context, tx DBTX, id string, reason,
// precondition: the row's current RowVersion (row_lock) must still equal
// *expectedVersion or the close refuses with storage.ErrVersionMismatch. This
// runs first — before the is_blocked guard and before force short-circuits it —
// so force bypasses only the is_blocked guard, never the version check. Because
// so force bypasses the child and blocker policies, never the version check. Because
// the read shares this transaction, a mismatch returns before any write and the
// transaction rolls back with the issue unchanged (a true compare-and-swap).
// row_lock only tracks lifecycle/ownership writes (status, assignee, started_at),
@ -59,56 +70,212 @@ func CloseIssueCheckedInTx(ctx context.Context, tx DBTX, id, reason, actor, sess
return nil, err
}
}
if !force {
// The blocked guard only has meaning for an open→closed transition. An
// already-closed row is an idempotent no-op (Unchanged=true per the
// Storage.CloseIssueChecked contract), so detect that first. A closed
// row can still carry a stale is_blocked=1 — e.g. after a cross-clone
// Dolt merge, a state the schema explicitly models (GetStatistics
// filters `is_blocked = 1 AND status <> 'closed'`). Guarding such a row
// would refuse the idempotent re-close with ErrCloseBlocked. Only guard
// rows that are not already closed; CloseIssueInTx below is the sole
// detector of the already-closed no-op (and matches the Force path,
// which already reaches Unchanged=true by skipping the guard).
closed, err := isClosedInTx(ctx, tx, id)
// Read the target before policy checks. A closed target can still have open
// children, which refuses without Force just like an open target.
closed, targetColumn, found, err := isClosedInTx(ctx, tx, id)
if err != nil {
return nil, err
}
if !found {
return nil, fmt.Errorf("%w: issue %s", storage.ErrNotFound, id)
}
// domain/db also supplies a *sql.DB Runner, whose independently pooled
// statements cannot retain a savepoint. The shared UOW uses a pinned
// *sql.Conn after START TRANSACTION, while embedded callers use *sql.Tx.
if !closeCheckedSavepointEligible(tx) {
return closeIssueCheckedAfterSavepoint(ctx, tx, id, reason, actor, session, force, closed, targetColumn)
}
savepoint, err := createCloseCheckedSavepoint(ctx, tx)
if err != nil {
return nil, err
}
result, scopedErr := closeIssueCheckedAfterSavepoint(ctx, tx, id, reason, actor, session, force, closed, targetColumn)
if scopedErr != nil {
if cleanupErr := rollbackAndReleaseCloseCheckedSavepoint(ctx, tx, savepoint); cleanupErr != nil {
return nil, fmt.Errorf("discard checked close savepoint after %v: %w", scopedErr, cleanupErr)
}
return nil, scopedErr
}
if err := releaseCloseCheckedSavepoint(ctx, tx, savepoint); err != nil {
if rollbackErr := rollbackToCloseCheckedSavepoint(ctx, tx, savepoint); rollbackErr != nil {
return nil, fmt.Errorf("release checked close savepoint: %v; rollback to savepoint: %w", err, rollbackErr)
}
return nil, err
}
return result, nil
}
func closeCheckedSavepointEligible(tx DBTX) bool {
switch tx.(type) {
case *sql.Tx, *sql.Conn:
return true
default:
return false
}
}
func closeIssueCheckedAfterSavepoint(ctx context.Context, tx DBTX, id, reason, actor, session string, force, closed bool, targetColumn string) (*CloseResult, error) {
// This write precedes every child-count policy branch, including Force and
// idempotent closes. A concurrent new parent-child edge writes its own tier
// cell, while a close writes both tiers, so Dolt cannot merge a stale count
// with a new edge.
if err := touchDependencyCoordinationInTx(ctx, tx, id); err != nil {
return nil, err
}
openChildren, err := countOpenChildrenForTargetInTx(ctx, tx, id, targetColumn)
if err != nil {
return nil, err
}
if !force && openChildren > 0 {
return nil, &storage.CloseOpenChildrenError{IssueID: id, OpenChildren: openChildren}
}
if !force && !closed {
blocked, blockers, err := IsBlockedInTx(ctx, tx, id)
if err != nil {
return nil, err
}
if !closed {
blocked, blockers, err := IsBlockedInTx(ctx, tx, id)
if err != nil {
return nil, err
}
if blocked && len(blockers) > 0 {
return nil, fmt.Errorf("%w: %s is blocked by %v", storage.ErrCloseBlocked, id, blockers)
}
if blocked && len(blockers) > 0 {
return nil, fmt.Errorf("%w: %s is blocked by %v", storage.ErrCloseBlocked, id, blockers)
}
}
return CloseIssueInTx(ctx, tx, id, reason, actor, session)
result, err := CloseIssueInTx(ctx, tx, id, reason, actor, session)
if err != nil {
return nil, err
}
result.OpenChildren = openChildren
return result, nil
}
// isClosedInTx reports whether the issue (or wisp) identified by id is already
// in the closed status. It probes the issues table then the optional wisps
// table, mirroring IsBlockedInTx's table order. A missing row reports false so
// the caller falls through to CloseIssueInTx, which returns ErrNotFound.
func countOpenChildrenInTx(ctx context.Context, tx DBTX, id string) (int, error) {
targetColumn, err := dependencyTargetColumnForIDInTx(ctx, tx, id)
if err != nil {
return 0, err
}
return countOpenChildrenForTargetInTx(ctx, tx, id, targetColumn)
}
func countOpenChildrenForTargetInTx(ctx context.Context, tx DBTX, id, targetColumn string) (int, error) {
if targetColumn != "depends_on_issue_id" && targetColumn != "depends_on_wisp_id" {
return 0, fmt.Errorf("count open children: unsupported target column %q", targetColumn)
}
var durableCount int
//nolint:gosec // G201: targetColumn is validated above against two hardcoded identifiers.
durableQuery := fmt.Sprintf(`
SELECT COUNT(DISTINCT dependency.issue_id)
FROM dependencies AS dependency
JOIN issues AS child ON child.id = dependency.issue_id
WHERE dependency.%s = ?
AND dependency.type = 'parent-child'
AND child.status != 'closed'
`, targetColumn)
if err := tx.QueryRowContext(ctx, durableQuery, id).Scan(&durableCount); err != nil {
return 0, fmt.Errorf("count open durable children for %s: %w", id, err)
}
var wispCount int
//nolint:gosec // G201: targetColumn is validated above against two hardcoded identifiers.
wispQuery := fmt.Sprintf(`
SELECT COUNT(DISTINCT dependency.issue_id)
FROM wisp_dependencies AS dependency
JOIN wisps AS child ON child.id = dependency.issue_id
WHERE dependency.%s = ?
AND dependency.type = 'parent-child'
AND child.status != 'closed'
AND NOT EXISTS (
SELECT 1 FROM dependencies AS durable WHERE durable.id = dependency.id
)
`, targetColumn)
if err := tx.QueryRowContext(ctx, wispQuery, id).Scan(&wispCount); err != nil {
if optionalBlockedTable("wisp_dependencies") && isTableNotExistError(err) {
return durableCount, nil
}
return 0, fmt.Errorf("count open wisp children for %s: %w", id, err)
}
return durableCount + wispCount, nil
}
func createCloseCheckedSavepoint(ctx context.Context, tx DBTX) (string, error) {
name := closeCheckedSavepointPrefix + strconv.FormatUint(closeCheckedSavepointCounter.Add(1), 10)
//nolint:gosec // G201: name is a fixed identifier-safe prefix plus an atomic decimal counter.
if _, err := tx.ExecContext(ctx, "SAVEPOINT "+name); err != nil {
return "", fmt.Errorf("create checked close savepoint: %w", err)
}
return name, nil
}
func rollbackAndReleaseCloseCheckedSavepoint(ctx context.Context, tx DBTX, name string) error {
rollbackErr := rollbackToCloseCheckedSavepoint(ctx, tx, name)
releaseErr := releaseCloseCheckedSavepoint(ctx, tx, name)
return errors.Join(rollbackErr, releaseErr)
}
func rollbackToCloseCheckedSavepoint(ctx context.Context, tx DBTX, name string) error {
//nolint:gosec // G201: name is generated by createCloseCheckedSavepoint.
if _, err := tx.ExecContext(ctx, "ROLLBACK TO SAVEPOINT "+name); err != nil {
return fmt.Errorf("rollback checked close savepoint: %w", err)
}
return nil
}
func releaseCloseCheckedSavepoint(ctx context.Context, tx DBTX, name string) error {
//nolint:gosec // G201: name is generated by createCloseCheckedSavepoint.
if _, err := tx.ExecContext(ctx, "RELEASE SAVEPOINT "+name); err != nil {
return fmt.Errorf("release checked close savepoint: %w", err)
}
return nil
}
// dependencyTargetColumnForIDInTx returns the typed target column for id,
// preferring a durable row when an id is present in both tables.
func dependencyTargetColumnForIDInTx(ctx context.Context, tx DBTX, id string) (string, error) {
var found int
err := tx.QueryRowContext(ctx, "SELECT 1 FROM issues WHERE id = ?", id).Scan(&found)
if err == nil {
return "depends_on_issue_id", nil
}
if !errors.Is(err, sql.ErrNoRows) {
return "", fmt.Errorf("classify child-count target in issues: %w", err)
}
err = tx.QueryRowContext(ctx, "SELECT 1 FROM wisps WHERE id = ?", id).Scan(&found)
if err == nil {
return "depends_on_wisp_id", nil
}
if optionalBlockedTable("wisps") && isTableNotExistError(err) {
return "depends_on_issue_id", nil
}
if !errors.Is(err, sql.ErrNoRows) {
return "", fmt.Errorf("classify child-count target in wisps: %w", err)
}
return "depends_on_issue_id", nil
}
// isClosedInTx reports whether the issue (or wisp) identified by id exists and
// is already closed. It probes the issues table then the optional wisps table,
// mirroring IsBlockedInTx's table order.
//
//nolint:gosec // G201: table is a hardcoded "issues" or "wisps".
func isClosedInTx(ctx context.Context, tx DBTX, id string) (bool, error) {
for _, table := range []string{"issues", "wisps"} {
func isClosedInTx(ctx context.Context, tx DBTX, id string) (closed bool, targetColumn string, found bool, err error) {
for _, target := range []struct {
table string
column string
}{
{table: "issues", column: "depends_on_issue_id"},
{table: "wisps", column: "depends_on_wisp_id"},
} {
var status string
err := tx.QueryRowContext(ctx, "SELECT status FROM "+table+" WHERE id = ?", id).Scan(&status)
err := tx.QueryRowContext(ctx, "SELECT status FROM "+target.table+" WHERE id = ?", id).Scan(&status)
if err == nil {
return types.Status(status) == types.StatusClosed, nil
return types.Status(status) == types.StatusClosed, target.column, true, nil
}
if errors.Is(err, sql.ErrNoRows) {
continue
}
if optionalBlockedTable(table) && isTableNotExistError(err) {
if optionalBlockedTable(target.table) && isTableNotExistError(err) {
continue
}
return false, fmt.Errorf("read status from %s: %w", table, err)
return false, "", false, fmt.Errorf("read status from %s: %w", target.table, err)
}
return false, nil
return false, "", false, nil
}
//nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants)
@ -174,9 +341,10 @@ func closeIssueInTx(ctx context.Context, tx DBTX, id string, reason, actor, sess
}
}
if err := RecomputeIsBlockedInTx(ctx, tx, affectedIssues, affectedWisps); err != nil {
recompute, err := RecomputeIsBlockedInTxWithResult(ctx, tx, affectedIssues, affectedWisps)
if err != nil {
return nil, fmt.Errorf("recompute is_blocked after close for %s: %w", id, err)
}
return &CloseResult{IsWisp: isWisp}, nil
return &CloseResult{IsWisp: isWisp, IssueRowsChanged: !isWisp || recompute.IssueRowsChanged}, nil
}

View file

@ -0,0 +1,45 @@
package issueops
import (
"context"
"testing"
"github.com/DATA-DOG/go-sqlmock"
)
// TestCountOpenChildrenInTxUsesTargetedOpenEdges keeps the close guard from
// regressing to a dependent-record scan followed by full issue hydration. The
// count needs only two indexed aggregates: permanent children and wisp children
// whose natural edge is not already durable.
func TestCountOpenChildrenInTxUsesTargetedOpenEdges(t *testing.T) {
t.Parallel()
_, mock, tx := beginMockTx(t)
const parent = "close-count-parent"
// Route the target durable-first, then use direct typed-target predicates
// (not COALESCE), literal closed filtering, and a durable-id anti-join for
// the wisp aggregate. The regexes intentionally leave SQL layout free.
mock.ExpectQuery(`SELECT 1 FROM issues WHERE id = \?`).
WithArgs(parent).
WillReturnRows(sqlmock.NewRows([]string{"1"}).AddRow(1))
durableQuery := `(?s)SELECT\s+COUNT\(DISTINCT\s+dependency\.issue_id\).*FROM\s+dependencies.*JOIN\s+issues.*depends_on_issue_id\s*=\s*\?.*type\s*=\s*'parent-child'.*status\s*!=\s*'closed'`
wispQuery := `(?s)SELECT\s+COUNT\(DISTINCT\s+dependency\.issue_id\).*FROM\s+wisp_dependencies.*JOIN\s+wisps.*depends_on_issue_id\s*=\s*\?.*type\s*=\s*'parent-child'.*status\s*!=\s*'closed'.*NOT EXISTS.*FROM\s+dependencies.*durable\.id\s*=\s*dependency\.id`
mock.ExpectQuery(durableQuery).
WithArgs(parent).
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1))
mock.ExpectQuery(wispQuery).
WithArgs(parent).
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1))
got, err := countOpenChildrenInTx(context.Background(), tx, parent)
if err != nil {
t.Fatalf("countOpenChildrenInTx: %v", err)
}
if got != 2 {
t.Fatalf("open child count = %d, want 2 (one durable + one wisp parent-child edge)", got)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet targeted-count SQL expectations: %v", err)
}
}

View file

@ -15,7 +15,7 @@ import (
// transaction. Automatically routes to wisp_comments if the ID is an active wisp.
//
//nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants)
func GetIssueCommentsInTx(ctx context.Context, tx *sql.Tx, issueID string) ([]*types.Comment, error) {
func GetIssueCommentsInTx(ctx context.Context, tx DBTX, issueID string) ([]*types.Comment, error) {
table := "comments"
if IsActiveWispInTx(ctx, tx, issueID) {
table = "wisp_comments"

View file

@ -177,13 +177,17 @@ func getConfigKeysInTx(ctx context.Context, tx DBTX, keys ...string) (map[string
func ResolveCustomStatusesDetailedInTx(ctx context.Context, tx DBTX) ([]types.CustomStatus, error) {
// Try the normalized table first
rows, err := tx.QueryContext(ctx, "SELECT name, category FROM custom_statuses ORDER BY name")
if err == nil {
if err != nil {
if !isTableNotExistError(err) {
return nil, fmt.Errorf("query custom_statuses: %w", err)
}
} else {
defer rows.Close()
var result []types.CustomStatus
for rows.Next() {
var name, category string
if err := rows.Scan(&name, &category); err != nil {
continue
return nil, fmt.Errorf("scan custom_statuses: %w", err)
}
result = append(result, types.CustomStatus{
Name: name,
@ -225,6 +229,26 @@ func ResolveCustomStatusesDetailedInTx(ctx context.Context, tx DBTX) ([]types.Cu
return nil, nil
}
// ReopenCategoryInTx resolves the reopen category for status from the same
// transaction that will perform the state change. Unknown and malformed custom
// statuses are treated as unspecified so callers leave them unchanged.
func ReopenCategoryInTx(ctx context.Context, tx DBTX, status types.Status) (types.StatusCategory, error) {
if status.IsValid() {
return types.BuiltInStatusCategory(status), nil
}
statuses, err := ResolveCustomStatusesDetailedInTx(ctx, tx)
if err != nil {
return types.CategoryUnspecified, fmt.Errorf("resolve custom statuses: %w", err)
}
for _, custom := range statuses {
if custom.Name == string(status) {
return custom.Category, nil
}
}
return types.CategoryUnspecified, nil
}
// ResolveCustomTypesInTx reads custom issue types from the custom_types table,
// falling back to config string when the table is empty or pre-migration,
// and always overlay-unions project-extension types from .beads/config.yaml on

View file

@ -1,11 +1,160 @@
package issueops
import (
"context"
"errors"
"regexp"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/steveyegge/beads/internal/types"
)
func TestReopenCategoryInTx(t *testing.T) {
t.Run("literal closed is done without configuration", func(t *testing.T) {
category, err := ReopenCategoryInTx(context.Background(), nil, types.StatusClosed)
if err != nil {
t.Fatalf("ReopenCategoryInTx: %v", err)
}
if category != types.CategoryDone {
t.Fatalf("category = %q, want %q", category, types.CategoryDone)
}
})
t.Run("normalized custom done status", func(t *testing.T) {
db, mock, tx := beginMockTx(t)
defer db.Close()
mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")).
WillReturnRows(sqlmock.NewRows([]string{"name", "category"}).
AddRow("archived", string(types.CategoryDone)))
mock.ExpectRollback()
category, err := ReopenCategoryInTx(context.Background(), tx, "archived")
if err != nil {
t.Fatalf("ReopenCategoryInTx: %v", err)
}
if category != types.CategoryDone {
t.Fatalf("category = %q, want %q", category, types.CategoryDone)
}
if err := tx.Rollback(); err != nil {
t.Fatalf("rollback: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet SQL expectations: %v", err)
}
})
t.Run("legacy config fallback", func(t *testing.T) {
db, mock, tx := beginMockTx(t)
defer db.Close()
mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")).
WillReturnError(errors.New("Error 1146 (42S02): Table 'beads.custom_statuses' doesn't exist"))
mock.ExpectQuery(regexp.QuoteMeta("SELECT value FROM config WHERE `key` = ?")).
WithArgs("status.custom").
WillReturnRows(sqlmock.NewRows([]string{"value"}).AddRow("archived:done"))
mock.ExpectRollback()
category, err := ReopenCategoryInTx(context.Background(), tx, "archived")
if err != nil {
t.Fatalf("ReopenCategoryInTx: %v", err)
}
if category != types.CategoryDone {
t.Fatalf("category = %q, want %q", category, types.CategoryDone)
}
if err := tx.Rollback(); err != nil {
t.Fatalf("rollback: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet SQL expectations: %v", err)
}
})
t.Run("normalized query failure does not fall back to legacy config", func(t *testing.T) {
db, mock, tx := beginMockTx(t)
defer db.Close()
mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")).
WillReturnError(errors.New("connection reset"))
mock.ExpectRollback()
_, err := ReopenCategoryInTx(context.Background(), tx, "archived")
if err == nil || !regexp.MustCompile("connection reset").MatchString(err.Error()) {
t.Fatalf("err = %v, want normalized query failure", err)
}
if err := tx.Rollback(); err != nil {
t.Fatalf("rollback: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet SQL expectations: %v", err)
}
})
t.Run("normalized row scan failure does not fall back to legacy config", func(t *testing.T) {
db, mock, tx := beginMockTx(t)
defer db.Close()
mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")).
WillReturnRows(sqlmock.NewRows([]string{"name", "category"}).AddRow("archived", nil))
mock.ExpectRollback()
_, err := ReopenCategoryInTx(context.Background(), tx, "archived")
if err == nil || !regexp.MustCompile("scan custom_statuses").MatchString(err.Error()) {
t.Fatalf("err = %v, want normalized scan failure", err)
}
if err := tx.Rollback(); err != nil {
t.Fatalf("rollback: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet SQL expectations: %v", err)
}
})
t.Run("malformed legacy config is unspecified", func(t *testing.T) {
db, mock, tx := beginMockTx(t)
defer db.Close()
mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")).
WillReturnRows(sqlmock.NewRows([]string{"name", "category"}))
mock.ExpectQuery(regexp.QuoteMeta("SELECT value FROM config WHERE `key` = ?")).
WithArgs("status.custom").
WillReturnRows(sqlmock.NewRows([]string{"value"}).AddRow("archived:not-a-category"))
mock.ExpectRollback()
category, err := ReopenCategoryInTx(context.Background(), tx, "archived")
if err != nil {
t.Fatalf("ReopenCategoryInTx: %v", err)
}
if category != types.CategoryUnspecified {
t.Fatalf("category = %q, want %q", category, types.CategoryUnspecified)
}
if err := tx.Rollback(); err != nil {
t.Fatalf("rollback: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet SQL expectations: %v", err)
}
})
t.Run("configuration query failure is returned", func(t *testing.T) {
db, mock, tx := beginMockTx(t)
defer db.Close()
mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")).
WillReturnRows(sqlmock.NewRows([]string{"name", "category"}))
mock.ExpectQuery(regexp.QuoteMeta("SELECT value FROM config WHERE `key` = ?")).
WithArgs("status.custom").
WillReturnError(errors.New("configuration unavailable"))
mock.ExpectRollback()
_, err := ReopenCategoryInTx(context.Background(), tx, "archived")
if err == nil || !regexp.MustCompile("configuration unavailable").MatchString(err.Error()) {
t.Fatalf("err = %v, want configuration query failure", err)
}
if err := tx.Rollback(); err != nil {
t.Fatalf("rollback: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet SQL expectations: %v", err)
}
})
}
func TestParseStatusFallback(t *testing.T) {
tests := []struct {
name string

View file

@ -3,10 +3,13 @@ package issueops
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
gmssql "github.com/dolthub/go-mysql-server/sql"
"github.com/go-sql-driver/mysql"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/depid"
"github.com/steveyegge/beads/internal/types"
@ -58,7 +61,15 @@ type CreateIssueResult struct {
// StaleRejected reports that the RejectStaleUpserts guard kept the stored
// row: nothing was written, and the issue's aux data must not be
// persisted by later batch stages either (bd-578h9.8).
StaleRejected bool
StaleRejected bool
persistedDependencies []persistedDependency
}
type persistedDependency struct {
source string
target string
depType types.DependencyType
sourceWisp bool
}
func (r *CreateIssueResult) markChanged(table string) {
@ -89,23 +100,12 @@ func CreateIssueInTxWithResult(ctx context.Context, tx *sql.Tx, bc *BatchContext
issueTable, eventTable := TableRouting(issue)
if issue.ID == "" {
prefix := bc.ConfigPrefix
if issue.PrefixOverride != "" {
prefix = issue.PrefixOverride
} else if issue.IDPrefix != "" {
prefix = bc.ConfigPrefix + "-" + issue.IDPrefix
} else if IsWisp(issue) {
prefix = bc.ConfigPrefix + "-wisp"
}
var err error
issue.ID, err = GenerateIssueIDInTable(ctx, tx, issueTable, prefix, issue, actor)
if err != nil {
return result, fmt.Errorf("failed to generate issue ID: %w", err)
}
} else if !bc.Opts.SkipPrefixValidation {
if err := ValidateIssueIDPrefix(issue.ID, bc.ConfigPrefix, bc.AllowedPrefixes); err != nil {
return result, fmt.Errorf("prefix validation failed for %s: %w", issue.ID, err)
if err := assignCreateIssueIDInTx(ctx, tx, bc, issue, actor); err != nil {
return result, err
}
if bc.Opts.CreateOnly {
if err := EnsureIssueIDAvailableInTx(ctx, tx, issue.ID); err != nil {
return result, err
}
}
@ -167,6 +167,32 @@ func CreateIssueInTxWithResult(ctx context.Context, tx *sql.Tx, bc *BatchContext
return result, nil
}
func assignCreateIssueIDInTx(ctx context.Context, tx *sql.Tx, bc *BatchContext, issue *types.Issue, actor string) error {
if issue.ID == "" {
issueTable, _ := TableRouting(issue)
prefix := bc.ConfigPrefix
if issue.PrefixOverride != "" {
prefix = issue.PrefixOverride
} else if issue.IDPrefix != "" {
prefix = bc.ConfigPrefix + "-" + issue.IDPrefix
} else if IsWisp(issue) {
prefix = bc.ConfigPrefix + "-wisp"
}
var err error
issue.ID, err = GenerateIssueIDInTable(ctx, tx, issueTable, prefix, issue, actor)
if err != nil {
return fmt.Errorf("failed to generate issue ID: %w", err)
}
return nil
}
if !bc.Opts.SkipPrefixValidation {
if err := ValidateIssueIDPrefix(issue.ID, bc.ConfigPrefix, bc.AllowedPrefixes); err != nil {
return fmt.Errorf("prefix validation failed for %s: %w", issue.ID, err)
}
}
return nil
}
// CreateIssuesResult reports side effects that callers need for selective
// Dolt staging after CreateIssuesInTxWithResult returns.
type CreateIssuesResult struct {
@ -236,14 +262,18 @@ func CreateIssuesInTxWithResult(ctx context.Context, tx *sql.Tx, issues []*types
for table := range changedCounters {
result.markChanged(table)
}
issueIDs, wispIDs := createBlockedRecomputeIDs(issues)
if err := RecomputeIsBlockedInTx(ctx, tx, issueIDs, wispIDs); err != nil {
issueIDs, wispIDs, err := createBlockedRecomputeIDs(ctx, tx, issues, depResult.persistedDependencies)
if err != nil {
return CreateIssuesResult{}, err
}
if len(issueIDs) > 0 {
recomputed, err := RecomputeIsBlockedInTxWithResult(ctx, tx, issueIDs, wispIDs)
if err != nil {
return CreateIssuesResult{}, err
}
if recomputed.IssueRowsChanged {
result.markChanged("issues")
}
if len(wispIDs) > 0 {
if recomputed.WispRowsChanged {
result.markChanged("wisps")
}
return result, nil
@ -386,7 +416,7 @@ func filterCreateIssuesMixedBucketDependencies(issues []*types.Issue, opts stora
return issues, nil
}
func createBlockedRecomputeIDs(issues []*types.Issue) ([]string, []string) {
func createBlockedRecomputeIDs(ctx context.Context, tx *sql.Tx, issues []*types.Issue, dependencies []persistedDependency) ([]string, []string, error) {
issueSeen := make(map[string]bool, len(issues))
wispSeen := make(map[string]bool, len(issues))
issueIDs := make([]string, 0, len(issues))
@ -413,18 +443,26 @@ func createBlockedRecomputeIDs(issues []*types.Issue) ([]string, []string) {
}
isWisp := IsWisp(issue)
add(issue.ID, isWisp)
for _, dep := range issue.Dependencies {
if dep == nil {
continue
}
src := dep.IssueID
if src == "" {
src = issue.ID
}
add(src, isWisp)
}
for _, dependency := range dependencies {
var affectedIssues, affectedWisps []string
var err error
if dependency.sourceWisp {
affectedIssues, affectedWisps, err = AffectedByDepChangeForWispInTx(ctx, tx, dependency.source, dependency.target, dependency.depType)
} else {
affectedIssues, affectedWisps, err = AffectedByDepChangeInTx(ctx, tx, dependency.source, dependency.target, dependency.depType)
}
if err != nil {
return nil, nil, fmt.Errorf("affected by created dependency %s -> %s: %w", dependency.source, dependency.target, err)
}
for _, id := range affectedIssues {
add(id, false)
}
for _, id := range affectedWisps {
add(id, true)
}
}
return issueIDs, wispIDs
return issueIDs, wispIDs, nil
}
// PrepareIssueForInsert normalizes timestamps, validates, and computes the content hash.
@ -601,7 +639,7 @@ func checkCrossTableIDCollision(ctx context.Context, tx *sql.Tx, id, issueTable
// additively (bd-hj85c).
//
//nolint:gosec // G201: table is a hardcoded constant
func InsertIssueIfNew(ctx context.Context, tx *sql.Tx, issueTable string, issue *types.Issue, opts storage.BatchCreateOptions) (isNew bool, staleRejected bool, err error) {
func InsertIssueIfNew(ctx context.Context, tx DBTX, issueTable string, issue *types.Issue, opts storage.BatchCreateOptions) (isNew bool, staleRejected bool, err error) {
var existingCount int
if issue.ID != "" {
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE id = ?`, issueTable), issue.ID).Scan(&existingCount); err != nil {
@ -611,6 +649,15 @@ func InsertIssueIfNew(ctx context.Context, tx *sql.Tx, issueTable string, issue
if opts.ConflictSkip && existingCount > 0 {
return false, false, nil // issue already exists — skip, never overwrite
}
if opts.CreateOnly {
if err := insertIssueCreateOnly(ctx, tx, issueTable, issue); err != nil {
if isCreateOnlyDuplicateError(err) {
return false, false, fmt.Errorf("%w: %s", storage.ErrAlreadyExists, issue.ID)
}
return false, false, err
}
return true, false, nil
}
if opts.RejectStaleUpserts && existingCount > 0 {
var storedNewer int
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE id = ? AND updated_at > ?`, issueTable), issue.ID, issue.UpdatedAt).Scan(&storedNewer); err != nil {
@ -628,6 +675,27 @@ func InsertIssueIfNew(ctx context.Context, tx *sql.Tx, issueTable string, issue
return existingCount == 0, false, nil
}
func isCreateOnlyDuplicateError(err error) bool {
var mysqlError *mysql.MySQLError
if errors.As(err, &mysqlError) && mysqlError.Number == 1062 {
return true
}
return gmssql.ErrPrimaryKeyViolation.Is(err) || gmssql.ErrUniqueKeyViolation.Is(err)
}
// InsertIssueStrictInTx inserts one issue without probing either storage plane.
// Callers that move an aggregate use it while the source row necessarily still
// occupies the shared ID, so cross-plane create guards would reject a valid move.
func InsertIssueStrictInTx(ctx context.Context, tx DBTX, table string, issue *types.Issue) error {
if err := insertIssueCreateOnly(ctx, tx, table, issue); err != nil {
if isCreateOnlyDuplicateError(err) {
return fmt.Errorf("%w: %s", storage.ErrAlreadyExists, issue.ID)
}
return err
}
return nil
}
func PersistLabels(ctx context.Context, tx *sql.Tx, issue *types.Issue, actor, eventTable string) (CreateIssueResult, error) {
var result CreateIssueResult
if len(issue.Labels) == 0 {
@ -764,16 +832,16 @@ func PersistDependenciesWithOptionsResult(ctx context.Context, tx *sql.Tx, issue
if len(issue.Dependencies) == 0 {
continue
}
depTable := "dependencies"
if IsWisp(issue) {
depTable = "wisp_dependencies"
}
for _, dep := range issue.Dependencies {
// Default IssueID to the owning issue when not pre-set (e.g.,
// markdown bulk create where the ID is auto-generated).
if dep.IssueID == "" {
dep.IssueID = issue.ID
}
depTable := "dependencies"
if IsActiveWispInTx(ctx, tx, dep.IssueID) {
depTable = "wisp_dependencies"
}
pending = append(pending, pendingDependency{dep: dep, depTable: depTable})
}
}
@ -835,12 +903,16 @@ func PersistDependenciesWithOptionsResult(ctx context.Context, tx *sql.Tx, issue
// merge-safe across clones — two clones importing the same JSONL get the
// same primary key, not two random UUIDs that collide on uk_dep_* (#4259).
createdBy := dependencyCreatedBy(dep, actor)
metadata := dep.Metadata
if metadata == "" {
metadata = "{}"
}
//nolint:gosec // G201: item.depTable is one of two hardcoded constants; target column from DepTargetKind.Column()
sqlResult, err := tx.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO %s (id, issue_id, %s, type, created_by, created_at)
VALUES (?, ?, ?, ?, ?, ?)
INSERT INTO %s (id, issue_id, %s, type, created_by, created_at, metadata, thread_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE type = type
`, item.depTable, kind.Column()), depid.New(dep.IssueID, dep.DependsOnID), dep.IssueID, dep.DependsOnID, dep.Type, createdBy, createdAt)
`, item.depTable, kind.Column()), depid.New(dep.IssueID, dep.DependsOnID), dep.IssueID, dep.DependsOnID, dep.Type, createdBy, createdAt, metadata, dep.ThreadID)
if err != nil {
return result, fmt.Errorf("failed to insert dependency %s -> %s: %w", dep.IssueID, dep.DependsOnID, err)
}
@ -850,6 +922,17 @@ func PersistDependenciesWithOptionsResult(ctx context.Context, tx *sql.Tx, issue
}
if rowsAffected > 0 {
result.markChanged(item.depTable)
result.persistedDependencies = append(result.persistedDependencies, persistedDependency{
source: dep.IssueID,
target: dep.DependsOnID,
depType: dep.Type,
sourceWisp: item.depTable == "wisp_dependencies",
})
if dep.Type == types.DepParentChild {
if err := TouchDependencyCoordinationTableInTx(ctx, tx, dep.DependsOnID, item.depTable); err != nil {
return result, err
}
}
}
}
}

View file

@ -0,0 +1,33 @@
package issueops
import (
"errors"
"fmt"
"testing"
gmssql "github.com/dolthub/go-mysql-server/sql"
"github.com/go-sql-driver/mysql"
)
func TestIsCreateOnlyDuplicateError(t *testing.T) {
for _, err := range []error{
&mysql.MySQLError{Number: 1062, Message: "Duplicate entry"},
fmt.Errorf("wrapped: %w", &mysql.MySQLError{Number: 1062}),
gmssql.ErrPrimaryKeyViolation.New(),
gmssql.ErrUniqueKeyViolation.New(),
} {
if !isCreateOnlyDuplicateError(err) {
t.Fatalf("isCreateOnlyDuplicateError(%v) = false, want true", err)
}
}
}
func TestIsCreateOnlyDuplicateErrorPreservesOtherFailures(t *testing.T) {
err := &mysql.MySQLError{Number: 1045, Message: "access denied"}
if isCreateOnlyDuplicateError(err) {
t.Fatal("isCreateOnlyDuplicateError() = true for non-duplicate MySQL error")
}
if isCreateOnlyDuplicateError(errors.New("duplicate wording only")) {
t.Fatal("isCreateOnlyDuplicateError() = true for untyped error")
}
}

View file

@ -0,0 +1,40 @@
package issueops
import (
"context"
"crypto/sha256"
"fmt"
"strconv"
"github.com/steveyegge/beads/internal/storage"
)
// EnsureIssueIDAvailableInTx serializes same-shard creates and rejects occupied IDs.
func EnsureIssueIDAvailableInTx(ctx context.Context, tx DBTX, id string) error {
if tx == nil {
return fmt.Errorf("ensure issue ID available: transaction is nil")
}
if id == "" {
return fmt.Errorf("ensure issue ID available: ID is empty")
}
key := issueCreateCoordinationKey(id)
if _, err := tx.ExecContext(ctx, "REPLACE INTO local_metadata (`key`, value) VALUES (?, ?)", key, strconv.FormatInt(FreshRowLock(), 10)); err != nil {
return fmt.Errorf("coordinate issue create: %w", err)
}
for _, table := range []string{"issues", "wisps"} {
var count int
if err := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM "+table+" WHERE id = ?", id).Scan(&count); err != nil {
return fmt.Errorf("check %s for issue %q: %w", table, id, err)
}
if count > 0 {
return fmt.Errorf("%w: %s", storage.ErrAlreadyExists, id)
}
}
return nil
}
func issueCreateCoordinationKey(id string) string {
sum := sha256.Sum256([]byte(id))
shard := uint16(sum[0])<<4 | uint16(sum[1])>>4
return fmt.Sprintf("issue-create/v1/%03x", shard)
}

View file

@ -0,0 +1,12 @@
package issueops
import (
"context"
"testing"
)
func TestEnsureIssueIDAvailableInTxRejectsEmptyID(t *testing.T) {
if err := EnsureIssueIDAvailableInTx(context.Background(), nil, ""); err == nil {
t.Fatal("EnsureIssueIDAvailableInTx() error = nil, want error")
}
}

Some files were not shown because too many files have changed in this diff Show more