beads/internal/storage/uow/lifecycle_update_contract_test.go
Julian Knutsen eaed71fbba
fix(http): bd promote over http through issueops.Promote and issues.update.persistence (S21b) (#7554)
* fix(http): bd promote over http through issueops.Promote and issues.update.persistence (S21b)

`bd promote` refused over a connected HTTP workspace: it called the raw
PromoteFromEphemeral, which the http backend stubs, and updateIssue's patch
did not publish persistence. MC's PR-intake formula
(mol-normalized-issue-pr-v1) runs `gc bd promote <id> --reason ...`, so this
blocked the HTTP cutover.

- One library entry, issueops.Promote(ctx, PromoteRoles{Reader, Lifecycle,
  Commenter}, PromoteRequest{Actor, IssueID, Reason, Provenance}): read the
  row, refuse a non-wisp (*NotAWispError, the sentence bd promote always
  printed), move it with ONE Lifecycle.Update whose patch is Persistence =
  persistent (the role's atomic plane move: same id, labels, deps, events and
  comments carried), then write the promotion comment (a comment failure is
  reported, the promotion stands). A no-op move is a lost race and reports
  NotAWispError without a second comment.
- cmd/bd: the direct route runs it over the store's own role accessors, so a
  connected http workspace and a local one take the same entry. The history
  label is "bd: promote <id>" where the store carries caller labels.
- bd serve: IssuePatchBody.persistence (persistent|ephemeral|no_history,
  anything else a 400 naming patch.persistence) on PATCH
  /v0/beads/issues/{id}, behind the new additive behavior token
  issues.update.persistence. wire_revision unchanged. Spec, apigen and the
  wire-shape golden regenerated; the handler only decodes and passes it to
  the role.
- httpclient: Lifecycle.Update sends patch.persistence only to a server
  advertising the token, and otherwise refuses BEFORE the dial with
  *wire.CapabilityError naming it (unwraps to *storage.ErrUnsupported with
  Capability set). The batchApply item still refuses it
  (W-IssuePatch.Persistence now reads "ON issues:batchApply").
- Conformance: RunLifecycleUpdatePersistentPromotesAWisp on dolt, embedded,
  uow and the served http leg; the served
  PersistentPreservesUnversionedClass case is unparked.
- Served e2e TestE2E_PromoteOverHTTP: the mc-promote shape end to end
  (label kept, comment written, one PATCH, re-promote refused), and under
  the MC server mask a pre-dial refusal naming the token with no write.
- Corpus: mc-promote stays pending, relabelled SRV-1 with the reference
  profile's exact refusal (the 1.3.0 server lacks issues.update.persistence).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(promote): run the proxied-server route through issueops.Promote (bd-4y73m9)

The adoption review found (major) that the proxied-server route still
promoted through the old engine, IssueUseCase.PromoteWisp in one
transaction with the comment, while the PR's docs said every route runs
issueops.Promote. Converge rather than reword: runPromoteProxiedServer
resolves the id, then runs issueops.Promote over the provider's own
notifying role accessors (proxiedIssueReader, proxiedIssueLifecycle,
proxiedCommenter), the entry the direct route runs. Both routes now share
promoteFailure (the error mapping) and reportPromotion (the comment
warning and the output), so neither contract can drift.

What a script sees change on the proxied-server route:
- the move is the persistence branch of Lifecycle.Update, so the child
  counter moves with the row: a promoted parent's next
  `bd create --parent` mints .3 after .1/.2 instead of failing with
  "issue already exists";
- on_update fires twice, for the move and for the comment, as on the
  direct route (it fired once, for the comment);
- a promotion is two Dolt commits, "bd: promote <id>" and
  "bd: comment <id>" (it was one);
- a comment that cannot be written leaves the promotion standing behind
  a warning, as on every other route, instead of rolling it back;
- a dual-plane id is refused rather than merged, the update role's
  template guard applies, and a lost race reads "<id> is not a wisp
  (already persistent)".

The PromoteWisp exemption in TestRecordingIssueUseCaseCoversItsSurface
stays, with its reason corrected: no route calls PromoteWisp now, and
its DoltStorage twin fires no hook either. The doc comments on the old
engine (PromoteFromEphemeral on DoltStore and the db layer, PromoteWisp)
no longer say bd promote uses it.

CHANGELOG: the promote entry now names what a script can see on the
direct and proxied-server routes: the hook firings, the comment row
`bd comments` lists, the child-counter carry, the two-commit shape, and
a comment failure that warns instead of rolling back.

Tests:
- TestEmbeddedPromoteMovesAWispParent promotes a wisp parent with .1/.2
  children, a dependency and a comment under a counting on_update hook:
  the hook fires twice, the dependency and the children's parent edge
  survive, `bd comments` lists the old comment and the promotion reason,
  and the next child is .3. At the pre-PR base it fails (the hook fired
  0 times).
- The proxied journey pins the two commits, and new subtests pin the
  child counter (the child_counters row, next child .3) and the two hook
  firings. Against the contributor head each fails: one commit, no
  counter row and a failing create, one firing.

Review iteration 2:
- TestEmbeddedPromoteMovesAWispParent gets its row in the embedded cmd
  shard manifest (shard 64 of 100, from the generator's incremental
  --write). Without it //scripts:go_test_sources_test fails both the
  NotStale and the bare-write guard, and the generator's --check fails.
- notifying.go no longer lists the promotion comment as a divergence.
  The direct route now writes that comment through st.Commenter(),
  which HookFiringStore wraps, so an embedded promote fires on_update
  for it (TestEmbeddedPromoteMovesAWispParent counts both firings). The
  list counts four, and the empty-commit note becomes the fifth item.
- batchapplier.go no longer says persistence is absent from both patch
  bodies: the update body publishes it behind issues.update.persistence,
  and only batchApply refuses it (W-IssuePatch.Persistence).
- Three comments still tied promotion to the old engine: the
  conformance fixture's PromoteWisp no longer claims to do what
  `bd promote` does, the CLI differential's promote scenario names
  issueops.Promote, and export_source's wisp-relations note names
  issueops.MoveIssuePersistenceInTx.
- The Promote unit test compares the whole update patch with
  reflect.DeepEqual. The helper it replaces checked 9 of the patch's 22
  members, so a Promote that also set Description passed it.

Review iteration 3:
- A refused persistence move answered 500 `internal` over http and
  emitted request_error, though the caller could fix the request. The
  role now returns two refusals as ErrValidation, so bd serve answers
  400 invalid_argument and the client maps that back to ErrValidation:
  an unversioned row asked for ephemeral or no_history (the role wraps
  types.ErrUnversionedWispMove, a new sentinel NormalizePersistenceMode
  returns for that case alone, with its message unchanged), and a
  demotion of a row with retained snapshots. A row that breaks its own
  persistence invariants still answers 500.
- RunLifecycleUpdateWispModesRefuseAnUnversionedRow pins the refusal on
  every leg (dolt, embedded dolt, the unit of work, served http): both
  wisp modes match ErrValidation and leave the row durable, unversioned
  and off the wisp plane. Without the wrap the dolt leg fails, and the
  served leg fails on "answered 500 internal".
- TestMoveIssuePersistenceInTxRefusesDemotionWithRetainedSnapshots is
  the first test of the snapshot refusal, and fails without its wrap.
  The unversioned unit test now requires both sentinels. The types tests
  pin the sentinel, its unchanged message, and that no row-invariant
  error matches it: checking the unversioned class ahead of the
  invariant checks fails them.
- CHANGELOG: the promote entry counts five script-visible changes, the
  fifth being the lost-race refusal sentence, and says the two refusals
  now answer 400 over bd serve and gain a `validation failed: ` prefix
  locally.
- NotAWispError's doc comment records that a no-history wisp is refused
  too: the gate reads the Ephemeral flag, as bd promote always has, and
  `bd update --persistent` is the move for that row.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 05:51:53 +00:00

161 lines
7 KiB
Go

package uow
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/types"
)
// TestLifecycleUpdateContract runs the accessor-only Update half of the
// Lifecycle contract against the unit-of-work provider — the one Lifecycle
// implementation that does not share the validate/execute body the two stores
// share. It maps the patch itself and derives Changed by comparing the
// post-state snapshot to the pre-state one instead of reading the row-write
// facts, so this is the wiring where a same-value or clear divergence shows up.
//
// One provider for the whole block (each newUOWRoleFixtureProvider boots a real
// Dolt sql-server) and NO t.Parallel: this backend has no per-test
// copy-on-write branch, so a parallel subtest would share another subtest's
// database.
func TestLifecycleUpdateContract(t *testing.T) {
ctx := context.Background()
fixture := newUOWLifecycleUpdateFixture(t, ctx, "lup")
t.Run("PersistsThePatchAndHydratesTheResult", func(t *testing.T) {
conformance.RunLifecycleUpdatePersistsThePatchAndHydratesTheResult(t, ctx, fixture)
})
t.Run("PreservesTheCreationStamp", func(t *testing.T) {
conformance.RunLifecycleUpdatePreservesTheCreationStamp(t, ctx, fixture)
})
t.Run("ReportsNoChangeForASameValuePatch", func(t *testing.T) {
conformance.RunLifecycleUpdateReportsNoChangeForASameValuePatch(t, ctx, fixture)
})
t.Run("AppendsNotesWithoutReplacingThem", func(t *testing.T) {
conformance.RunLifecycleUpdateAppendsNotesWithoutReplacingThem(t, ctx, fixture)
})
t.Run("ClearsTheNullableMembers", func(t *testing.T) {
conformance.RunLifecycleUpdateClearsTheNullableMembers(t, ctx, fixture)
})
t.Run("ReplacesTheLabelSet", func(t *testing.T) {
conformance.RunLifecycleUpdateReplacesTheLabelSet(t, ctx, fixture)
})
t.Run("ResolvesBothPlanesUnlessRestricted", func(t *testing.T) {
conformance.RunLifecycleUpdateResolvesBothPlanesUnlessRestricted(t, ctx, fixture)
})
t.Run("RefusesUnknownIDsAndActorlessRequests", func(t *testing.T) {
conformance.RunLifecycleUpdateRefusesUnknownIDsAndActorlessRequests(t, ctx, fixture)
})
t.Run("RefusalWritesNoMemberOfThePatch", func(t *testing.T) {
conformance.RunLifecycleUpdateRefusalWritesNoMemberOfThePatch(t, ctx, fixture)
})
t.Run("ConditionalGuardsGateOrdinaryEdits", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits(t, ctx, fixture)
})
t.Run("ExpectedVersionSingleWinnerUnderConcurrency", func(t *testing.T) {
conformance.RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency(t, ctx, fixture)
})
t.Run("ExpectedVersionSingleWinnerWithDisjointColumnsUnderConcurrency", func(t *testing.T) {
conformance.RunLifecycleUpdateExpectedVersionSingleWinnerWithDisjointColumnsUnderConcurrency(t, ctx, fixture)
})
t.Run("CloseExpectedVersionSingleWinnerUnderConcurrency", func(t *testing.T) {
conformance.RunLifecycleCloseExpectedVersionSingleWinnerUnderConcurrency(t, ctx, fixture)
})
t.Run("ExpectedVersionSingleWinnerAcrossUpdateAndCloseUnderConcurrency", func(t *testing.T) {
conformance.RunLifecycleUpdateExpectedVersionSingleWinnerAcrossUpdateAndCloseUnderConcurrency(t, ctx, fixture)
})
t.Run("ConditionalGuardAcceptsRespelledAssignee", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee(t, ctx, fixture)
})
t.Run("MetadataPatchOrdersMergeSetUnset", func(t *testing.T) {
conformance.RunLifecycleUpdateMetadataPatchOrdersMergeSetUnset(t, ctx, fixture)
})
t.Run("ClosePolicy", func(t *testing.T) {
conformance.RunLifecycleUpdateClosePolicy(t, ctx, fixture)
})
t.Run("AssigneeTransferFence", func(t *testing.T) {
conformance.RunLifecycleUpdateAssigneeTransferFence(t, ctx, fixture)
})
t.Run("ClaimIsAMutationWhenThePatchRestoresTheRow", func(t *testing.T) {
conformance.RunLifecycleUpdateClaimIsAMutationWhenThePatchRestoresTheRow(t, ctx, fixture)
})
t.Run("ParentIDReplacesTheParentEdge", func(t *testing.T) {
conformance.RunLifecycleUpdateParentIDReplacesTheParentEdge(t, ctx, fixture)
})
t.Run("ParentIDReplacesEveryParent", func(t *testing.T) {
conformance.RunLifecycleUpdateParentIDReplacesEveryParent(t, ctx, fixture)
})
t.Run("PersistentPreservesUnversionedClass", func(t *testing.T) {
conformance.RunLifecycleUpdatePersistentPreservesUnversionedClass(t, ctx, fixture)
})
t.Run("WispModesRefuseAnUnversionedRow", func(t *testing.T) {
conformance.RunLifecycleUpdateWispModesRefuseAnUnversionedRow(t, ctx, fixture)
})
t.Run("PersistentPromotesAWisp", func(t *testing.T) {
conformance.RunLifecycleUpdatePersistentPromotesAWisp(t, ctx, fixture)
})
t.Run("ProvenanceLabelsHistory", func(t *testing.T) {
conformance.RunLifecycleUpdateProvenanceLabelsHistory(t, ctx, fixture)
})
t.Run("RefusesATemplate", func(t *testing.T) {
conformance.RunLifecycleUpdateRefusesATemplate(t, ctx, fixture)
})
t.Run("AllowTemplateEditsATemplate", func(t *testing.T) {
conformance.RunLifecycleUpdateAllowTemplateEditsATemplate(t, ctx, fixture)
})
}
func newUOWLifecycleUpdateFixture(t *testing.T, ctx context.Context, prefix string) conformance.LifecycleUpdateFixture {
t.Helper()
provider := newUOWRoleFixtureProvider(t, ctx, prefix)
// Through the capability accessor, not NewIssueOperations: a provider that
// stopped offering the role is the regression, and a constructor call would
// hide it.
source, ok := provider.(IssueLifecycleSource)
if !ok {
t.Fatalf("provider %T does not offer the IssueLifecycle accessor", provider)
}
lifecycle, err := source.IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
kit := newUOWRoleFixtureKit(provider, prefix)
return conformance.LifecycleUpdateFixture{
IssuePrefix: kit.IssuePrefix,
Lifecycle: lifecycle,
CreateIssue: kit.CreateIssue,
CreateWisp: kit.CreateWisp,
AddDependency: kit.AddDependency,
SetConfig: kit.SetConfig,
CountHistoryMatching: kit.CountHistoryMatching,
ListEvents: newUOWContractEventLister(provider),
ListDependencies: newUOWContractDependencyLister(provider),
WispExists: newUOWContractWispProbe(provider),
// The frozen kit reads through QueryScalar. This block reads its
// post-state through the backend's own both-plane issue read instead,
// so no case in it depends on raw SQL.
//
// The label set is read straight off the label use case rather than
// through hydrateIssueOperation, which is the code the result-shape
// assertions are ABOUT: a readback sharing it could not tell a result
// that lost its labels from a row that never had them.
GetIssue: func(ctx context.Context, id string) (*types.Issue, error) {
return RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (*types.Issue, error) {
issue, isWisp, err := operationIssue(ctx, uw, id, false)
if err != nil {
return nil, err
}
if isWisp {
issue.Labels, err = uw.LabelUseCase().GetWispLabels(ctx, id)
} else {
issue.Labels, err = uw.LabelUseCase().GetLabels(ctx, id)
}
if err != nil {
return nil, err
}
return issue, nil
})
},
}
}