beads/cmd/bd/delete_test.go
CI Bot cf0a42cdae feat(delete): put bd delete behind the Deleter role and converge both routes (bd-x82so)
THE TWO ROUTES DISAGREED ABOUT WHAT --force MEANS on a destructive command.
On a local database `--force` deletes the named beads and orphans their
dependents; on a team server it deleted the whole dependent subtree, `--cascade`
was REFUSED outright ("not supported in proxied-server mode (delete always
cascades)") and Cascade was hardcoded true at both call sites. So there was no
way to delete one bead on a team server without taking everything under it, and
asking for the safer behaviour was an error.

Q1 ANSWERED IN THE ROLE. issueops.Deleter has one method, reached through
store.Deleter() and the provider's own accessor, and the three modes are request
fields: no flags refuses over a dependent the request did not name, Force
orphans it, Cascade deletes the closure. The guard is workapi's and the body's,
below every front door, for the reason Sweeper's require-a-filter gate is: a
second front door that inherited the capability without the guard would orphan a
workspace's graph by omission — which is exactly what this commit's HTTP
operation would otherwise have been.

IT IS A DIFFERENT ROLE FROM Sweeper, not a mode of it. Sweeper erases a set the
caller DESCRIBED; this erases rows the caller NAMED. That is what decides where
each one's safety lives: a description can be accidentally too wide, so Sweeper
carries a require-a-filter refusal; a list of ids cannot be, so this one's guard
is about the graph.

THE DEFECT. The direct route's batch path deleted the rows in one transaction
and then rewrote `[deleted:ID]` into the neighbours' text afterwards, discarding
every update error. A failure in the window left a workspace whose beads were
gone and whose descriptions still cited them by id. The existence probe, the
guard, the cascade expansion, the deletion and the rewrite are now one
transaction. WHAT THAT COSTS is written into the leaf beside the promise: the
transaction is as large as the deletion plus its neighbourhood, so a batch with
a very large neighbourhood fails whole. It is NOT Sweeper's trade (bd-hysee) —
the delete itself was already one transaction on every route — and the part that
is new is named rather than measured, which is recorded for sign-off.

TWO MORE DEFECTS the single call site removed. The one-id path held its own
transaction that removed each edge by hand, so it never reported labels, events
or orphans; and `domain.DeleteIssuesParams.EnforceCascadePolicy` and `.Force`
were declared, documented in fifteen lines describing exactly these three modes,
and READ BY NOTHING. They are deleted; the policy lives in the role now.

THE CONTRACT IS WHAT WAS DELETED, not what was reported.
backend/conformance/deleter_contract.go holds eleven cases, each citing the leaf
doc, run at all three backends with ZERO PARKS and zero divergences. Every case
that acts asserts row counts through QueryScalar rather than trusting the result
the delete reported about itself. They are TWO INDEPENDENT BODIES plus an engine
check: dolt and embeddeddolt share internal/storage/issueops.DeleteInTx and
differ only in how they reach a transaction, and the unit-of-work provider
reaches the same questions through the domain use cases. It does NOT duplicate
backend/conformance/audit_issue-lifecycle.go, which stays the right home for
`DeleteIssues` at the STORAGE seam: that suite's Factory hands back a bare
storage.DoltStorage, so the unit-of-work backend — where the guard did not exist
at all before this commit — can never run a case placed there.

`bd serve` gains POST /v0/beads/issues:delete, spec first. The dependents guard,
the all-or-nothing id resolution and the reference rewrite are the role's, so
the handler is argument validation and a projection. `cascade` and `force`
default false, which is the guarded mode; DeleteIssuesResult is not
x-go-type-pinned for the reason SweepResult is not, and a reflection test keeps
the projection honest. No page envelope, so nothing to pin in pinning.go.

USER-VISIBLE, and the CHANGELOG says so loudly: a team-server script relying on
the implicit cascade starts leaving orphans; `bd delete <one-id>` without
--force now refuses over an outside dependent, converging the direct route's
three paths onto the answer two of them already gave; the proxied `--json`
result gains `orphaned_issues`. Reasoning and the alternatives are in
/data/tmp/sd-server/AMBIGUITIES.md as A-del-1..6.

Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
(regenerate-and-diff plus the httpapi suite) green; TestDeleterContract 11/11 at
dolt, embeddeddolt and uow; the internal/workapi delete unit tests; the
internal/storage, internal/telemetry and root layering pins;
TestConformance/Audit/issue-lifecycle and the dolt TestDeleteIssues* family
(this commit refactors DeleteIssuesInTx's guard); TestEmbeddedDelete,
TestEmbeddedDeleteJSONDependencyErrorContract, TestBurnWisps,
TestWispGCProtectsActiveWisps and TestCLI_WispGCExcludeType under
BEADS_TEST_EMBEDDED_DOLT=1; TestProxiedServerDelete{,ForceOrphans,Wisp,
Concurrent}, TestProxiedServerMolBurn and TestProxiedServerWispGC under
BEADS_TEST_PROXIED_SERVER=1; and TestProxiedLookup*.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-06 02:59:08 +00:00

333 lines
9 KiB
Go

//go:build cgo && integration
// +build cgo,integration
package main
import (
"context"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
func TestDeletePreviewJSONIsPayloadBlind(t *testing.T) {
ensureCleanGlobalState(t)
oldQuiet := quietFlag
quietFlag = false
t.Cleanup(func() { quietFlag = oldQuiet })
issues := map[string]*types.Issue{
"test-delete-1": {
ID: "test-delete-1",
Title: "sensitive title must not appear",
Description: "sensitive payload must not appear",
},
}
result := &issueops.DeleteResult{Deleted: 1, Dependencies: 2}
out := captureStdout(t, func() error {
return outputDeletionPreview([]string{"test-delete-1"}, issues, false, true, result, nil, true)
})
for _, secret := range []string{"sensitive title", "sensitive payload"} {
if strings.Contains(out, secret) {
t.Fatalf("JSON preview leaked %q: %s", secret, out)
}
}
for _, required := range []string{"\"issue_ids\"", "\"would_delete\"", "\"dry_run\""} {
if !strings.Contains(out, required) {
t.Errorf("JSON preview missing %s: %s", required, out)
}
}
quietFlag = true
quietOut := captureStdout(t, func() error {
return outputDeletionPreview([]string{"test-delete-1"}, issues, false, true, result, nil, false)
})
if quietOut != "" {
t.Fatalf("quiet preview produced output: %s", quietOut)
}
}
func TestDeleteBatchDryRunHonorsForce(t *testing.T) {
tmpDir := t.TempDir()
s := newTestStore(t, filepath.Join(tmpDir, ".beads", "beads.db"))
ctx := context.Background()
parent := &types.Issue{Title: "parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
child := &types.Issue{Title: "child", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := s.CreateIssue(ctx, parent, "test"); err != nil {
t.Fatalf("create parent: %v", err)
}
if err := s.CreateIssue(ctx, child, "test"); err != nil {
t.Fatalf("create child: %v", err)
}
if err := s.AddDependency(ctx, &types.Dependency{IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepBlocks}, "test"); err != nil {
t.Fatalf("add dependency: %v", err)
}
oldStore, oldRootCtx, oldJSON, oldQuiet := store, rootCtx, jsonOutput, quietFlag
store, rootCtx, jsonOutput, quietFlag = s, ctx, false, true
t.Cleanup(func() { store, rootCtx, jsonOutput, quietFlag = oldStore, oldRootCtx, oldJSON, oldQuiet })
if err := deleteBatch(nil, []string{parent.ID}, true, true, false, false, false); err != nil {
t.Fatalf("forced dry-run rejected a dependent issue: %v", err)
}
if issue, err := s.GetIssue(ctx, parent.ID); err != nil || issue == nil {
t.Fatalf("forced dry-run deleted parent: issue=%v err=%v", issue, err)
}
if issue, err := s.GetIssue(ctx, child.ID); err != nil || issue == nil {
t.Fatalf("forced dry-run deleted child: issue=%v err=%v", issue, err)
}
deps, err := s.GetDependencies(ctx, child.ID)
if err != nil {
t.Fatalf("get dependencies after dry-run: %v", err)
}
if len(deps) != 1 {
t.Fatalf("forced dry-run changed dependencies: got %d, want 1", len(deps))
}
}
func TestBulkDeleteNoResurrection(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
testDB := filepath.Join(beadsDir, "beads.db")
testGitInit(t, tmpDir)
s := newTestStore(t, testDB)
ctx := context.Background()
totalIssues := 20
toDeleteCount := 10
var toDelete []string
for i := 1; i <= totalIssues; i++ {
issue := &types.Issue{
Title: "Issue " + string(rune('A'+i-1)),
Description: "Test issue",
Status: types.StatusOpen,
Priority: 2,
IssueType: "task",
}
if err := s.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatalf("Failed to create issue %d: %v", i, err)
}
if i <= toDeleteCount {
toDelete = append(toDelete, issue.ID)
}
}
oldStore := store
oldDbPath := dbPath
defer func() {
store = oldStore
dbPath = oldDbPath
}()
store = s
dbPath = testDB
result, err := s.DeleteIssues(ctx, toDelete, false, true, false)
if err != nil {
t.Fatalf("DeleteIssues failed: %v", err)
}
if result.DeletedCount != toDeleteCount {
t.Errorf("Expected %d deletions, got %d", toDeleteCount, result.DeletedCount)
}
stats, err := s.GetStatistics(ctx)
if err != nil {
t.Fatalf("GetStatistics failed: %v", err)
}
expectedRemaining := totalIssues - toDeleteCount
if stats.TotalIssues != expectedRemaining {
t.Errorf("After delete: expected %d issues in DB, got %d", expectedRemaining, stats.TotalIssues)
}
for _, id := range toDelete {
issue, err := s.GetIssue(ctx, id)
if err != nil {
t.Fatalf("GetIssue failed for %s: %v", id, err)
}
if issue != nil {
t.Errorf("Deleted issue %s was resurrected!", id)
}
}
}
func testGitInit(t *testing.T, dir string) {
t.Helper()
testGitCmd(t, dir, "init")
testGitCmd(t, dir, "config", "user.email", "test@example.com")
testGitCmd(t, dir, "config", "user.name", "Test User")
}
func testGitCmd(t *testing.T, dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v failed: %v\nOutput: %s", args, err, output)
}
}
// TestDeleteIssueWrapper tests the deleteIssue wrapper function
func TestDeleteIssueWrapper(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
testDB := filepath.Join(beadsDir, "beads.db")
s := newTestStore(t, testDB)
ctx := context.Background()
// Save and restore global store
oldStore := store
defer func() { store = oldStore }()
store = s
t.Run("successful issue deletion", func(t *testing.T) {
issue := &types.Issue{
Title: "Issue to delete",
Description: "Will be permanently deleted",
Status: types.StatusOpen,
Priority: 2,
IssueType: "task",
}
if err := s.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatalf("Failed to create issue: %v", err)
}
err := deleteIssue(ctx, issue.ID)
if err != nil {
t.Fatalf("deleteIssue failed: %v", err)
}
// Verify issue is gone
deleted, err := s.GetIssue(ctx, issue.ID)
if err != nil {
t.Fatalf("GetIssue failed: %v", err)
}
if deleted != nil {
t.Error("Issue should be completely deleted")
}
})
t.Run("error on non-existent issue", func(t *testing.T) {
err := deleteIssue(ctx, "nonexistent-issue-id")
if err == nil {
t.Error("Expected error for non-existent issue")
}
})
t.Run("verify dependencies are removed", func(t *testing.T) {
// Create two issues with a dependency
issue1 := &types.Issue{
Title: "Blocker issue",
Status: types.StatusOpen,
Priority: 1,
IssueType: "task",
}
issue2 := &types.Issue{
Title: "Dependent issue",
Status: types.StatusOpen,
Priority: 2,
IssueType: "task",
}
if err := s.CreateIssue(ctx, issue1, "test"); err != nil {
t.Fatalf("Failed to create issue1: %v", err)
}
if err := s.CreateIssue(ctx, issue2, "test"); err != nil {
t.Fatalf("Failed to create issue2: %v", err)
}
// Add dependency: issue2 depends on issue1
dep := &types.Dependency{
IssueID: issue2.ID,
DependsOnID: issue1.ID,
Type: types.DepBlocks,
}
if err := s.AddDependency(ctx, dep, "test"); err != nil {
t.Fatalf("Failed to add dependency: %v", err)
}
// Delete issue1 (the blocker)
err := deleteIssue(ctx, issue1.ID)
if err != nil {
t.Fatalf("deleteIssue failed: %v", err)
}
// Verify issue2 no longer has dependencies
deps, err := s.GetDependencies(ctx, issue2.ID)
if err != nil {
t.Fatalf("GetDependencies failed: %v", err)
}
if len(deps) > 0 {
t.Errorf("Expected no dependencies after deleting blocker, got %d", len(deps))
}
})
t.Run("verify issue removed from database", func(t *testing.T) {
issue := &types.Issue{
Title: "Verify removal",
Status: types.StatusOpen,
Priority: 2,
IssueType: "task",
}
if err := s.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatalf("Failed to create issue: %v", err)
}
// Get statistics before delete
statsBefore, err := s.GetStatistics(ctx)
if err != nil {
t.Fatalf("GetStatistics failed: %v", err)
}
err = deleteIssue(ctx, issue.ID)
if err != nil {
t.Fatalf("deleteIssue failed: %v", err)
}
// Get statistics after delete
statsAfter, err := s.GetStatistics(ctx)
if err != nil {
t.Fatalf("GetStatistics failed: %v", err)
}
if statsAfter.TotalIssues != statsBefore.TotalIssues-1 {
t.Errorf("Expected total issues to decrease by 1, was %d now %d",
statsBefore.TotalIssues, statsAfter.TotalIssues)
}
})
}
func TestDeleteIssueUnsupportedStorage(t *testing.T) {
if testDoltServerPort == 0 {
t.Skip("skipping: Dolt test container not available")
}
oldStore := store
defer func() { store = oldStore }()
// Set store to nil - the type assertion will fail
store = nil
ctx := context.Background()
err := deleteIssue(ctx, "any-id")
if err == nil {
t.Error("Expected error when storage is nil")
}
expectedMsg := "delete operation not supported by this storage backend"
if err.Error() != expectedMsg {
t.Errorf("Expected error %q, got %q", expectedMsg, err.Error())
}
}