beads/errors_test.go
Julian Knutsen f9b20203e8
feat(close): CloseIssueChecked — atomic guarded close in the engine (#4893)
* feat(close): CloseIssueChecked — atomic guarded close in the engine

`bd close` reads blockers (store.IsBlocked) and then closes in a SEPARATE
transaction — a TOCTOU where a blocker can clear (or the bead can be closed)
between the check and the close. Add CloseIssueChecked, which runs the
is_blocked guard AND the close inside ONE transaction, so the guard is atomic.
A Force option bypasses it (mirrors `bd close --force`). This lets the `bd`
CLI delegate its close guard to the engine instead of hand-rolling the
check-then-close dance.

- storage.ErrCloseBlocked sentinel + re-export beads.ErrCloseBlocked;
  storage.CloseIssueOptions{Reason,Session,Force} and CloseIssueResult{Unchanged}.
- issueops.CloseIssueCheckedInTx: IsBlockedInTx guard (denormalized transitive
  is_blocked — an open blocking dependency or an open blocking gate) then
  CloseIssueInTx, sharing the transaction. Force skips the guard. A blocked
  refusal returns ErrCloseBlocked and rolls back — no close, no closed event.
- Storage-interface method CloseIssueChecked implemented on DoltStore (perm +
  wisp paths, mirroring CloseIssue's DOLT_COMMIT/wisp handling) and forwarded
  on EmbeddedDoltStore, HookFiringStore (fires on_close on success like
  CloseIssue), and InstrumentedStorage.
- Integration tests for the atomic-refuse property on the perm, wisp, and
  embeddeddolt paths (blocked → refused + still open + zero closed events;
  Force → closes; non-blocking dep does not trip; already-closed → Unchanged;
  missing id → ErrNotFound).

Scope is one concern: category-aware reopen and the open-children close guard
are deliberately split into follow-ups. Builds under cgo and CGO_ENABLED=0.

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

* fix(close): short-circuit already-closed before the is_blocked guard

CloseIssueCheckedInTx ran the is_blocked guard before the already-closed
detection, so a row that is already closed but still carries a stale
is_blocked=1 was refused with ErrCloseBlocked instead of the documented
idempotent Unchanged=true. A closed row can carry a stale flag after a
cross-clone Dolt merge — a state the schema explicitly models (GetStatistics
filters `is_blocked = 1 AND status <> 'closed'`) and a hand-resolved merge
conflict can leave indefinitely.

Detect the already-closed row before consulting is_blocked; the guard only
has meaning for an open->closed transition. This makes the non-force path
symmetric with Force, which already reached Unchanged=true on such a row by
skipping the guard.

Add a regression fixture that seeds a closed row with a stale is_blocked=1
(direct SQL + DOLT_COMMIT, mirroring blocked_merge_test.go's merge-staleness
seeding) and asserts non-force CloseIssueChecked returns Unchanged=true, not
ErrCloseBlocked.

Maintainer review fixup for PR #4893.

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

---------

Co-authored-by: Test User <test@test.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <ci@beads.test>
2026-07-19 14:03:25 -07:00

94 lines
3.5 KiB
Go

package beads_test
import (
"context"
"errors"
"fmt"
"testing"
"github.com/steveyegge/beads"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
// TestReExportCloseBlocked proves the public beads.ErrCloseBlocked alias is the
// same value as the internal sentinel and composes through errors.Is when
// wrapped — the property CloseIssueChecked callers rely on to detect a guard
// refusal without importing internal/storage.
func TestReExportCloseBlocked(t *testing.T) {
t.Parallel()
if beads.ErrCloseBlocked != storage.ErrCloseBlocked {
t.Error("beads.ErrCloseBlocked is not the internal sentinel value (identity broken)")
}
wrapped := fmt.Errorf("x: %w", beads.ErrCloseBlocked)
if !errors.Is(wrapped, beads.ErrCloseBlocked) {
t.Errorf("errors.Is(wrapped, beads.ErrCloseBlocked) = false; err = %v", wrapped)
}
}
// TestReExportedSentinelIdentity proves each public sentinel is the SAME value
// as the internal one it aliases, so errors.Is composes across the package
// boundary without any bridging.
func TestReExportedSentinelIdentity(t *testing.T) {
t.Parallel()
cases := []struct {
name string
exported error
internal error
}{
{"ErrNotFound", beads.ErrNotFound, storage.ErrNotFound},
{"ErrAlreadyClaimed", beads.ErrAlreadyClaimed, storage.ErrAlreadyClaimed},
{"ErrNotClaimable", beads.ErrNotClaimable, storage.ErrNotClaimable},
{"ErrSelfDependency", beads.ErrSelfDependency, domain.ErrSelfDependency},
{"ErrDependencyCycle", beads.ErrDependencyCycle, domain.ErrDependencyCycle},
}
for _, tc := range cases {
if tc.exported != tc.internal {
t.Errorf("beads.%s is not the internal sentinel value (identity broken)", tc.name)
}
}
}
// stubDepRepo satisfies domain.DependencySQLRepository via the embedded
// interface; only the two methods dependencyUseCaseImpl.add consults before
// returning a self-dep/cycle sentinel are implemented. Any other call would
// nil-panic, which keeps the stub honest about the exact surface these
// branches touch.
type stubDepRepo struct {
domain.DependencySQLRepository
hasCycle bool
}
func (s stubDepRepo) ValidateBlockingHierarchy(context.Context, *types.Dependency) error {
return nil
}
func (s stubDepRepo) HasCycle(context.Context, string, string) (bool, error) {
return s.hasCycle, nil
}
// TestReExportedSentinelCatchesRealProductionError drives ACTUAL converted
// production returns — the domain dependency use case's self-dep and cycle
// branches — and asserts the PUBLIC aliases match them via errors.Is. This is
// the property the re-export exists to provide, verified end to end through
// real code rather than by wrapping a sentinel with itself.
func TestReExportedSentinelCatchesRealProductionError(t *testing.T) {
t.Parallel()
uc := domain.NewDependencyUseCase(stubDepRepo{})
selfErr := uc.AddDependency(context.Background(),
&types.Dependency{IssueID: "a", DependsOnID: "a", Type: types.DepBlocks}, "tester")
if !errors.Is(selfErr, beads.ErrSelfDependency) {
t.Errorf("errors.Is(real self-dep err, beads.ErrSelfDependency) = false; err = %v", selfErr)
}
uc = domain.NewDependencyUseCase(stubDepRepo{hasCycle: true})
cycleErr := uc.AddDependency(context.Background(),
&types.Dependency{IssueID: "a", DependsOnID: "b", Type: types.DepBlocks}, "tester")
if !errors.Is(cycleErr, beads.ErrDependencyCycle) {
t.Errorf("errors.Is(real cycle err, beads.ErrDependencyCycle) = false; err = %v", cycleErr)
}
}