beads/issueops/issueops_external_test.go
CI Bot 927f943572 feat(issueops): name the two dependency-endpoint refusals (bd-yby99.9)
DependencyEditor.AddDependencies refuses an edge whose SOURCE names no row,
and one whose TARGET names no row this database can see the absence of. Every
other refusal the role can raise hands a caller something to branch on —
ErrSelfDependency, ErrDependencyCycle, *DependencyTypeConflictError,
*DependencyHierarchyConflictError — and these two handed back "an error", with
different text on each backend. A programmatic consumer could not tell a ghost
endpoint from an infrastructure failure, and the role's own doc said so rather
than promising the anonymity would last.

Both now carry an identity: ErrDependencySourceNotFound and
ErrDependencyTargetNotFound, wrapped by a *DependencyEndpointNotFoundError that
names the refused edge and which of its endpoints was absent. Two sentinels
rather than one because the two are separate answers — a ghost source is always
a bad id, while a target is refused only where this database would have held
it. What is NOT refused is unchanged: an "external:" reference and another
repository's id are still stored as external targets.

The store-backed body and the cross-tier target precheck mint the refusal where
they already read the row. The domain repository has no such read: it learns of
the absence from a foreign-key violation, so it reads both endpoints back on
the transaction that refused, only on the refusal path, and never downgrades
the refusal to a probe's failure. Taking the identity out of the driver's
constraint name would have been the thing a typed refusal exists to avoid. One
user-visible consequence: the proxied-server path now renders "issue <id> not
found" where it used to render a raw foreign-key violation, which is what the
embedded path has always said.

The guarded create classifies the new type where it classified the raw
foreign-key signal, so a missing dependency, parent or waits-for target is
still ErrValidation wrapping ErrNotFound on every backend.

RemoveDependency is deliberately untouched. A removal that finds no edge is
Removed false with a nil error, so there is no refusal there to name.

The shared contract asserts the sentinel and the typed fields for each endpoint
in TWO POSITIONS: alone in a request, and mid-batch where the refusal competes
with the rollback of an edge already written, the half that also reads the
graph back at zero edges. Both cases were verified red on all three backends
before the production change — "issue <id> not found" untyped on the two store
paths, "Error 1452 ... Foreign key violation" on the unit-of-work path.

Agent-Signature: claude-code-claude-opus-5-unknown-reasoning on behalf of CI Bot

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 19:45:54 +00:00

294 lines
11 KiB
Go

package issueops_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"testing"
"github.com/steveyegge/beads"
"github.com/steveyegge/beads/issueops"
)
func TestPublicDeclarationsHaveUsefulZeroValues(t *testing.T) {
var _ issueops.Lifecycle = operationsProbe{}
var create issueops.CreateRequest
var update issueops.UpdateRequest
var closeRequest issueops.CloseRequest
var reopen issueops.ReopenRequest
if create.Issue != nil || update.ExpectedVersion != nil || closeRequest.ExpectedVersion != nil || reopen.ExpectedVersion != nil {
t.Fatal("zero-value request unexpectedly carries a value")
}
}
func TestFieldDistinguishesOmittedFromExplicitZero(t *testing.T) {
var omitted issueops.Field[int]
explicit := issueops.Field[int]{Set: true, Value: 0}
if omitted.Set || !explicit.Set || explicit.Value != 0 {
t.Fatalf("field semantics lost: %#v %#v", omitted, explicit)
}
clear := issueops.Field[*string]{Set: true, Value: nil}
if !clear.Set || clear.Value != nil {
t.Fatalf("explicit pointer clear lost: %#v", clear)
}
}
func TestPatchesRepresentExplicitEmptyReplacements(t *testing.T) {
labels := issueops.LabelPatch{
Replace: issueops.Field[[]string]{Set: true, Value: []string{}},
}
if !labels.Replace.Set || labels.Replace.Value == nil || len(labels.Replace.Value) != 0 {
t.Fatalf("explicit empty label replacement lost: %#v", labels.Replace)
}
metadata := issueops.MetadataPatch{
Replace: issueops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{}`)},
}
if !metadata.Replace.Set || string(metadata.Replace.Value) != `{}` {
t.Fatalf("explicit empty metadata replacement lost: %#v", metadata.Replace)
}
}
func TestPersistencePatchHasOneTypedMode(t *testing.T) {
patchType := reflect.TypeFor[issueops.IssuePatch]()
if _, found := patchType.FieldByName("Ephemeral"); found {
t.Fatal("IssuePatch still exposes independent Ephemeral")
}
if _, found := patchType.FieldByName("NoHistory"); found {
t.Fatal("IssuePatch still exposes independent NoHistory")
}
persistence, found := patchType.FieldByName("Persistence")
if !found {
t.Fatal("IssuePatch.Persistence is missing")
}
if persistence.Type != reflect.TypeFor[issueops.Field[issueops.PersistenceMode]]() {
t.Fatalf("IssuePatch.Persistence type = %v, want Field[PersistenceMode]", persistence.Type)
}
}
func TestPublicPersistenceModeValues(t *testing.T) {
cases := []struct {
got issueops.PersistenceMode
want string
}{
{issueops.PersistenceModePersistent, "persistent"},
{issueops.PersistenceModeEphemeral, "ephemeral"},
{issueops.PersistenceModeNoHistory, "no_history"},
}
for _, tc := range cases {
if string(tc.got) != tc.want {
t.Errorf("persistence mode = %q, want %q", tc.got, tc.want)
}
}
}
func TestClaimRequestSupportsPostClaimPatch(t *testing.T) {
version := int64(7)
request := issueops.UpdateRequest{
Actor: "worker",
IssueID: "bd-123",
Claim: true,
ExpectedVersion: &version,
Patch: issueops.IssuePatch{
Status: issueops.Field[issueops.Status]{Set: true, Value: issueops.StatusBlocked},
Assignee: issueops.Field[string]{Set: true, Value: "dispatcher"},
},
}
if !request.Claim || request.Patch.Status.Value != issueops.StatusBlocked || request.Patch.Assignee.Value != "dispatcher" || *request.ExpectedVersion != version {
t.Fatalf("claim request lost its explicit post-claim patch or version guard: %#v", request)
}
}
func TestForceAssigneeTransferHasSafeZeroValue(t *testing.T) {
var guarded issueops.UpdateRequest
forced := issueops.UpdateRequest{ForceAssigneeTransfer: true}
if guarded.ForceAssigneeTransfer || !forced.ForceAssigneeTransfer {
t.Fatalf("force-assignee-transfer declaration lost bool zero-value semantics: %#v %#v", guarded, forced)
}
}
func TestPublicConstantsKeepCanonicalValues(t *testing.T) {
statuses := []struct {
got issueops.Status
want beads.Status
}{
{issueops.StatusOpen, beads.StatusOpen},
{issueops.StatusInProgress, beads.StatusInProgress},
{issueops.StatusBlocked, beads.StatusBlocked},
{issueops.StatusDeferred, beads.StatusDeferred},
{issueops.StatusClosed, beads.StatusClosed},
}
for _, check := range statuses {
if check.got != check.want {
t.Fatalf("status constant = %q, want %q", check.got, check.want)
}
}
for name, got := range map[string]string{
"pinned": string(issueops.StatusPinned),
"hooked": string(issueops.StatusHooked),
"all-children": issueops.WaitsForAllChildren,
"any-children": issueops.WaitsForAnyChildren,
} {
if got != name {
t.Errorf("public constant = %q, want %q", got, name)
}
}
}
func TestPublicErrorsKeepCanonicalIdentity(t *testing.T) {
checks := []struct {
name string
got, want error
}{
{"not found", issueops.ErrNotFound, beads.ErrNotFound},
{"field too long", issueops.ErrFieldTooLong, beads.ErrFieldTooLong},
{"already claimed", issueops.ErrAlreadyClaimed, beads.ErrAlreadyClaimed},
{"not claimable", issueops.ErrNotClaimable, beads.ErrNotClaimable},
{"close blocked", issueops.ErrCloseBlocked, beads.ErrCloseBlocked},
{"version mismatch", issueops.ErrVersionMismatch, beads.ErrVersionMismatch},
{"self dependency", issueops.ErrSelfDependency, beads.ErrSelfDependency},
{"dependency cycle", issueops.ErrDependencyCycle, beads.ErrDependencyCycle},
}
for _, check := range checks {
if !errors.Is(check.got, check.want) {
t.Errorf("%s error identity lost: %v", check.name, check.got)
}
}
for name, err := range map[string]error{
"validation": issueops.ErrValidation,
"not initialized": issueops.ErrNotInitialized,
"prefix mismatch": issueops.ErrPrefixMismatch,
"assignee mismatch": issueops.ErrAssigneeMismatch,
"status mismatch": issueops.ErrStatusMismatch,
"already exists": issueops.ErrAlreadyExists,
} {
if err == nil {
t.Errorf("%s sentinel is nil", name)
}
}
classified := errors.Join(issueops.ErrValidation, issueops.ErrPrefixMismatch)
if !errors.Is(classified, issueops.ErrValidation) {
t.Error("deterministic validation failure lost ErrValidation classification")
}
if !errors.Is(classified, issueops.ErrPrefixMismatch) {
t.Error("deterministic validation failure lost its specific classification")
}
}
func TestOpenChildrenCloseContractShape(t *testing.T) {
err := &issueops.CloseOpenChildrenError{
IssueID: "bd-parent",
OpenChildren: 3,
}
if !errors.Is(err, issueops.ErrCloseOpenChildren) {
t.Fatalf("CloseOpenChildrenError does not match ErrCloseOpenChildren: %v", err)
}
if got := err.Error(); !strings.Contains(got, "bd-parent") || !strings.Contains(got, "3") {
t.Errorf("CloseOpenChildrenError = %q, want issue and count", got)
}
result := issueops.CloseResult{OpenChildren: 3}
if result.OpenChildren != 3 {
t.Fatalf("CloseResult.OpenChildren = %d, want 3", result.OpenChildren)
}
}
func TestPublicDependencyConflictTypesRemainCanonical(t *testing.T) {
var typeConflict error = &issueops.DependencyTypeConflictError{}
var hierarchyConflict error = &issueops.DependencyHierarchyConflictError{}
if typeConflict == nil || hierarchyConflict == nil {
t.Fatal("dependency conflict aliases lost their error implementations")
}
if reflect.TypeFor[*issueops.DependencyTypeConflictError]() != reflect.TypeFor[*beads.DependencyTypeConflictError]() {
t.Error("DependencyTypeConflictError lost canonical type identity")
}
if reflect.TypeFor[*issueops.DependencyHierarchyConflictError]() != reflect.TypeFor[*beads.DependencyHierarchyConflictError]() {
t.Error("DependencyHierarchyConflictError lost canonical type identity")
}
if reflect.TypeFor[*issueops.DependencyEndpointNotFoundError]() != reflect.TypeFor[*beads.DependencyEndpointNotFoundError]() {
t.Error("DependencyEndpointNotFoundError lost canonical type identity")
}
}
// TestDependencyEndpointNotFoundCarriesTheAbsentEndpoint pins the value's own
// promises: the sentinel a caller branches on, the edge and the endpoint it
// names, and the message — which the two write plumbings render identically
// only because both build it from here.
func TestDependencyEndpointNotFoundCarriesTheAbsentEndpoint(t *testing.T) {
ghostSource := &issueops.DependencyEndpointNotFoundError{
IssueID: "bd-ghost", DependsOnID: "bd-real", MissingID: "bd-ghost",
Err: issueops.ErrDependencySourceNotFound,
}
if !errors.Is(ghostSource, issueops.ErrDependencySourceNotFound) {
t.Fatalf("ghost source does not match ErrDependencySourceNotFound: %v", ghostSource)
}
if errors.Is(ghostSource, issueops.ErrDependencyTargetNotFound) {
t.Error("ghost source also matches ErrDependencyTargetNotFound: the two refusals are not interchangeable")
}
if got := ghostSource.Error(); got != "issue bd-ghost not found" {
t.Errorf("ghost source message = %q, want the endpoint named once", got)
}
missingTarget := &issueops.DependencyEndpointNotFoundError{
IssueID: "bd-real", DependsOnID: "bd-ghost", MissingID: "bd-ghost",
Err: issueops.ErrDependencyTargetNotFound,
}
var recovered *issueops.DependencyEndpointNotFoundError
if !errors.As(fmt.Errorf("add deps[1]: %w", missingTarget), &recovered) {
t.Fatal("DependencyEndpointNotFoundError is not recoverable through a wrap")
}
if recovered.IssueID != "bd-real" || recovered.DependsOnID != "bd-ghost" || recovered.MissingID != "bd-ghost" {
t.Errorf("recovered = %+v, want the refused edge and the absent endpoint", recovered)
}
}
// TestClaimConflictCarriesTheStateThatBeatIt pins the whole point of the typed
// conflict: a caller reports who won by reading FIELDS, and still classifies
// the refusal by sentinel.
func TestClaimConflictCarriesTheStateThatBeatIt(t *testing.T) {
conflict := &issueops.ClaimConflictError{
IssueID: "bd-1",
Assignee: "bob",
Status: issueops.StatusInProgress,
Err: issueops.ErrAlreadyClaimed,
}
if !errors.Is(conflict, issueops.ErrAlreadyClaimed) {
t.Fatalf("ClaimConflictError does not match ErrAlreadyClaimed: %v", conflict)
}
var recovered *issueops.ClaimConflictError
if !errors.As(fmt.Errorf("claim bd-1: %w", conflict), &recovered) {
t.Fatal("ClaimConflictError is not recoverable through a wrap")
}
if recovered.Assignee != "bob" || recovered.Status != issueops.StatusInProgress {
t.Errorf("recovered = %+v, want the observed assignee and status", recovered)
}
// The zero observation is a documented state, not a panic: the refusal
// stands, it just carries nothing.
bare := &issueops.ClaimConflictError{IssueID: "bd-1", Err: issueops.ErrNotClaimable}
if !errors.Is(bare, issueops.ErrNotClaimable) || bare.Error() != issueops.ErrNotClaimable.Error() {
t.Errorf("unobserved conflict = %q, want the bare sentinel", bare.Error())
}
}
type operationsProbe struct{}
func (operationsProbe) Create(context.Context, issueops.CreateRequest) (issueops.CreateResult, error) {
return issueops.CreateResult{}, nil
}
func (operationsProbe) Update(context.Context, issueops.UpdateRequest) (issueops.UpdateResult, error) {
return issueops.UpdateResult{}, nil
}
func (operationsProbe) Close(context.Context, issueops.CloseRequest) (issueops.CloseResult, error) {
return issueops.CloseResult{}, nil
}
func (operationsProbe) Reopen(context.Context, issueops.ReopenRequest) (issueops.ReopenResult, error) {
return issueops.ReopenResult{}, nil
}