* fix(issueops): enforce the dotted-child dependency rule on every leg The refusal of an explicit edge from a dotted-id child to its own ancestor (bd-abc.1 -> bd-abc; only the parent-child edge to the immediate dotted parent is allowed) lived only in cmd/bd (isDisallowedHierarchicalDependency). HTTP dependencies:add, batch:apply dep_add items and `bd create --graph`'s own edges skipped it. It is now one library rule, issueops.CheckDottedChildDependency, returning *issueops.DottedChildDependencyError (unwraps to ErrValidation, same message the CLI printed): - ValidateAddDependenciesRequest applies it, so DependencyEditor refuses on dolt, embedded, uow and the server behind httpapi (400 invalid_argument); - both BatchApplier bodies (issueops and uow) apply it to each dep_add item on the resolved ids, so a key bound to a minted dotted child is refused too; - the HTTP client checks it before the dial, as it does self-dependency, so the typed error survives the wire. cmd/bd keeps no copy: single-edge dep add / dep --blocks rely on the role; bd link (still on the store verb) and the --file bulk reporter call the library rule. CLI output is byte-identical (checked against origin/main). Conformance: RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent and RunBatchApplyRefusesADottedChildGatedOnItsOwnParent wired on dolt, embedded, uow and http, plus a raw-wire served test past the client check and handler mapping cases. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(batch): refuse a dotted child gated on its own ancestor in bd batch Review fixup for PR #7424 (iterations 1 and 2). Major: a bd batch script line `dep add bd-abc.1 bd-abc` still wrote the edge this PR refuses everywhere else, on both backends. Neither batch dispatch writes through the DependencyEditor role that enforces the dotted-child rule: the classic arm calls storage.Transaction.AddDependency and the proxied arm the unit of work's AddDependencies verb. Both arms now build the edge with one helper, batchDepAddEdge, which keeps the default type and the arity and type errors, and asks publicops.CheckDottedChildDependency the way bd link does. A refused line rolls the whole batch back. Tests: TestBatchDepAddEdge (default and explicit types, arity and type errors, three refusals typed *DottedChildDependencyError matching ErrValidation, and the immediate parent-child edge allowed), and TestProxiedServerBatchDepAddRefusesADottedChildGatedOnItsParent (classic and proxied: the refusal names line 2, rolls back an earlier update line and writes no edge, and `dep add C P parent-child` still lands exactly one), registered in the proxied shard manifest. A mutant that drops the rule from the shared helper fails both; one that bypasses the helper in the proxied arm alone fails the proxied leg. Minors: - For a child whose parent-child edge is already stored (a `bd create --parent` child) the rule answers ahead of the hierarchy and type conflicts, so an HTTP caller now gets 400 invalid_argument where it got 409 dependency_cycle (blocking types) or dependency_exists (any other type). Documented in the DependencyEditor role doc, the CHANGELOG entry and the httpapi batch-apply test comment, and pinned by a stored-hierarchy phase in the DependencyEditor and BatchApplier dotted-child conformance contracts on every leg; a mutant that drops the rule gets the hierarchy conflict instead (409 dependency_cycle on the wire). - The bd create --graph dry-run note now says the live create may also refuse an edge that gates a dotted-id child on its own ancestor. - The DottedChildDependencyError comment says the message is kept verbatim and says "deadlock" whatever the type. Not changed: bd relate (relates-to does not schedule) and the edges a create writes with its issue (bd create --deps/--waits-for, and over HTTP an explicit dotted id with a non-immediate ParentID) still write through paths that skip the rule. The scheduling shapes need an explicit dotted id or a grandparent target. Follow-up bd-25s1wh tracks moving the rule down to the domain/store add verbs, with a structural bypass for reparent and template edges. Iteration 2 (minor): the CheckDottedChildDependency doc no longer implies bd link and bd batch are the only writers outside the roles. It names bd relate and the create edges as not applying the rule yet and cites bd-25s1wh. Complexity (cyclomatic/cognitive): runBatchOp 23/35 -> 21/31, runBatchOpUOW 28/48 -> 26/44, batchDepAddEdge 5/4. Touching them brings both pre-existing dispatch switches into the measured set; splitting them is out of scope here. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(issueops,httpapi): document the dotted-child 400 and widen its gap list Review fixup for PR #7424 (relaunch, iteration 1, minors). - The OpenAPI spec now describes the wire change this PR makes. The dependencies:add and issues:batchApply 400 vocabularies name an edge from a dotted-id child to its own ancestor (anything but the parent-child edge to its immediate parent; param `edges` and `items`). dependencies:add says why that is request-intrinsic, and both 409s say it is never dependency_cycle or dependency_exists, even for a child whose parent-child edge is stored. Response descriptions only: the generated types and the wireshape digest are unchanged (make api-check). - The CheckDottedChildDependency doc no longer reads as a complete list of the writers that skip the rule. Besides bd relate and the create edges it names bd duplicate, bd supersede, bd duplicates --auto-merge (its related link and its reparenting) and the tracker engine's createDependencies, and says the molecule, template and swarm writers are unaudited. bd-25s1wh's notes carry the widened scope, including `bd duplicate bd-a.1 --of bd-a`. Declined (nit): unifying the root issueops import alias across the PR's cmd/bd files. batch.go is the one file that imports both issueops packages, so one of them needs an alias there; it uses publicops, the repo's usual alias for the root package, and aliasing the other side instead would rewrite base-owned lines. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
281 lines
13 KiB
Go
281 lines
13 KiB
Go
package issueops
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/storage/domain"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
publicops "github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
// ValidateAddDependenciesRequest applies the request rules every
|
|
// DependencyEditor implementation shares. It lives here rather than in each of
|
|
// them because a rule enforced on one backend and not the other is not a
|
|
// contract.
|
|
//
|
|
// The self-dependency refusal is here, ahead of the per-edge cycle probe and
|
|
// for EVERY edge type, for the reason the domain path states: a blocking
|
|
// self-edge otherwise trips the cycle check and reports the wrong refusal, and
|
|
// SkipPerEdgeCycleCheck would skip it entirely.
|
|
//
|
|
// The dotted-id hierarchy rule (publicops.CheckDottedChildDependency) is here
|
|
// for the same reason: it is decided from the request alone, and putting it in
|
|
// the shared validator is what makes every leg — dolt, embedded, the unit of
|
|
// work and the server behind httpapi — refuse a child gated on its own dotted
|
|
// parent, not only the CLI that used to check it before calling the role.
|
|
//
|
|
// The type check is that there IS a type — non-empty, within the column's
|
|
// length. It is deliberately not a membership test: the vocabulary is an open,
|
|
// workspace-configurable set (see the Dep* constants), so refusing an unlisted
|
|
// type would refuse a workspace's own.
|
|
func ValidateAddDependenciesRequest(request publicops.AddDependenciesRequest) error {
|
|
if request.Actor == "" {
|
|
return fmt.Errorf("%w: add dependencies requires an actor", storage.ErrValidation)
|
|
}
|
|
if len(request.Edges) == 0 {
|
|
return fmt.Errorf("%w: add dependencies requires at least one edge", storage.ErrValidation)
|
|
}
|
|
for i, edge := range request.Edges {
|
|
if edge.IssueID == "" || edge.DependsOnID == "" {
|
|
return fmt.Errorf("%w: add dependencies edge %d requires both endpoints", storage.ErrValidation, i)
|
|
}
|
|
if !edge.Type.IsValid() {
|
|
return fmt.Errorf("%w: add dependencies edge %d requires a dependency type (max %d chars)",
|
|
storage.ErrValidation, i, types.MaxDependencyTypeLen)
|
|
}
|
|
if edge.IssueID == edge.DependsOnID {
|
|
return fmt.Errorf("%w: %s cannot depend on itself", domain.ErrSelfDependency, edge.IssueID)
|
|
}
|
|
if err := publicops.CheckDottedChildDependency(edge.IssueID, edge.DependsOnID, edge.Type); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ValidateRemoveDependencyRequest applies the request rules every
|
|
// DependencyEditor implementation shares for a removal.
|
|
func ValidateRemoveDependencyRequest(request publicops.RemoveDependencyRequest) error {
|
|
if request.Actor == "" {
|
|
return fmt.Errorf("%w: remove dependency requires an actor", storage.ErrValidation)
|
|
}
|
|
if request.IssueID == "" || request.DependsOnID == "" {
|
|
return fmt.Errorf("%w: remove dependency requires both endpoints", storage.ErrValidation)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// AddDependenciesCommitMessage is the history entry an edge assertion records.
|
|
//
|
|
// Unlike CloseBatchCommitMessage it is composed from the REQUEST rather than
|
|
// the result, and that difference is the contract's: the request is
|
|
// all-or-nothing, so what was asked for is exactly what landed or nothing did.
|
|
// A batch close has to name what landed because it can skip an id; this cannot.
|
|
//
|
|
// The two spellings are the two the CLI already wrote — one edge names both
|
|
// endpoints, several name their count — because the role is what both `bd dep
|
|
// add <a> <b>` and `bd dep add --file` now go through, and `bd dolt log` should
|
|
// keep reading the way it did. The count spelling is keyed on the EDGE COUNT
|
|
// and not on which flag was used, so a one-line bulk file now names its edge
|
|
// instead of reading "add 1 edges": one edge is one edge however it was
|
|
// spelled.
|
|
func AddDependenciesCommitMessage(request publicops.AddDependenciesRequest) string {
|
|
if len(request.Edges) == 1 {
|
|
return "bd: dep add " + request.Edges[0].IssueID + " " + request.Edges[0].DependsOnID
|
|
}
|
|
return fmt.Sprintf("dependency: add %d edges", len(request.Edges))
|
|
}
|
|
|
|
// RemoveDependencyCommitMessage is the history entry a removal records.
|
|
func RemoveDependencyCommitMessage(issueID, dependsOnID string) string {
|
|
return "bd: dep remove " + issueID + " " + dependsOnID
|
|
}
|
|
|
|
// ExecuteAddDependencies asserts every requested edge in tx and reports the
|
|
// durable tables changed. It is the store-backed body behind the
|
|
// DependencyEditor accessor; the unit-of-work provider has its own, for the
|
|
// reason Lifecycle does.
|
|
//
|
|
// ALL-OR-NOTHING is enforced by doing nothing special: the first refusal
|
|
// returns an error, and the caller's transaction rolls every earlier edge back
|
|
// with it. There is no per-edge outcome to report because there is no outcome
|
|
// but the request's.
|
|
//
|
|
// Edges are applied PARENT-CHILD FIRST regardless of request order, so the
|
|
// complete planned hierarchy is visible before any blocking edge is validated
|
|
// against it — an ordering the direct bulk path already relies on. The
|
|
// whole-graph gate at the end runs even when the per-edge probe was skipped:
|
|
// per-edge checks cannot see a path that only exists once several of this
|
|
// request's own edges are in place.
|
|
//
|
|
// Both orderings hold ACROSS THE TWO PLANES, not within each: a request may
|
|
// mix wisp-sourced and issue-sourced edges, and the hierarchy a blocking edge
|
|
// is validated against, like the graph the final gate walks, spans both
|
|
// tables. That is why the phase loop and the gate are over the whole request
|
|
// and the plane is decided per edge, one level down.
|
|
func ExecuteAddDependencies(ctx context.Context, tx *sql.Tx, request publicops.AddDependenciesRequest) (publicops.AddDependenciesResult, ChangedTables, error) {
|
|
// One scoped query for the whole request instead of a probe per edge: a
|
|
// bulk `bd dep add --file` against a remote Dolt pays WAN latency per
|
|
// round-trip (GH#3414). Nothing an edge write does moves a source between
|
|
// planes, so a set read once up front stays true for the transaction.
|
|
sources := make([]string, 0, len(request.Edges))
|
|
for _, edge := range request.Edges {
|
|
sources = append(sources, edge.IssueID)
|
|
}
|
|
wispSources, err := WispIDSetInTx(ctx, tx, sources)
|
|
if err != nil {
|
|
return publicops.AddDependenciesResult{}, nil, err
|
|
}
|
|
|
|
tables := ChangedTables{}
|
|
for phase := 0; phase < 2; phase++ {
|
|
parentPhase := phase == 0
|
|
for _, edge := range request.Edges {
|
|
if (edge.Type == types.DepParentChild) != parentPhase {
|
|
continue
|
|
}
|
|
_, sourceIsWisp := wispSources[edge.IssueID]
|
|
edgeTables, err := addDependencyEdgeInTx(ctx, tx, request, edge, sourceIsWisp)
|
|
if err != nil {
|
|
return publicops.AddDependenciesResult{}, nil, err
|
|
}
|
|
tables.Merge(edgeTables)
|
|
}
|
|
}
|
|
if err := checkAddedEdgesForCycles(ctx, tx, request.Edges); err != nil {
|
|
return publicops.AddDependenciesResult{}, nil, err
|
|
}
|
|
added := make([]publicops.DependencyEdge, len(request.Edges))
|
|
copy(added, request.Edges)
|
|
return publicops.AddDependenciesResult{Added: added}, tables, nil
|
|
}
|
|
|
|
// addDependencyEdgeInTx writes one edge and reports the durable tables it
|
|
// touched.
|
|
//
|
|
// The edge FOLLOWS ITS SOURCE, the same rule the removal reads and the same
|
|
// one the stores' own dependency verb applied before this role existed: a wisp
|
|
// has no row in the issues plane, so pinning the source there refused every
|
|
// `bd dep add <wisp-id> <target>` with "issue not found". Source class decides
|
|
// the dependency table and, with it, the event table. The target's routing
|
|
// stays independently detected: either class may legitimately depend on the
|
|
// other.
|
|
//
|
|
// Refusals pass through UNWRAPPED. Every one of them —
|
|
// *DependencyTypeConflictError, *DependencyHierarchyConflictError,
|
|
// ErrDependencyCycle, a missing endpoint — is already a complete sentence, and
|
|
// the store's own dependency verb has always surfaced them verbatim.
|
|
func addDependencyEdgeInTx(ctx context.Context, tx *sql.Tx, request publicops.AddDependenciesRequest, edge publicops.DependencyEdge, sourceIsWisp bool) (ChangedTables, error) {
|
|
sourceTable, _, eventTable, depTable := WispTableRouting(sourceIsWisp)
|
|
|
|
dep := &types.Dependency{IssueID: edge.IssueID, DependsOnID: edge.DependsOnID, Type: edge.Type}
|
|
eventWritten, err := AddDependencyInTx(ctx, tx, dep, request.Actor, AddDependencyOpts{
|
|
SourceTable: sourceTable,
|
|
WriteTable: depTable,
|
|
IsCrossPrefix: types.ExtractPrefix(edge.IssueID) != types.ExtractPrefix(edge.DependsOnID),
|
|
SkipCycleCheck: request.SkipPerEdgeCycleCheck,
|
|
EmitEvent: true,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// The edge's referencing (source) issue is versioned by AddDependencyInTx
|
|
// itself, at the row write — once, and only for a genuinely inserted row
|
|
// (the idempotent re-add mints nothing, the same exemption eventWritten
|
|
// draws for the events table below) — so every leg that reaches that
|
|
// helper versions identically and this role adds no second mint.
|
|
// Stage the source's dependency table always and its events table only
|
|
// when a row was recorded — the same selective staging the stores' own
|
|
// AddDependencyWithOptions does, so an idempotent re-add cannot sweep
|
|
// unrelated pending event rows into this commit (GH#2455). Naming the
|
|
// source's own pair rather than the durable pair is what keeps that true
|
|
// across the planes: ChangedTables drops the wisp tables itself, so a
|
|
// wisp-sourced edge stages nothing and a request made entirely of them
|
|
// commits nothing, which is right — the wisp plane is dolt-ignored and has
|
|
// no version history to write.
|
|
//
|
|
// This is NOT every table the edge wrote. A blocking edge also flips the
|
|
// source's is_blocked (markDirectBlockingDependencySourceInTx, then
|
|
// MarkIsBlockedInTx over the affected ids), and neither `issues` nor any
|
|
// other issue-plane table is ever staged here. On an issue-sourced
|
|
// blocking add the flip therefore stays in the working set and is swept up
|
|
// by whatever command auto-commits next — including one that was REFUSED,
|
|
// which then shows up in history having changed nothing of its own. That
|
|
// predates this role: origin/main's dolt.AddDependencyWithOptions staged
|
|
// the same {dependencies, events} pair. Tracked as bd-2y9ke; fixing it
|
|
// changes what every dep-add commit contains and belongs in its own change
|
|
// with its own tests, so do not widen the set here without reading that
|
|
// bead first.
|
|
tables := ChangedTables{}
|
|
tables.Add(depTable)
|
|
if eventWritten {
|
|
tables.Add(eventTable)
|
|
}
|
|
return tables, nil
|
|
}
|
|
|
|
// checkAddedEdgesForCycles runs the whole-graph gate over the scheduling edges
|
|
// this request added. Per-edge probes cannot see a path that only closes once
|
|
// several of the request's own edges exist, and SkipPerEdgeCycleCheck turns
|
|
// them off entirely, so this is the check that actually holds the invariant.
|
|
//
|
|
// The message is built through domain.NewCycleError so it errors.Is-matches
|
|
// ErrDependencyCycle while rendering byte-for-byte what the direct bulk path
|
|
// already prints.
|
|
func checkAddedEdgesForCycles(ctx context.Context, tx *sql.Tx, edges []publicops.DependencyEdge) error {
|
|
var pairs [][2]string
|
|
for _, edge := range edges {
|
|
if !types.IsSchedulingEdge(edge.Type) {
|
|
continue
|
|
}
|
|
pairs = append(pairs, [2]string{edge.IssueID, edge.DependsOnID})
|
|
}
|
|
if len(pairs) == 0 {
|
|
return nil
|
|
}
|
|
graph := make(map[string][]string)
|
|
if err := AppendSchedulingGraphInTx(ctx, tx, cycleDetectionTables(), graph); err != nil {
|
|
return fmt.Errorf("final cycle check failed (no edges added): %w", err)
|
|
}
|
|
if cyclePath := CycleThroughEdgesInGraph(graph, pairs); cyclePath != "" {
|
|
return domain.NewCycleError("dependency cycle would be created: %s (no edges added; run 'bd dep cycles' for analysis)", cyclePath)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ExecuteRemoveDependency removes one edge in tx and reports the durable
|
|
// tables changed.
|
|
//
|
|
// A missing edge reports Removed false and NO changed tables, which is how the
|
|
// callers spell "commit nothing": removing an edge that was never there leaves
|
|
// the graph it already had, and a history entry for it would be a commit with
|
|
// nothing in it.
|
|
func ExecuteRemoveDependency(ctx context.Context, tx *sql.Tx, request publicops.RemoveDependencyRequest) (publicops.RemoveDependencyResult, ChangedTables, error) {
|
|
// Routing is READ here rather than pinned, unlike the add. A removal
|
|
// cannot put an edge anywhere, so pinning it would only mean failing to
|
|
// remove an edge the caller named — and the staging has to name the tables
|
|
// the delete actually touched or the commit sweeps rows it never wrote
|
|
// (GH#2455). ChangedTables drops the wisp tables itself.
|
|
sourceIsWisp := IsActiveWispInTx(ctx, tx, request.IssueID)
|
|
_, _, eventTable, depTable := WispTableRouting(sourceIsWisp)
|
|
|
|
// RemoveDependencyInTx reports whether it recorded an event, which on the
|
|
// explicit-verb path is exactly "an edge was there and is gone" — it
|
|
// returns early without emitting when no row matched.
|
|
eventWritten, err := RemoveDependencyInTx(ctx, tx, request.IssueID, request.DependsOnID, request.Actor, true)
|
|
if err != nil {
|
|
return publicops.RemoveDependencyResult{}, nil, err
|
|
}
|
|
if !eventWritten {
|
|
return publicops.RemoveDependencyResult{Removed: false}, nil, nil
|
|
}
|
|
// A removal that actually happened versioned the referencing issue inside
|
|
// RemoveDependencyInTx, at the row delete; an absent edge returned above
|
|
// without ever reaching that seam.
|
|
tables := ChangedTables{}
|
|
tables.Add(depTable, eventTable)
|
|
return publicops.RemoveDependencyResult{Removed: true}, tables, nil
|
|
}
|