diff --git a/CHANGELOG.md b/CHANGELOG.md index 54dd8d062..e5c2df561 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **The two dependency-endpoint refusals now carry an identity** (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. Both + were "an error" and nothing more — not the same error text on every backend, + and impossible to tell apart from an infrastructure failure — which left the + role's typed-refusal vocabulary with a hole every other refusal it can raise + had already filled. They are now `errors.Is`-matchable as + `ErrDependencySourceNotFound` and `ErrDependencyTargetNotFound`, carried by a + `*DependencyEndpointNotFoundError` naming the refused edge and which of its + endpoints was absent, all three re-exported from the root package beside the + conflict types. What is NOT refused is unchanged: an `external:` reference + and another repository's id are still accepted as external targets. + + The user-facing message is byte-identical on the embedded and store paths + (`issue not found`), and the proxied-server path now renders that + message too instead of a raw foreign-key violation — the endpoint is + classified from the refusing transaction rather than parsed out of the + driver's prose, so the two plumbings agree on the text as well as the type. + The shared `DependencyEditor` contract asserts the sentinel and the typed + fields for each endpoint, alone in a request and mid-batch, with the + mid-batch half reading the graph back at zero edges. `RemoveDependency` is + unaffected: a removal that finds no edge is a success, not a refusal. + ### Changed - **`bd search` now includes closed issues by default** (bd-t5yex). The diff --git a/backend/conformance/dependency_editor_contract.go b/backend/conformance/dependency_editor_contract.go index 21f057b42..4618c547d 100644 --- a/backend/conformance/dependency_editor_contract.go +++ b/backend/conformance/dependency_editor_contract.go @@ -886,10 +886,13 @@ func RunDependencyEditorRoutesWispSourcedRemovalToTheWispPlane(t *testing.T, ctx // the target here is deliberately a real seeded issue: the refusal under test // is about the source alone. // -// SPEC-GAP bd-yby99.9: the doc now states that the refusal HAPPENS and states -// that it deliberately names no identity yet, so err != nil is still the whole -// assertion — pinning a sentinel or a message here would assert more than the -// leaf says, and the leaf says the anonymity is a gap rather than a promise. +// The refusal's IDENTITY is asserted in BOTH POSITIONS. Alone in a request it +// is the only thing that can have failed; mid-batch it competes with the +// rollback of the edge already written, which is where an implementation that +// re-raised the refusal as its own wrapper — or as the rollback's error — would +// lose the type. The mid-batch half therefore reads the graph back at zero +// edges as well, because a typed refusal that left half a graph behind would +// still be the wrong answer. func RunDependencyEditorRefusesAGhostSource(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { t.Helper() source := fixture.IssuePrefix + "-ghostsrc-known" @@ -898,15 +901,20 @@ func RunDependencyEditorRefusesAGhostSource(t *testing.T, ctx context.Context, f seedDependencyEditorIssue(t, ctx, fixture, target) ghost := source[:len(source)-1] - if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: ghost, DependsOnID: target, Type: publicops.DepBlocks}}, + }) + assertDependencyEndpointNotFound(t, err, "the sole edge of a request", publicops.ErrDependencySourceNotFound, ghost, target, ghost) + + _, err = fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ Actor: "writer", Edges: []publicops.DependencyEdge{ {IssueID: source, DependsOnID: target, Type: publicops.DepBlocks}, {IssueID: ghost, DependsOnID: target, Type: publicops.DepBlocks}, }, - }); err == nil { - t.Fatalf("AddDependencies from the nonexistent source %q = nil error, want a refusal: %q exists but is a different id", ghost, source) - } + }) + assertDependencyEndpointNotFound(t, err, "the second edge of a request", publicops.ErrDependencySourceNotFound, ghost, target, ghost) assertDependencyEditorNoEdgesFrom(t, ctx, fixture, source, ghost) } @@ -914,28 +922,61 @@ func RunDependencyEditorRefusesAGhostSource(t *testing.T, ctx context.Context, f // target-existence clause. Existence is checked "only where the backend can // see it", and the two acceptance cases above pin what that therefore does NOT // refuse — an "external:" reference and an issue in another repository. The -// leaf now states the half neither of them covers outright: a target whose -// absence the backend CAN see — same prefix, no "external:" marker, no row — -// is refused and nothing is written. Without it the clause reads as a blanket -// amnesty, which is the opposite of what it says. +// leaf states the half neither of them covers outright: a target whose absence +// the backend CAN see — same prefix, no "external:" marker, no row — is refused +// and nothing is written. Without it the clause reads as a blanket amnesty, +// which is the opposite of what it says. // -// SPEC-GAP bd-yby99.9: the refusal's IDENTITY is still unnamed, and the leaf -// now says so deliberately, so err != nil is all this asserts. +// The refusal is ErrDependencyTargetNotFound and not the source's sentinel, +// asserted in both positions for the reason the ghost-source case gives. The +// two are separate answers, so a backend that raised one endpoint's refusal for +// the other's absence would send a caller to fix the wrong id. func RunDependencyEditorRefusesAMissingLocalTarget(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { t.Helper() source := fixture.IssuePrefix + "-notgt-source" + other := fixture.IssuePrefix + "-notgt-other" seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, other) // Same prefix as the source, so it is neither an external reference nor // another repository's id: this database is exactly where it would be. missing := fixture.IssuePrefix + "-notgt-ghost" - if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ Actor: "writer", Edges: []publicops.DependencyEdge{{IssueID: source, DependsOnID: missing, Type: publicops.DepBlocks}}, - }); err == nil { - t.Fatalf("AddDependencies onto the missing local target %q = nil error, want a refusal", missing) - } + }) + assertDependencyEndpointNotFound(t, err, "the sole edge of a request", publicops.ErrDependencyTargetNotFound, source, missing, missing) assertDependencyEditorNoEdgesFrom(t, ctx, fixture, source) + + _, err = fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: source, DependsOnID: other, Type: publicops.DepBlocks}, + {IssueID: source, DependsOnID: missing, Type: publicops.DepBlocks}, + }, + }) + assertDependencyEndpointNotFound(t, err, "the second edge of a request", publicops.ErrDependencyTargetNotFound, source, missing, missing) + assertDependencyEditorNoEdgesFrom(t, ctx, fixture, source) +} + +// assertDependencyEndpointNotFound is the shared shape of the two +// endpoint-existence refusals: the sentinel a caller branches on, and the typed +// value carrying which edge was refused and which of its endpoints was absent. +// Reading the fields is the point — the message is prose and is not a promise, +// so a caller that needs the id must be able to take it from the value. +func assertDependencyEndpointNotFound(t *testing.T, err error, position string, sentinel error, issueID, dependsOnID, missingID string) { + t.Helper() + if !errors.Is(err, sentinel) { + t.Fatalf("%s: error = %v, want errors.Is %v", position, err, sentinel) + } + var missing *publicops.DependencyEndpointNotFoundError + if !errors.As(err, &missing) { + t.Fatalf("%s: error = %v, want *DependencyEndpointNotFoundError", position, err) + } + if missing.IssueID != issueID || missing.DependsOnID != dependsOnID || missing.MissingID != missingID { + t.Errorf("%s: refusal = %+v, want the edge %s -> %s with %s missing", + position, missing, issueID, dependsOnID, missingID) + } } // dependencyEditorUnlistedType is a DependencyType deliberately absent from the diff --git a/beads.go b/beads.go index 56ad8e02f..ea26654a5 100644 --- a/beads.go +++ b/beads.go @@ -513,7 +513,12 @@ var ( ErrVersionMismatch = storage.ErrVersionMismatch ErrSelfDependency = domain.ErrSelfDependency ErrDependencyCycle = domain.ErrDependencyCycle - ErrFieldTooLong = types.ErrFieldTooLong + // ErrDependencySourceNotFound and ErrDependencyTargetNotFound are the two + // endpoint-existence refusals AddDependency and AddDependencies raise; the + // typed value carrying the missing id is DependencyEndpointNotFoundError. + ErrDependencySourceNotFound = domain.ErrDependencySourceNotFound + ErrDependencyTargetNotFound = domain.ErrDependencyTargetNotFound + ErrFieldTooLong = types.ErrFieldTooLong // ErrGateBusy is returned by OpenGated when a maintenance operation // holds the workspace or physical-root gate exclusively and the wait // budget ran out. Alias of the internal sentinel so errors.Is works @@ -530,3 +535,8 @@ type DependencyTypeConflictError = domain.DependencyTypeConflictError // edge would gate an issue on its own ancestor/descendant (a gate that can // never clear). type DependencyHierarchyConflictError = domain.DependencyHierarchyConflictError + +// DependencyEndpointNotFoundError is returned by AddDependency when an edge +// names an endpoint this database can see the absence of; callers errors.As it +// to read the missing id instead of parsing the message. +type DependencyEndpointNotFoundError = domain.DependencyEndpointNotFoundError diff --git a/errors_test.go b/errors_test.go index 1c936e528..5fcd96966 100644 --- a/errors_test.go +++ b/errors_test.go @@ -95,6 +95,8 @@ func TestReExportedSentinelIdentity(t *testing.T) { {"ErrVersionMismatch", beads.ErrVersionMismatch, storage.ErrVersionMismatch}, {"ErrSelfDependency", beads.ErrSelfDependency, domain.ErrSelfDependency}, {"ErrDependencyCycle", beads.ErrDependencyCycle, domain.ErrDependencyCycle}, + {"ErrDependencySourceNotFound", beads.ErrDependencySourceNotFound, domain.ErrDependencySourceNotFound}, + {"ErrDependencyTargetNotFound", beads.ErrDependencyTargetNotFound, domain.ErrDependencyTargetNotFound}, {"ErrFieldTooLong", beads.ErrFieldTooLong, types.ErrFieldTooLong}, } for _, tc := range cases { @@ -207,6 +209,27 @@ func TestReExportedDependencyConflictTypes(t *testing.T) { if gotHier.IssueID != "child" || gotHier.BlockerID != "ancestor" || !gotHier.BlockerIsAncestor { t.Errorf("extracted hierarchy-conflict fields = %+v, want {child ancestor true}", gotHier) } + + // Endpoint miss: the target names no row this database holds. The domain + // use case passes it through unwrapped for the same reason the two + // conflicts above are passed through. + missing := &domain.DependencyEndpointNotFoundError{ + IssueID: "a", DependsOnID: "ghost", MissingID: "ghost", + Err: domain.ErrDependencyTargetNotFound, + } + uc = domain.NewDependencyUseCase(insertErrDepRepo{insertErr: missing}) + err = uc.AddDependency(context.Background(), + &types.Dependency{IssueID: "a", DependsOnID: "ghost", Type: types.DepBlocks}, "tester") + var gotMissing *beads.DependencyEndpointNotFoundError + if !errors.As(err, &gotMissing) { + t.Fatalf("errors.As(real endpoint-miss err, *beads.DependencyEndpointNotFoundError) = false; err = %v", err) + } + if !errors.Is(err, beads.ErrDependencyTargetNotFound) { + t.Errorf("errors.Is(real endpoint-miss err, beads.ErrDependencyTargetNotFound) = false; err = %v", err) + } + if gotMissing.IssueID != "a" || gotMissing.DependsOnID != "ghost" || gotMissing.MissingID != "ghost" { + t.Errorf("extracted endpoint-miss fields = %+v, want {a ghost ghost}", gotMissing) + } } // TestReExportFieldTooLong proves the public beads.ErrFieldTooLong alias is the diff --git a/internal/storage/dolt/transaction.go b/internal/storage/dolt/transaction.go index c6fc15418..993fbedae 100644 --- a/internal/storage/dolt/transaction.go +++ b/internal/storage/dolt/transaction.go @@ -971,7 +971,7 @@ func (t *doltTransaction) AddDependencyWithOptions(ctx context.Context, dep *typ // own tx and hand the row to AddDependencyInTx. crossTierTarget := kind != issueops.DepTargetExternal && t.txFor(targetTable) != t.txFor(table) if crossTierTarget { - precheck, err := t.readDepTargetForPrecheck(ctx, targetTable, dep.DependsOnID) + precheck, err := t.readDepTargetForPrecheck(ctx, dep.IssueID, targetTable, dep.DependsOnID) if err != nil { return err } @@ -1062,14 +1062,14 @@ func (t *doltTransaction) addWispDepSuspendingIssueTargetFK(ctx context.Context, // readDepTargetForPrecheck validates a dependency target on the transaction // that owns its table and returns the row fields AddDependencyInTx needs when // it cannot read the target itself (cross-tier edges). -func (t *doltTransaction) readDepTargetForPrecheck(ctx context.Context, targetTable, id string) (*issueops.DepTargetPrecheck, error) { +func (t *doltTransaction) readDepTargetForPrecheck(ctx context.Context, sourceID, targetTable, id string) (*issueops.DepTargetPrecheck, error) { var p issueops.DepTargetPrecheck //nolint:gosec // G201: targetTable is "issues" or "wisps" err := t.txFor(targetTable).QueryRowContext(ctx, fmt.Sprintf(`SELECT issue_type, status FROM %s WHERE id = ?`, targetTable), id, ).Scan(&p.IssueType, &p.Status) if errors.Is(err, sql.ErrNoRows) { - return nil, fmt.Errorf("issue %s not found", id) + return nil, issueops.MissingDependencyTarget(sourceID, id) } if err != nil { return nil, fmt.Errorf("failed to check target issue existence: %w", err) diff --git a/internal/storage/domain/db/dependency.go b/internal/storage/domain/db/dependency.go index fe2514314..10e99e847 100644 --- a/internal/storage/domain/db/dependency.go +++ b/internal/storage/domain/db/dependency.go @@ -151,6 +151,9 @@ func (r *dependencySQLRepositoryImpl) Insert(ctx context.Context, dep *types.Dep depid.New(dep.IssueID, dep.DependsOnID), dep.IssueID, dep.DependsOnID, string(dep.Type), time.Now().UTC(), actor, metadata, dep.ThreadID, ); err != nil { + if missing := r.classifyMissingEndpoint(ctx, dep, opts.UseWispsTable, targetCol, err); missing != nil { + return missing + } return fmt.Errorf("db: DependencySQLRepository.Insert: %w", err) } if dep.Type == types.DepParentChild { @@ -218,6 +221,60 @@ func (r *dependencySQLRepositoryImpl) Insert(ctx context.Context, dep *types.Dep return nil } +// classifyMissingEndpoint names the endpoint behind a foreign-key refusal, +// re-read on the same runner that refused the insert. The driver's message +// names its constraint, but taking identity out of driver prose is the thing a +// typed refusal exists to avoid, so the two endpoints are read back instead — +// only on the refusal path, so a bulk add still pays no probe per edge. +// +// The refusal is never downgraded to a probe's failure: anything the reads +// cannot settle returns nil and the caller keeps the original error. +func (r *dependencySQLRepositoryImpl) classifyMissingEndpoint(ctx context.Context, dep *types.Dependency, sourceIsWisp bool, targetCol string, insertErr error) error { + if !dberrors.IsMissingForeignKeyTarget(insertErr) { + return nil + } + sourceTable := "issues" + if sourceIsWisp { + sourceTable = "wisps" + } + sourceExists, probeErr := r.rowExists(ctx, sourceTable, dep.IssueID) + if probeErr != nil { + return nil + } + if !sourceExists { + return issueops.MissingDependencySource(dep.IssueID, dep.DependsOnID) + } + + var targetTable string + switch targetCol { + case "depends_on_issue_id": + targetTable = "issues" + case "depends_on_wisp_id": + targetTable = "wisps" + default: + return nil + } + targetExists, probeErr := r.rowExists(ctx, targetTable, dep.DependsOnID) + if probeErr != nil || targetExists { + return nil + } + return issueops.MissingDependencyTarget(dep.IssueID, dep.DependsOnID) +} + +func (r *dependencySQLRepositoryImpl) rowExists(ctx context.Context, table, id string) (bool, error) { + var probe int + //nolint:gosec // G201: table is one of the two hardcoded plane tables + err := r.runner.QueryRowContext(ctx, fmt.Sprintf("SELECT 1 FROM %s WHERE id = ? LIMIT 1", table), id).Scan(&probe) + switch { + case err == nil: + return true, nil + case errors.Is(err, sql.ErrNoRows): + return false, nil + default: + return false, err + } +} + func (r *dependencySQLRepositoryImpl) ValidateBlockingHierarchy(ctx context.Context, dep *types.Dependency) error { if dep == nil { return errors.New("db: DependencySQLRepository.ValidateBlockingHierarchy: dep must not be nil") diff --git a/internal/storage/domain/dependency.go b/internal/storage/domain/dependency.go index d20e79f8c..30277e950 100644 --- a/internal/storage/domain/dependency.go +++ b/internal/storage/domain/dependency.go @@ -17,8 +17,10 @@ import ( // values, so every domain.ErrX reference and every errors.Is site keeps // matching the identical error. var ( - ErrSelfDependency = issueops.ErrSelfDependency - ErrDependencyCycle = issueops.ErrDependencyCycle + ErrSelfDependency = issueops.ErrSelfDependency + ErrDependencyCycle = issueops.ErrDependencyCycle + ErrDependencySourceNotFound = issueops.ErrDependencySourceNotFound + ErrDependencyTargetNotFound = issueops.ErrDependencyTargetNotFound ) // cycleError carries a fully-formatted cycle-rejection message while unwrapping @@ -59,6 +61,11 @@ type DependencyTypeConflictError = issueops.DependencyTypeConflictError // issueops.DependencyHierarchyConflictError. type DependencyHierarchyConflictError = issueops.DependencyHierarchyConflictError +// DependencyEndpointNotFoundError reports which endpoint of a refused edge this +// database could see the absence of. See +// issueops.DependencyEndpointNotFoundError. +type DependencyEndpointNotFoundError = issueops.DependencyEndpointNotFoundError + type DepDirection int const ( @@ -276,7 +283,8 @@ func (u *dependencyUseCaseImpl) add(ctx context.Context, dep *types.Dependency, if err := u.depRepo.Insert(ctx, dep, actor, DepInsertOpts{UseWispsTable: useWisp, HierarchyValidated: true, CycleValidated: true, EmitEvent: true}); err != nil { // The retype conflict is a user-facing error whose message already // matches embedded verbatim; pass it through unwrapped so the CLI does - // not prepend "add dep: insert:" (#4547 F-1). + // not prepend "add dep: insert:" (#4547 F-1). The endpoint-existence + // refusals are here for the same reason. var conflict *DependencyTypeConflictError if errors.As(err, &conflict) { return err @@ -285,6 +293,10 @@ func (u *dependencyUseCaseImpl) add(ctx context.Context, dep *types.Dependency, if errors.As(err, &hierarchyConflict) { return err } + var missingEndpoint *DependencyEndpointNotFoundError + if errors.As(err, &missingEndpoint) { + return err + } return fmt.Errorf("add dep: insert: %w", err) } return nil @@ -720,6 +732,10 @@ func (u *dependencyUseCaseImpl) AddDependencies(ctx context.Context, deps []*typ if errors.As(err, &hierarchyConflict) { return BulkAddDepsResult{}, err } + var missingEndpoint *DependencyEndpointNotFoundError + if errors.As(err, &missingEndpoint) { + return BulkAddDepsResult{}, err + } return BulkAddDepsResult{}, fmt.Errorf("add deps[%d]: insert: %w", i, err) } } diff --git a/internal/storage/issueops/dependencies.go b/internal/storage/issueops/dependencies.go index 2ec42838b..d0a544eab 100644 --- a/internal/storage/issueops/dependencies.go +++ b/internal/storage/issueops/dependencies.go @@ -214,7 +214,7 @@ func addDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, a //nolint:gosec // G201: sourceTable is from WispTableRouting ("issues" or "wisps") if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT issue_type FROM %s WHERE id = ?`, sourceTable), dep.IssueID).Scan(&sourceType); err != nil { if errors.Is(err, sql.ErrNoRows) { - return false, fmt.Errorf("issue %s not found", dep.IssueID) + return false, MissingDependencySource(dep.IssueID, dep.DependsOnID) } return false, fmt.Errorf("failed to check issue existence: %w", err) } @@ -229,7 +229,7 @@ func addDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, a //nolint:gosec // G201: targetTable is from WispTableRouting ("issues" or "wisps") if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT issue_type FROM %s WHERE id = ?`, targetTable), dep.DependsOnID).Scan(&targetType); err != nil { if errors.Is(err, sql.ErrNoRows) { - return false, fmt.Errorf("issue %s not found", dep.DependsOnID) + return false, MissingDependencyTarget(dep.IssueID, dep.DependsOnID) } return false, fmt.Errorf("failed to check target issue existence: %w", err) } diff --git a/internal/storage/issueops/errors.go b/internal/storage/issueops/errors.go index 50d7e28fb..0bc299bcc 100644 --- a/internal/storage/issueops/errors.go +++ b/internal/storage/issueops/errors.go @@ -1,6 +1,40 @@ package issueops -import "fmt" +import ( + "fmt" + + publicops "github.com/steveyegge/beads/issueops" +) + +// MissingDependencySource builds the refusal for an edge whose SOURCE names no +// row this database holds. +// +// Every write plumbing that can observe the absence mints its refusal here or +// in the target twin below: the in-transaction store body, the cross-tier +// target precheck, and the domain repository's classification of a foreign-key +// refusal. That is what makes the message identical across them as well as the +// type. +func MissingDependencySource(issueID, dependsOnID string) error { + return &publicops.DependencyEndpointNotFoundError{ + IssueID: issueID, + DependsOnID: dependsOnID, + MissingID: issueID, + Err: publicops.ErrDependencySourceNotFound, + } +} + +// MissingDependencyTarget builds the refusal for an edge whose TARGET names no +// row this database holds and whose absence this database can see. Callers +// decide that second half — an "external:" reference and another repository's +// id never reach here. +func MissingDependencyTarget(issueID, dependsOnID string) error { + return &publicops.DependencyEndpointNotFoundError{ + IssueID: issueID, + DependsOnID: dependsOnID, + MissingID: dependsOnID, + Err: publicops.ErrDependencyTargetNotFound, + } +} // ErrTooManyRows is returned by SearchIssuesInTx (and equivalent paths in // other backends) when a search would yield more rows than the caller's diff --git a/internal/storage/issueops/public_create.go b/internal/storage/issueops/public_create.go index 19b7a59c4..693edac9e 100644 --- a/internal/storage/issueops/public_create.go +++ b/internal/storage/issueops/public_create.go @@ -102,13 +102,16 @@ func ClassifyPublicCreateError(err error) error { if errors.Is(err, storage.ErrPrefixMismatch) || errors.Is(err, domain.ErrSelfDependency) || errors.Is(err, types.ErrFieldTooLong) || errors.Is(err, domain.ErrDependencyCycle) || errors.As(err, &conflict) || errors.As(err, &hierarchyConflict) { return publicCreateValidationError(err) } - // A create whose requested relationship names a row that does not exist - // fails the dependency table's target foreign key. The caller asked for an - // edge to something absent, so this is a deterministic refusal rather than - // an infrastructure error: classify it the same way ExecuteCreate refuses a - // skipped dependency, so every backend reports a missing dependency, - // parent, or waits-for target as ErrValidation wrapping ErrNotFound. - if dberrors.IsMissingForeignKeyTarget(err) { + // A create whose requested relationship names a row that does not exist is + // refused by the dependency write: as the typed endpoint refusal where the + // write could name the absent endpoint, and as the target foreign key where + // it could not. The caller asked for an edge to something absent, so this + // is a deterministic refusal rather than an infrastructure error: classify + // it the same way ExecuteCreate refuses a skipped dependency, so every + // backend reports a missing dependency, parent, or waits-for target as + // ErrValidation wrapping ErrNotFound. + var missingEndpoint *domain.DependencyEndpointNotFoundError + if errors.As(err, &missingEndpoint) || dberrors.IsMissingForeignKeyTarget(err) { return publicCreateValidationError(fmt.Errorf("create: dependency target does not exist: %w: %w", err, storage.ErrNotFound)) } return err diff --git a/issueops/dependencyeditor.go b/issueops/dependencyeditor.go index 724790021..3555de67f 100644 --- a/issueops/dependencyeditor.go +++ b/issueops/dependencyeditor.go @@ -145,23 +145,24 @@ type DependencyEditor interface { // scheduling cycle (ErrDependencyCycle), a conflicting type on a pair that // already has an edge (*DependencyTypeConflictError), a blocking edge that // would gate an issue on its own ancestor or descendant - // (*DependencyHierarchyConflictError), or a SOURCE that does not exist. + // (*DependencyHierarchyConflictError), or a SOURCE that does not exist + // (ErrDependencySourceNotFound). // // A target's existence is checked only where the backend can see it. A // target may legitimately be an "external:" reference or an issue in // another repository, neither of which this database holds, so there is no // blanket unknown-target refusal to promise. Where the backend CAN see the // absence — an id in this database's own namespace, carrying no - // "external:" marker and matching no row — the edge is refused, and the - // request writes nothing like any other refusal. + // "external:" marker and matching no row — the edge is refused with + // ErrDependencyTargetNotFound, and the request writes nothing like any + // other refusal. // - // NEITHER EXISTENCE REFUSAL NAMES AN IDENTITY YET. The four refusals above - // hand a caller a sentinel or a typed value to branch on; a ghost source - // and a missing local target are only "an error", and not even the same - // error text on every implementation. So a caller cannot today tell a - // ghost endpoint from an infrastructure failure. That is a known gap - // (bd-yby99.9) rather than a promise the refusal will stay anonymous, and - // nothing should be written that string-matches it. + // BOTH EXISTENCE REFUSALS CARRY THEIR IDENTITY. Each is a + // *DependencyEndpointNotFoundError naming the refused edge and the + // endpoint that was absent, wrapping its own sentinel, so a caller tells a + // ghost endpoint from an infrastructure failure — and the source case from + // the target case — with errors.Is and errors.As rather than by reading + // the message. The message itself remains prose and is not a promise. // // An edge that already exists with the SAME type is idempotent and refuses // nothing, and REPETITION WITHIN ONE REQUEST answers the same way: the diff --git a/issueops/errors.go b/issueops/errors.go index aef0c36ec..8f41a8987 100644 --- a/issueops/errors.go +++ b/issueops/errors.go @@ -191,6 +191,51 @@ func (e *DependencyTypeConflictError) Error() string { e.IssueID, e.DependsOnID, e.ExistingType, e.RequestedType) } +// ErrDependencySourceNotFound is returned when an edge's SOURCE names no row +// this database holds. An edge follows its source, so there is no plane for it +// to land in and no event stream to record it on. +var ErrDependencySourceNotFound = errors.New("dependency source not found") + +// ErrDependencyTargetNotFound is returned when an edge's TARGET names no row +// this database holds AND is one whose absence this database can SEE: an id in +// its own namespace, carrying no "external:" marker. An "external:" reference +// and an id belonging to another repository are accepted as external targets, +// so neither raises this. +// +// It is a separate sentinel from the source's because the two are separate +// answers. A ghost source is always a bad id; a target is only refused when +// this database is the one that would have held it, which is a narrower claim +// and the one a caller has to reason about before retrying. +var ErrDependencyTargetNotFound = errors.New("dependency target not found") + +// DependencyEndpointNotFoundError reports which endpoint of a refused edge was +// absent, read inside the transaction that refused it. It wraps the refusal +// rather than replacing it, so the sentinel still matches, the message stays +// what it was, and a caller classifies the refusal from typed fields instead of +// parsing prose — the ClaimConflictError arrangement, applied to the graph. +// +// It carries the whole edge rather than only the missing id because the request +// is all-or-nothing: the refusal is the REQUEST's, so a caller reporting which +// of its own edges was rejected has to find it by both endpoints. +type DependencyEndpointNotFoundError struct { + // IssueID and DependsOnID name the refused edge. + IssueID string + DependsOnID string + // MissingID is the endpoint that named no row: IssueID for a ghost source, + // DependsOnID for a missing target. + MissingID string + // Err is the wrapped refusal. It matches ErrDependencySourceNotFound or + // ErrDependencyTargetNotFound. + Err error +} + +func (e *DependencyEndpointNotFoundError) Error() string { + return fmt.Sprintf("issue %s not found", e.MissingID) +} + +// Unwrap makes DependencyEndpointNotFoundError match the refusal it carries. +func (e *DependencyEndpointNotFoundError) Unwrap() error { return e.Err } + // 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. diff --git a/issueops/issueops_external_test.go b/issueops/issueops_external_test.go index a81fd64ae..c2e1e772d 100644 --- a/issueops/issueops_external_test.go +++ b/issueops/issueops_external_test.go @@ -212,6 +212,41 @@ func TestPublicDependencyConflictTypesRemainCanonical(t *testing.T) { 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