beads/cmd/bd/batch_proxied_server.go
Julian Knutsen d15958a5eb
fix(issueops): enforce the dotted-child dependency rule on every leg (#7424)
* 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>
2026-10-09 22:56:46 +00:00

221 lines
8.7 KiB
Go

package main
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/workapi"
)
// runBatchProxiedServer executes an already-parsed batch script in ONE
// proxied-server unit of work.
//
// The two modes divide exactly where the command's contract does. Parsing,
// validation, the dry-run echo, the empty-input no-op, the default commit
// message and every byte of output stay in batch.go and are shared: a batch
// script means the same thing whichever backend runs it, and a script rejected
// by the parser is rejected before either backend is reached. What is per-mode
// is the transaction primitive and the verbs the ops dispatch against —
// storage.Transaction there, the unit of work's use cases here.
//
// uow.RunTx is the analog of the classic `transact`: one transaction, one
// DOLT_COMMIT carrying the caller's message, and rollback of the WHOLE batch on
// the first failing line (the line is named in the error exactly as the classic
// path names it). RunTx additionally redoes the entire batch in a fresh unit of
// work when Dolt reports a serialization failure — the batch is re-executed
// against the winner's committed rows, never re-committed on a session the
// server already rolled back.
//
// NOT RunTxEphemeral: a batch writes versioned tables, and the ephemeral form
// commits without a Dolt commit (its whole point for the leases table), which
// would persist these writes while silently bypassing Dolt history.
func runBatchProxiedServer(ctx context.Context, ops []batchOp, commitMsg string) ([]batchOpResult, error) {
if uowProvider == nil {
return nil, HandleErrorRespectJSON("proxied-server UOW provider not initialized")
}
// Explicit commit point, like `transact` on the direct route: the commit
// carries the caller's message whatever dolt.auto-commit says (GH#4995).
ctx = explicitCommitPointContext(ctx)
return uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) ([]batchOpResult, string, error) {
// Built per attempt, not per call: a retried batch must report the
// results of the attempt that actually committed.
results := make([]batchOpResult, 0, len(ops))
for _, op := range ops {
res, rerr := runBatchOpUOW(ctx, uw, op)
if rerr != nil {
return nil, "", fmt.Errorf("line %d (%s): %w", op.line, op.raw, rerr)
}
results = append(results, res)
}
return results, commitMsg, nil
})
}
// runBatchOpUOW dispatches one parsed op against the unit of work, the proxied
// twin of runBatchOp's dispatch against storage.Transaction. Same grammar, same
// arity checks, same error strings, same per-op result — only the verb changes.
//
// Plane routing is explicit here because it has to be: the classic transaction
// methods route an id to the issues or wisps tables themselves, while the
// domain use cases expose the two planes as separate verbs. Every op that names
// an existing id resolves it through workapi.GetIssueOrWisp first (both planes,
// this transaction's own snapshot) and then calls the matching verb, so a batch
// line that touches a wisp touches the wisp tables on both backends.
func runBatchOpUOW(ctx context.Context, uw uow.UnitOfWork, op batchOp) (batchOpResult, error) {
actorName := getActor()
result := batchOpResult{Line: op.line, Op: op.cmd}
issues := uw.IssueUseCase()
switch op.cmd {
case "close":
if len(op.args) < 1 {
return result, fmt.Errorf("close requires <id>")
}
id := op.args[0]
reason := "Closed"
if len(op.args) > 1 {
reason = strings.Join(op.args[1:], " ")
}
resolved, isWisp, err := batchResolveOpTarget(ctx, uw, id)
if err != nil {
return result, err
}
// Deliberately the UNCHECKED close, matching the classic batch's
// issueops.CloseIssueInTx: `close <id>` in a batch does not apply close
// policy at all (the asymmetry with `update status=closed` is documented
// in the command's help and is contract, not oversight).
params := domain.CloseIssueParams{Reason: reason}
if isWisp {
_, err = issues.CloseWisp(ctx, resolved, params, actorName)
} else {
_, err = issues.CloseIssue(ctx, resolved, params, actorName)
}
if err != nil {
return result, err
}
result.Target = id
return result, nil
case "update":
if len(op.args) < 2 {
return result, fmt.Errorf("update requires <id> and at least one key=value")
}
id := op.args[0]
updates, err := parseUpdateKVs(op.args[1:])
if err != nil {
return result, err
}
resolved, isWisp, err := batchResolveOpTarget(ctx, uw, id)
if err != nil {
return result, err
}
if isWisp {
err = issues.UpdateWisp(ctx, resolved, updates, actorName)
} else {
err = issues.UpdateIssue(ctx, resolved, updates, actorName)
}
if err != nil {
return result, err
}
result.Target = id
return result, nil
case "create":
if len(op.args) < 3 {
return result, fmt.Errorf("create requires <type> <priority> <title>")
}
issueType := types.IssueType(op.args[0])
if strings.TrimSpace(op.args[0]) == "" {
return result, fmt.Errorf("create: type cannot be empty")
}
priority, err := strconv.Atoi(op.args[1])
if err != nil {
return result, fmt.Errorf("create: invalid priority %q: %w", op.args[1], err)
}
title := strings.Join(op.args[2:], " ")
if strings.TrimSpace(title) == "" {
return result, fmt.Errorf("create: title cannot be empty")
}
issue := &types.Issue{
Title: title,
IssueType: issueType,
Status: types.StatusOpen,
Priority: priority,
}
created, err := issues.CreateIssue(ctx, domain.CreateIssueParams{Issue: issue}, actorName)
if err != nil {
return result, err
}
// The classic path reports the id the store minted into the caller's
// struct; the use case hands the same row back as a result.
if created.Issue != nil {
result.Target = created.Issue.ID
} else {
result.Target = issue.ID
}
return result, nil
case "dep.add":
dep, err := batchDepAddEdge(op.args)
if err != nil {
return result, err
}
// AddDependencies (not the single-edge AddDependency) because it lands
// each edge in the plane its own SOURCE lives in, which is the routing
// the classic transaction does from isActiveWisp. One edge is still one
// edge, and the per-edge cycle probe runs.
//
// KNOWN DIVERGENCE, in the HISTORY only: every domain edge verb records
// a dependency_added event, while the classic batch reaches
// storage.Transaction.AddDependency, whose zero DependencyAddOptions
// leaves EmitEvent false — the "structural, quiet" setting meant for
// create-with-deps and reparenting, not for a verb a user typed. So a
// batched `dep add` shows up in `bd history` here and does not there.
// The edge itself, its plane, its type and the cycle verdict are
// identical; `bd dep add` at the CLI emits the event on BOTH backends,
// which is why the classic batch's silence reads as the outlier.
// Silencing it here would need a quiet variant on the use case that
// nothing else wants, so this port takes the event and names it rather
// than growing the domain surface to reproduce an inconsistency.
if _, err := uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, actorName, domain.BulkAddDepsOpts{}); err != nil {
return result, err
}
result.Target = fmt.Sprintf("%s->%s", dep.IssueID, dep.DependsOnID)
return result, nil
case "dep.remove":
if len(op.args) < 2 {
return result, fmt.Errorf("dep remove requires <from-id> <to-id>")
}
from, to := op.args[0], op.args[1]
// BySource for the same reason dep.add uses the bulk verb: the edge is
// removed from the plane its source lives in. A missing edge is not an
// error on either backend — the removal is idempotent, and a batch that
// re-runs must not roll back on an edge already gone. The
// dependency_removed event carries the same divergence, and the same
// reasoning, as the added one above.
if _, err := uw.DependencyUseCase().RemoveDependencyBySource(ctx, from, to, actorName); err != nil {
return result, err
}
result.Target = fmt.Sprintf("%s->%s", from, to)
return result, nil
}
return result, fmt.Errorf("internal: unhandled batch op %q", op.cmd)
}
// batchResolveOpTarget resolves an id an op names to the row it is about and
// the plane that row lives in, inside this transaction. A missing id is an
// error, which rolls the whole batch back — the same verdict the classic path
// reaches when its store call cannot find the row.
func batchResolveOpTarget(ctx context.Context, uw uow.UnitOfWork, id string) (string, bool, error) {
issue, isWisp, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), id)
if err != nil {
return "", false, err
}
return issue.ID, isWisp, nil
}