beads/internal/workapi/delete_test.go
Julian Knutsen 2c3a75d78c
Add DeleteRequest.ExpectedVersion: a compare-and-delete on the named row (#5481)
* Add DeleteRequest.ExpectedVersion: a compare-and-delete on the named row

`bd delete` is the one irreversible verb with no way to say "only if this
is still the row I looked at". Every other guarded write has one —
Lifecycle's Update, Close and Reopen all take an ExpectedVersion over the
same row_lock token — and the operation that most needs it is the one
where being wrong cannot be undone. A caller that reads a row, decides it
is finished with it, and deletes it has a window in which somebody else
reopened, reassigned or restarted the work; today the delete lands anyway.

The token is the ordinary one: server-minted, opaque, equality-only, nil
to disable, and read inside the deleting transaction so the pair is a
compare-and-delete rather than a read followed by a hopeful write.

TWO DECISIONS ARE WORTH THE REVIEW.

It requires a SINGLE-ID request, and a non-nil version beside more than
one distinct id is ErrValidation before anything is read. A row version
is per-row and the space is not shared, so one number checked against a
batch would pass a whole list of never-written rows by coincidence —
every one of them holds 0 — and fail forever for any list whose rows have
diverged. A guard that passes by coincidence and a guard nobody can
satisfy are the same defect from two sides. The shape a batch would need
is a token per ITEM, which BatchCloser.Items is, and this role is a list
of ids rather than a list of items; BatchCloseItem carries no version for
the same reason. Duplicates collapse first, so `bd delete a a` with a
token is one row and is legal.

It OUTRANKS the dependents guard and neither Force nor Cascade bypasses
it. A mismatch says the caller's whole view is stale, so reporting the
dependents refusal first would ask it to choose --cascade or --force over
information that has already moved; and force bypasses policy, never a
precondition, exactly as CloseRequest.Force does. It still ranks below
the existence probe: a request that named no row has nothing to be stale
about.

Two bodies, as ever. The store legs call the same CheckVersionInTx the
update and close guards use, on the transaction they delete in. The
unit-of-work leg compares the row its own existence probe already
loaded — the probe now keeps rows rather than a set of ids — which is
what updatePreconditionsHold does for the same token on the update path,
and avoids a second read of the same rows in the same unit of work.

Four contract cases on all three legs, written as a falsifiable pair: the
satisfied case takes the row's REAL token straight out of row_lock, on
both planes, so a body that refused every versioned delete reddens; the
stale case is the refusal, under DryRun too, with the rows counted raw
and the token asserted unmoved. The ranking case keeps a live outside
dependent on every arm, so "force did not bypass" is distinguishable from
"force was not needed", and ends on a matching-token force release so the
three refusals cannot be satisfied by a body that refuses unconditionally.
The arity case uses a token that MATCHES the first id, which is the only
arrangement that catches a body checking the first row and deleting the
list, and pairs it with the repeated-mention collapse so the rule cannot
be read as "expected-version deletes take one element".

FACADE ONLY. No wire, spec or httpapi change: the delete handler reads an
explicit member allowlist, so a new leaf field is invisible to clients
until the wire half follows in the conditional-update / release wire slice
per the program's council gating.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Review: pin existence-outranks-version, and say what the second SELECT buys

Three review items, one of which was a real hole.

THE HOLE: the leaf promises the version precondition ranks BELOW the
existence probe — "a request that named no row has nothing to be stale
about" — and nothing watched it. A second block on RefusesAnAbsentID does,
with a single absent id carrying a version.

It asserts the TYPE and not the sentinel, which is the whole point.
errors.Is(err, ErrNotFound) is satisfied by the WRONG order too: the store
legs run the guard through CheckVersionInTx, which answers a bare wrapped
ErrNotFound of its own for a row that is not there, so a flipped order
looks identical to a reader of the sentinel. Only *NotFoundError — which
nothing but the existence probe mints, and which carries the id — tells
them apart. The unit-of-work leg cannot answer at all: its comparison reads
the row the probe loaded, so a flipped order is a nil dereference.

Watched: moving the guard above the probe in the store body reddens it.

The other two are prose. workapi/delete.go cited `--expect-version`, a flag
that does not exist — the wire half is deferred — and now states the request
shape instead. And delete_role.go now says that CheckVersionInTx re-reads a
row the existence probe already returned, that what the second SELECT buys
is ONE definition of the guard shared with the update and close paths, and
that the unit-of-work leg answers the same trade the other way because the
shared function is not reachable from it — so the difference reads as a
consequence of where each leg sits rather than as drift.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 07:17:54 -07:00

113 lines
4.9 KiB
Go

package workapi
import (
"errors"
"reflect"
"testing"
"github.com/steveyegge/beads/issueops"
)
// The database-free half of issueops.Deleter, pinned in milliseconds. Every
// backend runs these functions, so a disagreement about what a malformed
// request means is caught here rather than three times over in conformance.
func TestValidateDeleteRequest(t *testing.T) {
for _, test := range []struct {
name string
request issueops.DeleteRequest
wantErr bool
}{
{"one id", issueops.DeleteRequest{IDs: []string{"bd-1"}}, false},
{"several ids", issueops.DeleteRequest{IDs: []string{"bd-1", "bd-2"}}, false},
{"untrimmed id is accepted and normalized later", issueops.DeleteRequest{IDs: []string{" bd-1 "}}, false},
{"nil ids", issueops.DeleteRequest{}, true},
{"empty ids", issueops.DeleteRequest{IDs: []string{}}, true},
{"blank id", issueops.DeleteRequest{IDs: []string{""}}, true},
{"whitespace id", issueops.DeleteRequest{IDs: []string{"\t "}}, true},
{"blank beside a real one", issueops.DeleteRequest{IDs: []string{"bd-1", " "}}, true},
{"expected version on one id", issueops.DeleteRequest{IDs: []string{"bd-1"}, ExpectedVersion: deleteVersion(7)}, false},
// DeleteRequest.ExpectedVersion counts DISTINCT ids, so the two rows
// below are the whole rule: a repeated mention still names one row.
{"expected version on a repeated id", issueops.DeleteRequest{IDs: []string{"bd-1", " bd-1 "}, ExpectedVersion: deleteVersion(7)}, false},
{"expected version on several ids", issueops.DeleteRequest{IDs: []string{"bd-1", "bd-2"}, ExpectedVersion: deleteVersion(7)}, true},
// Version 0 is a real expectation — a row nothing has written yet — so
// the pointer and not the value is what disables the check.
{"expected version zero on one id", issueops.DeleteRequest{IDs: []string{"bd-1"}, ExpectedVersion: deleteVersion(0)}, false},
{"expected version zero on several ids", issueops.DeleteRequest{IDs: []string{"bd-1", "bd-2"}, ExpectedVersion: deleteVersion(0)}, true},
// Without a version the multi-id request is the ordinary one, which is
// what keeps the new rule from reading as a general arity limit.
{"several ids without a version", issueops.DeleteRequest{IDs: []string{"bd-1", "bd-2"}}, false},
} {
t.Run(test.name, func(t *testing.T) {
err := ValidateDeleteRequest(test.request)
if test.wantErr {
if !errors.Is(err, issueops.ErrValidation) {
t.Fatalf("error = %v, want ErrValidation", err)
}
return
}
if err != nil {
t.Fatalf("error = %v, want nil", err)
}
})
}
}
// TestNormalizeDeleteIDs pins FIRST-MENTION order rather than sorted order. It
// is the order both front doors echo back — in "issues not found" and in the
// `--force` hint they print — so a caller re-reading its own `--from-file` list
// against that output should not have to re-sort it.
func TestNormalizeDeleteIDs(t *testing.T) {
for _, test := range []struct {
name string
in []string
want []string
}{
{"unchanged", []string{"bd-1", "bd-2"}, []string{"bd-1", "bd-2"}},
{"duplicates collapse to the first mention", []string{"bd-2", "bd-1", "bd-2"}, []string{"bd-2", "bd-1"}},
{"whitespace is trimmed before comparing", []string{" bd-1", "bd-1 "}, []string{"bd-1"}},
{"order is not sorted", []string{"bd-z", "bd-a"}, []string{"bd-z", "bd-a"}},
} {
t.Run(test.name, func(t *testing.T) {
if got := NormalizeDeleteIDs(test.in); !reflect.DeepEqual(got, test.want) {
t.Errorf("NormalizeDeleteIDs(%v) = %v, want %v", test.in, got, test.want)
}
})
}
}
// TestNormalizeDeleteIDsDoesNotMutateTheCaller is the pin behind
// issueops.DeleteRequest's "IDs is read, never written through": normalizing in
// place is the most natural way to write this function and would hand the
// caller back a shorter, reordered version of its own slice.
func TestNormalizeDeleteIDsDoesNotMutateTheCaller(t *testing.T) {
in := []string{" bd-2 ", "bd-1", "bd-2"}
snapshot := append([]string(nil), in...)
NormalizeDeleteIDs(in)
if !reflect.DeepEqual(in, snapshot) {
t.Errorf("caller's slice changed: got %v, want %v", in, snapshot)
}
}
// TestSortedDeleteIDs pins the ascending order DeleteResult.Orphaned and
// DependentsOutsideRequestError.Dependents promise. Both are collected out of
// maps, so without this they would publish Go's map order and a caller
// diffing two runs would see spurious changes.
func TestSortedDeleteIDs(t *testing.T) {
if got := SortedDeleteIDs(nil); got != nil {
t.Errorf("SortedDeleteIDs(nil) = %v, want nil", got)
}
if got := SortedDeleteIDs(map[string]bool{}); got != nil {
t.Errorf("SortedDeleteIDs(empty) = %v, want nil", got)
}
got := SortedDeleteIDs(map[string]bool{"bd-c": true, "bd-a": true, "bd-b": true})
if want := []string{"bd-a", "bd-b", "bd-c"}; !reflect.DeepEqual(got, want) {
t.Errorf("SortedDeleteIDs() = %v, want %v", got, want)
}
}
// deleteVersion is the one-line address-of a table row cannot spell inline.
func deleteVersion(v int64) *int64 { return &v }