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>
This commit is contained in:
Julian Knutsen 2026-08-09 07:17:54 -07:00 • committed by GitHub
commit 2c3a75d78c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 505 additions and 9 deletions

View file

@ -28,7 +28,19 @@ import (
// guard and the dry-run counts at the STORAGE SEAM, and cannot see the role at
// all. The cases below are the promises the ROLE adds on top of it: id
// normalization, the ordered refusals, the typed errors, the reference rewrite
// inside the transaction, and the history entry.
// inside the transaction, the history entry, and the ExpectedVersion
// precondition.
//
// ONE PROMISE ABOUT ExpectedVersion IS STRUCTURAL RATHER THAN OBSERVABLE, and
// the four version cases say so here instead of faking it: the leaf promises
// the version read shares the deleting transaction, and a single-threaded case
// cannot tell one transaction from two when nothing else is writing. What holds
// it is the SHAPE of the bodies — the store legs call CheckVersionInTx on the
// transaction they delete in, and the unit-of-work leg compares a row its own
// existence probe loaded inside the same unit of work — so there is no
// two-call composition to regress into. A concurrent case would be flaky at
// three engines and buy a suite people re-run rather than a guarantee. What
// would upgrade it is a transaction-counting seam on the fixture kit.
//
// EVERY CASE NAMESPACES ITS SEEDS with fixture.IssuePrefix and its own tag: the
// three wirings share one database across the whole role suite, and a delete
@ -116,6 +128,21 @@ func RunDeleterRefusesAMalformedRequest(t *testing.T, ctx context.Context, fixtu
// arrangement that can fail: an implementation that deleted as it resolved
// would pass a single-absent-id case perfectly. And under DryRun too, because a
// preview that succeeded here would tell a caller to go ahead.
//
// THE SECOND BLOCK PINS THE ORDER AGAINST ExpectedVersion, which is the one
// boundary the leaf promises and nothing else here watches: "it ranks BELOW the
// existence probe ... a request that named no row has nothing to be stale
// about" (Deleter.Delete). It is a SINGLE absent id, because a version request
// may not name two.
//
// IT ASSERTS THE TYPE, NOT THE SENTINEL, and that is the whole point of the
// block. errors.Is(err, ErrNotFound) is satisfied by the WRONG order too: the
// store legs run the version guard through CheckVersionInTx, which answers a
// bare wrapped ErrNotFound of its own for a row that is not there. Only
// *NotFoundError — which nothing but the existence probe mints, and which
// carries the id — tells the two apart. The uow leg cannot even answer: its
// version comparison reads the row the probe loaded, so a flipped order is a
// nil dereference rather than a wrong error.
func RunDeleterRefusesAnAbsentID(t *testing.T, ctx context.Context, fixture DeleterFixture) {
t.Helper()
stored := deleterSeedIssue(t, ctx, fixture, "gone", "real")
@ -142,6 +169,34 @@ func RunDeleterRefusesAnAbsentID(t *testing.T, ctx context.Context, fixture Dele
}
deleterAssertIssueRows(t, ctx, fixture, 1, stored)
}
// The version the request carries is deliberately a plausible one rather
// than a sentinel: the subject is WHICH refusal comes back, so a token that
// looked obviously wrong would leave a reader unsure whether the existence
// probe won or the guard simply had nothing to compare.
version := int64(0)
for _, dryRun := range []bool{false, true} {
result, err := fixture.Deleter.Delete(ctx, publicops.DeleteRequest{
IDs: []string{absent},
Force: true,
ExpectedVersion: &version,
DryRun: dryRun,
})
var notFound *publicops.NotFoundError
if !errors.As(err, &notFound) {
t.Fatalf("Delete(dryRun=%v) of an absent id with a version error = %v, want *NotFoundError — the existence probe outranks the version guard",
dryRun, err)
}
if errors.Is(err, publicops.ErrVersionMismatch) {
t.Errorf("Delete(dryRun=%v) answered the version guard over an id that names no row", dryRun)
}
if !reflect.DeepEqual(notFound.IDs, []string{absent}) {
t.Errorf("NotFoundError.IDs = %v, want [%s]", notFound.IDs, absent)
}
if result.Deleted != 0 {
t.Errorf("refused delete reported Deleted = %d, want 0", result.Deleted)
}
}
}
// RunDeleterRefusesDependentsOutsideTheRequest pins the guard this role took
@ -926,6 +981,244 @@ func RunDeleterSettlesTheSurvivorsOfADeletedWispBlocker(t *testing.T, ctx contex
"a survivor whose only blocker was an erased WISP is left unblocked, in both planes, and so is everything that inherited from it")
}
// RunDeleterDeletesOnAMatchingExpectedVersion is the SATISFIED half of the
// version precondition (issueops/deleter.go, DeleteRequest.ExpectedVersion:
// "the deletion proceeds only if that row's current RowVersion ... still equals
// *ExpectedVersion").
//
// It is written first and cited by the refusal cases below because a
// refusal-only pair is half a test: a body that refused every versioned request
// would satisfy each of them and fail nothing. The token here is the row's REAL
// one, read raw out of row_lock — not a sentinel — so this is also the case
// that says the value a caller reads off a row is a value the delete accepts.
//
// BOTH PLANES, because the precondition has to route the version read the way
// the deletion routes the erasure. A guard that always looked in `issues` would
// answer ErrNotFound for a wisp whose row is perfectly present, and the durable
// arm alone cannot see that.
func RunDeleterDeletesOnAMatchingExpectedVersion(t *testing.T, ctx context.Context, fixture DeleterFixture) {
t.Helper()
for _, plane := range []struct {
name string
table string
seed func(*testing.T, context.Context, DeleterFixture, string, string) string
assertRows func(*testing.T, context.Context, DeleterFixture, int, ...string)
}{
{"durable", "issues", deleterSeedIssue, deleterAssertIssueRows},
{"ephemeral", "wisps", deleterSeedWisp, deleterAssertWispRows},
} {
t.Run(plane.name, func(t *testing.T) {
id := plane.seed(t, ctx, fixture, "version-match", plane.name)
version := deleterRowVersion(t, ctx, fixture, plane.table, id)
result := deleterDelete(t, ctx, fixture, publicops.DeleteRequest{
IDs: []string{id},
Actor: "deleter-contract",
ExpectedVersion: &version,
})
if result.Deleted != 1 {
t.Errorf("Deleted = %d, want 1", result.Deleted)
}
plane.assertRows(t, ctx, fixture, 0, id)
})
}
}
// RunDeleterRefusesAStaleExpectedVersion is the refusing half
// (issueops/deleter.go, DeleteRequest.ExpectedVersion: "otherwise the request is
// refused with ErrVersionMismatch and NOTHING IS DELETED").
//
// THE TOKEN IS THE ROW'S REAL VERSION PLUS ONE, and that arithmetic is the
// point rather than a shortcut. row_lock is minted afresh as a random non-zero
// int64 on every lifecycle write and never incremented, so a neighbor of the
// current value is a token no writer could have produced — while -1 or 0 would
// be a sentinel, and the pass that retired six unfalsifiable tests found
// sentinel-only refusal cases to be the shape that survives a body which
// refuses unconditionally. What rules that body out here is the SATISFIED case
// above, not the token below.
//
// It runs under DryRun too, because a preview that succeeded here would tell a
// caller its stale plan was safe to execute.
//
// The row count is read RAW rather than off the result, for the reason the
// whole file reads raw: "Deleted = 0" is exactly what a body that deleted the
// row and then failed would also report.
func RunDeleterRefusesAStaleExpectedVersion(t *testing.T, ctx context.Context, fixture DeleterFixture) {
t.Helper()
target := deleterSeedIssue(t, ctx, fixture, "version-stale", "target")
current := deleterRowVersion(t, ctx, fixture, "issues", target)
stale := current + 1
for _, dryRun := range []bool{false, true} {
result, err := fixture.Deleter.Delete(ctx, publicops.DeleteRequest{
IDs: []string{target},
Actor: "deleter-contract",
ExpectedVersion: &stale,
DryRun: dryRun,
})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("Delete(dryRun=%v) with a stale version error = %v, want ErrVersionMismatch", dryRun, err)
}
if result.Deleted != 0 {
t.Errorf("refused delete reported Deleted = %d, want 0", result.Deleted)
}
deleterAssertIssueRows(t, ctx, fixture, 1, target)
// The refusal wrote nothing at all, including the token itself: a
// guard that reminted row_lock on its way to refusing would make the
// caller's next read-and-retry lose a second time for a reason it
// could never see.
if got := deleterRowVersion(t, ctx, fixture, "issues", target); got != current {
t.Errorf("row version after a refused delete = %d, want %d unchanged", got, current)
}
}
}
// RunDeleterVersionOutranksForceAndCascade pins the two clauses a caller is
// most likely to assume the other way round (issueops/deleter.go,
// DeleteRequest.ExpectedVersion: "NEITHER Cascade NOR Force BYPASSES IT", and
// Deleter.Delete: "THE VERSION PRECONDITION OUTRANKS THE DEPENDENTS GUARD").
//
// The subject has a dependent OUTSIDE the request on every arm, so the
// dependents guard is LIVE throughout. That is what separates "force did not
// bypass the version" from "force was never needed here", and it is what lets
// the unforced arm assert the ranking: the request fails two ways at once and
// the answer is the version, not the guard.
//
// The satisfied arm at the end is not decoration. Without it, a body that
// refused every versioned delete under force would pass all three refusals —
// and the force path is exactly where a precondition is easiest to drop, since
// force is the flag that exists to make refusals go away.
func RunDeleterVersionOutranksForceAndCascade(t *testing.T, ctx context.Context, fixture DeleterFixture) {
t.Helper()
blocker := deleterSeedIssue(t, ctx, fixture, "version-rank", "blocker")
dependent := deleterSeedIssue(t, ctx, fixture, "version-rank", "dependent")
deleterAddEdge(t, ctx, fixture, dependent, blocker)
current := deleterRowVersion(t, ctx, fixture, "issues", blocker)
stale := current + 1
for _, mode := range []struct {
name string
cascade bool
force bool
}{
{"unforced", false, false},
{"force", false, true},
{"cascade", true, false},
} {
t.Run("stale/"+mode.name, func(t *testing.T) {
result, err := fixture.Deleter.Delete(ctx, publicops.DeleteRequest{
IDs: []string{blocker},
Actor: "deleter-contract",
ExpectedVersion: &stale,
Cascade: mode.cascade,
Force: mode.force,
})
if !errors.Is(err, publicops.ErrVersionMismatch) {
t.Fatalf("Delete(%s) with a stale version error = %v, want ErrVersionMismatch", mode.name, err)
}
if errors.Is(err, publicops.ErrDependentsOutsideRequest) {
t.Errorf("Delete(%s) answered the dependents guard over the stale version; the version outranks it", mode.name)
}
if result.Deleted != 0 {
t.Errorf("refused delete reported Deleted = %d, want 0", result.Deleted)
}
// Two rows, so the cascade arm also says the CLOSURE survived: a
// cascade that ran past the precondition would have taken the
// dependent with it.
deleterAssertIssueRows(t, ctx, fixture, 2, blocker, dependent)
})
}
result := deleterDelete(t, ctx, fixture, publicops.DeleteRequest{
IDs: []string{blocker},
Actor: "deleter-contract",
ExpectedVersion: &current,
Force: true,
})
if result.Deleted != 1 {
t.Errorf("Deleted = %d, want 1 with a matching version under force", result.Deleted)
}
if !reflect.DeepEqual(result.Orphaned, []string{dependent}) {
t.Errorf("Orphaned = %v, want [%s] — a matching version leaves force doing its ordinary job", result.Orphaned, dependent)
}
deleterAssertIssueRows(t, ctx, fixture, 0, blocker)
deleterAssertIssueRows(t, ctx, fixture, 1, dependent)
}
// RunDeleterRefusesAnExpectedVersionAcrossSeveralIDs pins the arity rule
// (issueops/deleter.go, DeleteRequest.ExpectedVersion: "A non-nil
// ExpectedVersion with more than one DISTINCT id is ErrValidation, refused
// before anything is read") and the duplicate-collapse exception beside it.
//
// THE TOKEN MATCHES THE FIRST ID. That is the arrangement the rule exists for:
// a body that quietly checked the first row and deleted the whole list would
// pass a case built on a token matching nothing, and would erase the second row
// under a precondition that never described it. Both rows are counted raw
// afterwards.
//
// The collapse arm is the falsifying sibling. Without it the rule reads as
// "expected-version deletes take one element", and an implementation that
// counted MENTIONS rather than distinct ids would refuse `bd delete a a`, which
// DeleteRequest.IDs promises is one row. The repeated mention is spelled
// untrimmed, so it also says the count happens after normalization.
func RunDeleterRefusesAnExpectedVersionAcrossSeveralIDs(t *testing.T, ctx context.Context, fixture DeleterFixture) {
t.Helper()
first := deleterSeedIssue(t, ctx, fixture, "version-arity", "first")
second := deleterSeedIssue(t, ctx, fixture, "version-arity", "second")
version := deleterRowVersion(t, ctx, fixture, "issues", first)
for _, dryRun := range []bool{false, true} {
result, err := fixture.Deleter.Delete(ctx, publicops.DeleteRequest{
IDs: []string{first, second},
Actor: "deleter-contract",
Force: true,
ExpectedVersion: &version,
DryRun: dryRun,
})
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("Delete(dryRun=%v) with a version across two ids error = %v, want ErrValidation", dryRun, err)
}
if result.Deleted != 0 {
t.Errorf("refused delete reported Deleted = %d, want 0", result.Deleted)
}
deleterAssertIssueRows(t, ctx, fixture, 2, first, second)
}
result := deleterDelete(t, ctx, fixture, publicops.DeleteRequest{
IDs: []string{first, " " + first + " "},
Actor: "deleter-contract",
Force: true,
ExpectedVersion: &version,
})
if result.Deleted != 1 {
t.Errorf("Deleted = %d, want 1 — a repeated mention of one id is one row", result.Deleted)
}
deleterAssertIssueRows(t, ctx, fixture, 0, first)
deleterAssertIssueRows(t, ctx, fixture, 1, second)
}
// deleterRowVersion reads the RowVersion token straight off the row, in the
// plane the caller names.
//
// RAW, like every other read in this file, and here the rawness is what makes
// the satisfied case mean something: a token laundered through the surface
// under test would be accepted by a body that ignored the column entirely.
// COALESCE mirrors the defensive scan the shared guard does, so a backend
// storing NULL in a NOT NULL DEFAULT 0 column reads as 0 rather than failing
// the case for a reason that is not the case's subject.
//
//nolint:gosec // G201: table is chosen by the caller from the two plane tables.
func deleterRowVersion(t *testing.T, ctx context.Context, fixture DeleterFixture, table, id string) int64 {
t.Helper()
var got int64
query := fmt.Sprintf("SELECT COALESCE(row_lock, 0) FROM %s WHERE id = ?", table)
if err := fixture.QueryScalar(ctx, query, []any{id}, &got); err != nil {
t.Fatalf("reading row_lock for %s from %s: %v", id, table, err)
}
return got
}
// deleterAddParentChildEdge is deleterAddEdge for the one edge type that is not
// a block: the blocked-state cases hang a child off a subject to observe
// INHERITANCE, which parent-child is what carries.

View file

@ -229,6 +229,10 @@ var roleContractCases = []roleContract{
RunDeleterSettlesTheSurvivorsOfADeletedBlocker,
RunDeleterSettlesTheChildrenOfADeletedParent,
RunDeleterSettlesTheSurvivorsOfADeletedWispBlocker,
RunDeleterDeletesOnAMatchingExpectedVersion,
RunDeleterRefusesAStaleExpectedVersion,
RunDeleterVersionOutranksForceAndCascade,
RunDeleterRefusesAnExpectedVersionAcrossSeveralIDs,
),
roleCases("DependencyEditor", "DependencyEditor()", oncePerRole,

View file

@ -78,6 +78,18 @@ func TestDeleterContract(t *testing.T) {
t.Run("SettlesTheChildrenOfADeletedParent", func(t *testing.T) {
conformance.RunDeleterSettlesTheChildrenOfADeletedParent(t, ctx, fixture)
})
t.Run("DeletesOnAMatchingExpectedVersion", func(t *testing.T) {
conformance.RunDeleterDeletesOnAMatchingExpectedVersion(t, ctx, fixture)
})
t.Run("RefusesAStaleExpectedVersion", func(t *testing.T) {
conformance.RunDeleterRefusesAStaleExpectedVersion(t, ctx, fixture)
})
t.Run("VersionOutranksForceAndCascade", func(t *testing.T) {
conformance.RunDeleterVersionOutranksForceAndCascade(t, ctx, fixture)
})
t.Run("RefusesAnExpectedVersionAcrossSeveralIDs", func(t *testing.T) {
conformance.RunDeleterRefusesAnExpectedVersionAcrossSeveralIDs(t, ctx, fixture)
})
}
// newDoltDeleterFixture composes the frozen role kit with this backend's

View file

@ -82,6 +82,18 @@ func TestDeleterContract(t *testing.T) {
t.Run("SettlesTheChildrenOfADeletedParent", func(t *testing.T) {
conformance.RunDeleterSettlesTheChildrenOfADeletedParent(t, ctx, fixture)
})
t.Run("DeletesOnAMatchingExpectedVersion", func(t *testing.T) {
conformance.RunDeleterDeletesOnAMatchingExpectedVersion(t, ctx, fixture)
})
t.Run("RefusesAStaleExpectedVersion", func(t *testing.T) {
conformance.RunDeleterRefusesAStaleExpectedVersion(t, ctx, fixture)
})
t.Run("VersionOutranksForceAndCascade", func(t *testing.T) {
conformance.RunDeleterVersionOutranksForceAndCascade(t, ctx, fixture)
})
t.Run("RefusesAnExpectedVersionAcrossSeveralIDs", func(t *testing.T) {
conformance.RunDeleterRefusesAnExpectedVersionAcrossSeveralIDs(t, ctx, fixture)
})
}
func newEmbeddedDeleterFixture(t *testing.T, te *testEnv, prefix string) conformance.DeleterFixture {

View file

@ -57,6 +57,40 @@ func DeleteInTx(ctx context.Context, tx *sql.Tx, req publicops.DeleteRequest) (p
return publicops.DeleteResult{}, &publicops.NotFoundError{IDs: missing}
}
// The version precondition sits between the existence probe and the
// dependents guard, where issueops.Deleter.Delete puts it: a version is a
// fact about a row, so a request naming a typo reports the typo; and a
// caller holding a stale token is not yet in a position to choose --cascade
// or --force, so the mismatch outranks that refusal.
//
// It reads ids[0] because ValidateDeleteRequest has already refused a
// multi-id request carrying one and NormalizeDeleteIDs has already
// collapsed duplicates, so exactly one distinct id is here. The read shares
// this transaction with the deletion below, which is what makes the pair a
// compare-and-delete; CheckVersionInTx is the same guard the update and
// close paths use, over the same row_lock token and with the same
// plane routing.
//
// IT RE-READS A ROW THE PROBE ABOVE ALREADY RETURNED, and that is a real
// trade rather than an oversight: `found` carries this row's RowVersion, so
// the comparison could be made here without a second SELECT. What the second
// SELECT buys is ONE definition of the guard — the same function the update
// and close paths call, so a change to how a version is read or how a
// mismatch is worded reaches all three together — at the cost of one indexed
// single-row read inside a transaction that is about to delete rows and
// rewrite their neighbors.
//
// THE UNIT-OF-WORK LEG ANSWERS THAT TRADE THE OTHER WAY, comparing the row
// its own probe loaded, and the two are not in disagreement: that leg
// reaches the domain use cases rather than a transaction, so this function
// is not available to it and there is no shared guard for it to prefer. The
// conformance contract is where the two are held equal.
if req.ExpectedVersion != nil {
if err := CheckVersionInTx(ctx, tx, ids[0], *req.ExpectedVersion); err != nil {
return publicops.DeleteResult{}, err
}
}
idSet := make(map[string]bool, len(ids))
for _, id := range ids {
idSet[id] = true

View file

@ -85,8 +85,11 @@ func deleteInUOW(ctx context.Context, uw UnitOfWork, req publicops.DeleteRequest
result := publicops.DeleteResult{DryRun: req.DryRun}
// The existence probe comes FIRST, so a request naming a typo reports the
// typo rather than whatever the graph says about the ids that resolved.
present := make(map[string]bool, len(req.IDs))
// typo rather than whatever the graph says about the ids that resolved. It
// keeps the ROWS rather than a set of ids, because the version precondition
// below needs their RowVersion and re-reading them for it would be a second
// read of the same rows in the same transaction.
present := make(map[string]*types.Issue, len(req.IDs))
for _, load := range []func(context.Context, []string) ([]*types.Issue, error){
issueUC.GetIssuesByIDs,
issueUC.GetWispsByIDs,
@ -97,13 +100,13 @@ func deleteInUOW(ctx context.Context, uw UnitOfWork, req publicops.DeleteRequest
}
for _, row := range rows {
if row != nil {
present[row.ID] = true
present[row.ID] = row
}
}
}
var missing []string
for _, id := range req.IDs {
if !present[id] {
if present[id] == nil {
missing = append(missing, id)
}
}
@ -111,6 +114,26 @@ func deleteInUOW(ctx context.Context, uw UnitOfWork, req publicops.DeleteRequest
return publicops.DeleteResult{}, &publicops.NotFoundError{IDs: missing}
}
// The version precondition, between the existence probe and the dependents
// guard exactly as issueops.Deleter.Delete orders them.
//
// This leg compares the row the probe already loaded rather than issuing
// its own guard read, which is what updatePreconditionsHold does for the
// same token on the update path. The row was read inside this unit of work,
// so the comparison and the deletion still see one snapshot; the sentinel
// and the message are the shared ones, because a caller matching
// ErrVersionMismatch must not have to know which backend answered.
//
// req.IDs[0] is the only distinct id: ValidateDeleteRequest refused a
// multi-id request carrying a version and NormalizeDeleteIDs collapsed the
// duplicates before either ran.
if req.ExpectedVersion != nil {
if current := present[req.IDs[0]].RowVersion; current != *req.ExpectedVersion {
return publicops.DeleteResult{}, fmt.Errorf("%w: expected %d, got %d",
publicops.ErrVersionMismatch, *req.ExpectedVersion, current)
}
}
// The guard runs only when the request did not already say what to do
// about dependents. Under Cascade there is nothing outside the set by
// construction.

View file

@ -81,6 +81,18 @@ func TestDeleterContract(t *testing.T) {
t.Run("SettlesTheChildrenOfADeletedParent", func(t *testing.T) {
conformance.RunDeleterSettlesTheChildrenOfADeletedParent(t, ctx, fixture)
})
t.Run("DeletesOnAMatchingExpectedVersion", func(t *testing.T) {
conformance.RunDeleterDeletesOnAMatchingExpectedVersion(t, ctx, fixture)
})
t.Run("RefusesAStaleExpectedVersion", func(t *testing.T) {
conformance.RunDeleterRefusesAStaleExpectedVersion(t, ctx, fixture)
})
t.Run("VersionOutranksForceAndCascade", func(t *testing.T) {
conformance.RunDeleterVersionOutranksForceAndCascade(t, ctx, fixture)
})
t.Run("RefusesAnExpectedVersionAcrossSeveralIDs", func(t *testing.T) {
conformance.RunDeleterRefusesAnExpectedVersionAcrossSeveralIDs(t, ctx, fixture)
})
}
func newUOWDeleterFixture(t *testing.T, ctx context.Context, prefix string) conformance.DeleterFixture {

View file

@ -26,6 +26,10 @@ import (
// delete request carries no predicate at all, so a caller cannot spell
// "everything" without typing every id. The guard that does matter — dependents
// outside the request — needs the graph and therefore lives in the bodies.
//
// The ExpectedVersion arity rule is here rather than in the bodies for the
// reason the rest of this file exists: it needs no database, and a rule the
// bodies each spelled themselves is a rule that can differ per backend.
func ValidateDeleteRequest(in issueops.DeleteRequest) error {
if len(in.IDs) == 0 {
return fmt.Errorf("%w: delete requires at least one issue id", issueops.ErrValidation)
@ -35,6 +39,16 @@ func ValidateDeleteRequest(in issueops.DeleteRequest) error {
return fmt.Errorf("%w: delete id at position %d is blank", issueops.ErrValidation, i)
}
}
// DISTINCT ids, not mentions: DeleteRequest.IDs promises duplicates
// collapse, so an IDs of {"a", "a"} carrying a version names ONE row and is
// legal. Counting the raw slice here would refuse the request the role's own
// normalization rule says is fine.
if in.ExpectedVersion != nil {
if distinct := len(NormalizeDeleteIDs(in.IDs)); distinct > 1 {
return fmt.Errorf("%w: expected-version delete names %d issues; one row version cannot describe more than one row",
issueops.ErrValidation, distinct)
}
}
return nil
}

View file

@ -26,6 +26,18 @@ func TestValidateDeleteRequest(t *testing.T) {
{"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)
@ -96,3 +108,6 @@ func TestSortedDeleteIDs(t *testing.T) {
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 }

View file

@ -45,6 +45,56 @@ type DeleteRequest struct {
// resolving an ambiguous prefix to a row and then deleting it is the one
// place a convenience is not one.
IDs []string
// ExpectedVersion is an optimistic-concurrency precondition on the row this
// request NAMES: the deletion proceeds only if that row's current
// RowVersion — the opaque server-minted row_lock token carried on
// types.Issue.RowVersion — still equals *ExpectedVersion, and otherwise the
// request is refused with ErrVersionMismatch and NOTHING IS DELETED.
//
// THE TOKEN IS OPAQUE AND COMPARED FOR EQUALITY ONLY. It is minted afresh
// on every lifecycle write rather than incremented, so it does not order:
// "newer" and "older" are not questions this precondition can answer. The
// only question it answers is whether the row is still the one the caller
// looked at, which is the only question a caller about to erase something
// irreversibly needs answered.
//
// nil DISABLES THE CHECK. It is a pointer for the reason
// UpdateRequest.ExpectedVersion is one: nil, meaning "do not check", has to
// be distinct from a caller that requires the never-written version 0.
//
// IT REQUIRES A SINGLE-ID REQUEST. A non-nil ExpectedVersion beside more
// than one DISTINCT id is ErrValidation, refused before anything is read.
// One token cannot describe two rows: the version space is per-row and not
// shared, so checking one number 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 since diverged. A guard that passes
// by coincidence and a guard a caller can never satisfy are the same defect
// seen from two sides. The per-id shape a batch would actually need is a
// token PER id, which is a list of ITEMS rather than a list of ids, and
// this role is not born with one; BatchCloser.Items is where that shape
// lives, and BatchCloseItem deliberately carries no version for the same
// reason its own doc gives.
//
// DUPLICATES COLLAPSE FIRST, so `bd delete a a` with a token names one row
// and is legal. The refusal counts DISTINCT ids, not mentions.
//
// NEITHER Cascade NOR Force BYPASSES IT. Force bypasses POLICY — the
// dependents guard — and never a precondition, exactly as
// CloseRequest.Force bypasses close policy and never the version it is
// paired with. A caller that could orphan its way past a stale token would
// be doing the irreversible half of the operation on a row it no longer
// recognizes.
//
// IT GUARDS THE NAMED ROW'S LIFECYCLE STATE, NOT ITS GRAPH AND NOT ITS
// CLOSURE. RowVersion is reminted by status, assignee and started_at
// writes and deliberately not by label, dependency, rename or is_blocked
// writes, so a matching token does NOT promise that the row's edges are the
// ones the caller saw. Under Cascade that has a consequence worth saying
// out loud: the closure is resolved inside the deleting transaction, so a
// caller whose named row is unchanged deletes the closure the graph has
// NOW, which an edge added since its read may have grown. A caller that
// needs the closure itself pinned wants DryRun's preview and not this.
ExpectedVersion *int64
// Cascade also deletes the TRANSITIVE CLOSURE of everything that depends
// on the named rows, in both planes. It is what `bd delete --cascade`
// asks for.
@ -82,6 +132,11 @@ type DeleteRequest struct {
// batch that names both ends of an edge is deleting the edge too, and
// refusing it would make `bd delete a b` fail on exactly the pair a caller
// took care to list together.
//
// IT BYPASSES POLICY, NEVER A PRECONDITION. It does not bypass
// ExpectedVersion and it does not bypass the existence probe: the guard it
// answers is the one about OTHER rows, and a caller saying "orphan them" has
// said nothing about whether the row it named is still the row it read.
Force bool
// DryRun reports what the deletion WOULD do and changes nothing, including
// history.
@ -259,23 +314,45 @@ type Deleter interface {
// scan on every delete is a cost this operation does not take.
//
// THE ORDER THE REFUSALS HAPPEN IN IS PART OF THE ANSWER, because a
// request can fail two ways at once: request validation, then the
// existence probe, then the dependents guard. `bd delete typo real-with-
// dependents` reports the TYPO, which is the one the caller can fix
// without deciding anything.
// request can fail several ways at once: request validation, then the
// existence probe, then the version precondition, then the dependents
// guard. `bd delete typo real-with-dependents` reports the TYPO, which is
// the one the caller can fix without deciding anything.
//
// THE VERSION PRECONDITION OUTRANKS THE DEPENDENTS GUARD, and that
// placement is the answer to "which refusal helps the caller more". A
// mismatch says the row has changed since the caller read it, so the whole
// plan — including whether to delete at all — is built on a stale view;
// reporting the dependents refusal first would be asking a caller to choose
// --cascade or --force over information that has already moved. It ranks
// BELOW the existence probe for the opposite reason: a version is a fact
// about a row, and a request that named no row has nothing to be stale
// about.
//
// REFUSALS:
//
// - an empty or all-blank IDs, and an IDs containing a blank entry:
// ErrValidation, before anything is read;
// - a non-nil ExpectedVersion beside more than one distinct id:
// ErrValidation, also before anything is read;
// - an id naming no row in either plane: *NotFoundError, matching
// ErrNotFound;
// - an ExpectedVersion that no longer matches the named row's current
// RowVersion: ErrVersionMismatch, which neither Force nor Cascade
// bypasses;
// - without Cascade and without Force, a named row with a dependent the
// request did not name: *DependentsOutsideRequestError, matching
// ErrDependentsOutsideRequest.
//
// EVERY ONE OF THEM DELETES NOTHING, under DryRun and otherwise.
//
// THE VERSION READ SHARES THE DELETING TRANSACTION, so the pair is a true
// compare-and-delete rather than a read followed by a hopeful write: a
// writer that committed before the transaction opened is caught by the read
// itself, and one that commits during it collides on the same row_lock cell
// and is replayed against the new value. That is the same two-limbed
// invariant Lifecycle's ExpectedVersion has, over the same token.
//
// A DRY RUN CHANGES NOTHING, including history: an implementation that
// records a version-control entry for a deletion records none for a dry
// run. Where an implementation versions at all, a call that deleted