beads/internal/storage/dolt/issue_operations_persistence_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

392 lines
16 KiB
Go

package dolt
import (
"context"
"database/sql"
"errors"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
)
func TestMoveIssuePersistenceInTxMovesAggregateAndReportsTables(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-move", Title: "move", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"label"}}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if _, err := store.AddIssueComment(ctx, issue.ID, "tester", "comment"); err != nil {
t.Fatal(err)
}
depender := &types.Issue{ID: "persist-depender", Title: "depender", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, depender, "tester"); err != nil {
t.Fatal(err)
}
if err := store.AddDependency(ctx, &types.Dependency{IssueID: depender.ID, DependsOnID: issue.ID, Type: types.DepBlocks}, "tester"); err != nil {
t.Fatal(err)
}
if _, err := store.db.ExecContext(ctx, `INSERT INTO child_counters (parent_id, last_child) VALUES (?, ?)`, issue.ID, 4); err != nil {
t.Fatal(err)
}
var moved issueops.PersistenceMoveResult
if err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
moved, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral, "test-actor")
return err
}); err != nil {
t.Fatal(err)
}
if !moved.Changed || !moved.ChangedTables["issues"] || !moved.ChangedTables["wisps"] || !moved.ChangedTables["wisp_comments"] || !moved.ChangedTables["wisp_labels"] || !moved.ChangedTables["dependencies"] {
t.Fatalf("move result = %#v, want changed aggregate tables", moved)
}
got, err := store.GetIssue(ctx, issue.ID)
if err != nil {
t.Fatal(err)
}
if !got.Ephemeral || got.NoHistory || len(got.Labels) != 1 || got.Labels[0] != "label" {
t.Fatalf("moved issue = %#v", got)
}
comments, err := store.GetIssueComments(ctx, issue.ID)
if err != nil {
t.Fatal(err)
}
if len(comments) != 1 || comments[0].Text != "comment" {
t.Fatalf("comments = %#v", comments)
}
var durableTarget, wispTarget *string
if err := store.db.QueryRowContext(ctx, `SELECT depends_on_issue_id, depends_on_wisp_id FROM dependencies WHERE issue_id = ?`, depender.ID).Scan(&durableTarget, &wispTarget); err != nil {
t.Fatal(err)
}
if durableTarget != nil || wispTarget == nil || *wispTarget != issue.ID {
t.Fatalf("inbound target = (%v,%v), want (nil,%q)", durableTarget, wispTarget, issue.ID)
}
var sourceEvents, targetEvents, sourceCounters, targetCounters int
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM events WHERE issue_id = ?`, issue.ID).Scan(&sourceEvents); err != nil {
t.Fatal(err)
}
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM wisp_events WHERE issue_id = ?`, issue.ID).Scan(&targetEvents); err != nil {
t.Fatal(err)
}
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM child_counters WHERE parent_id = ?`, issue.ID).Scan(&sourceCounters); err != nil {
t.Fatal(err)
}
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM wisp_child_counters WHERE parent_id = ? AND last_child = 4`, issue.ID).Scan(&targetCounters); err != nil {
t.Fatal(err)
}
if sourceEvents != 0 || targetEvents == 0 || sourceCounters != 0 || targetCounters != 1 {
t.Fatalf("moved event/counter rows = events(%d,%d) counters(%d,%d)", sourceEvents, targetEvents, sourceCounters, targetCounters)
}
}
func TestMoveIssuePersistenceInTxSameModeIsNoop(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-noop", Title: "noop", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
result, err := issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModePersistent, "test-actor")
if err != nil {
return err
}
if result.Changed {
t.Fatal("same persistence mode changed issue")
}
return nil
}); err != nil {
t.Fatal(err)
}
}
func TestMoveIssuePersistenceInTxTransitions(t *testing.T) {
for _, transition := range []struct {
name string
from types.PersistenceMode
to types.PersistenceMode
}{
{"persistent-to-ephemeral", types.PersistenceModePersistent, types.PersistenceModeEphemeral},
{"persistent-to-no-history", types.PersistenceModePersistent, types.PersistenceModeNoHistory},
{"ephemeral-to-persistent", types.PersistenceModeEphemeral, types.PersistenceModePersistent},
{"ephemeral-to-no-history", types.PersistenceModeEphemeral, types.PersistenceModeNoHistory},
{"no-history-to-persistent", types.PersistenceModeNoHistory, types.PersistenceModePersistent},
{"no-history-to-ephemeral", types.PersistenceModeNoHistory, types.PersistenceModeEphemeral},
} {
t.Run(transition.name, func(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
ephemeral, noHistory, _, err := types.NormalizePersistenceMode(types.Issue{}, transition.from)
if err != nil {
t.Fatal(err)
}
issue := &types.Issue{ID: "transition-" + transition.name, Title: transition.name, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: ephemeral, NoHistory: noHistory}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, transition.to, "test-actor")
return err
}); err != nil {
t.Fatal(err)
}
got, err := store.GetIssue(ctx, issue.ID)
if err != nil {
t.Fatal(err)
}
wantEphemeral, wantNoHistory, _, err := types.NormalizePersistenceMode(types.Issue{Ephemeral: ephemeral, NoHistory: noHistory}, transition.to)
if err != nil {
t.Fatal(err)
}
if got.Ephemeral != wantEphemeral || got.NoHistory != wantNoHistory {
t.Fatalf("persistence = (%t,%t), want (%t,%t)", got.Ephemeral, got.NoHistory, wantEphemeral, wantNoHistory)
}
})
}
}
func TestMoveIssuePersistenceInTxRefusesUnversionedDemotion(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "unversioned", Title: "unversioned", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, StorageClass: types.StorageClassUnversioned}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral, "test-actor")
return err
})
// The request is refused, not the row: ErrValidation is what makes this a
// 400 over http rather than a 500.
if !errors.Is(err, storage.ErrValidation) || !errors.Is(err, types.ErrUnversionedWispMove) {
t.Fatalf("unversioned demotion error = %v, want ErrValidation wrapping ErrUnversionedWispMove", err)
}
got, err := store.GetIssue(ctx, issue.ID)
if err != nil || got.Ephemeral || got.NoHistory {
t.Fatalf("refusal state = %#v, %v", got, err)
}
}
func TestMoveIssuePersistenceInTxRefusesDemotionWithRetainedSnapshots(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-snapshot", Title: "snapshot", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
// The snapshot tables have no default id since migration 0051.
if _, err := store.db.ExecContext(ctx, `INSERT INTO issue_snapshots (id, issue_id, snapshot_time, compaction_level, original_size, compressed_size, original_content) VALUES (?, ?, NOW(), 1, 1, 1, ?)`, "persist-snapshot-row", issue.ID, "snapshot"); err != nil {
t.Fatal(err)
}
err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral, "test-actor")
return err
})
if !errors.Is(err, storage.ErrValidation) {
t.Fatalf("demotion with retained snapshots error = %v, want ErrValidation", err)
}
got, err := store.GetIssue(ctx, issue.ID)
if err != nil || got.Ephemeral || got.NoHistory {
t.Fatalf("refusal state = %#v, %v", got, err)
}
}
func TestMoveIssuePersistenceInTxDeletesLeaseOnDemotion(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-lease", Title: "lease", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if err := store.ClaimIssue(ctx, issue.ID, "tester"); err != nil {
t.Fatal(err)
}
var before int
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM leases WHERE issue_id = ?`, issue.ID).Scan(&before); err != nil || before != 1 {
t.Fatalf("lease before move = %d, %v", before, err)
}
if err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral, "test-actor")
return err
}); err != nil {
t.Fatal(err)
}
var after int
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM leases WHERE issue_id = ?`, issue.ID).Scan(&after); err != nil || after != 0 {
t.Fatalf("lease after demotion = %d, %v", after, err)
}
}
func TestMoveIssuePersistenceInTxTargetCollisionRollsBackSource(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-collision", Title: "source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"source-label"}}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if _, err := store.db.ExecContext(ctx, `INSERT INTO wisps (id, title, description, design, acceptance_criteria, notes, status, priority, issue_type, ephemeral, is_blocked) VALUES (?, ?, '', '', '', '', ?, ?, ?, ?, ?)`, issue.ID, "target", types.StatusOpen, 2, types.TypeTask, true, 0); err != nil {
t.Fatal(err)
}
err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral, "test-actor")
return err
})
if err == nil {
t.Fatal("move into occupied target succeeded")
}
var sourceLabels int
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM labels WHERE issue_id = ? AND label = 'source-label'`, issue.ID).Scan(&sourceLabels); err != nil {
t.Fatal(err)
}
if sourceLabels != 1 {
t.Fatalf("source aggregate was not rolled back; labels = %d", sourceLabels)
}
}
func TestMoveIssuePersistenceInTxLateCounterConflictRollsBack(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-late-rollback", Title: "source", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: []string{"source-label"}}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
if _, err := store.AddIssueComment(ctx, issue.ID, "tester", "source comment"); err != nil {
t.Fatal(err)
}
if _, err := store.db.ExecContext(ctx, `INSERT INTO child_counters (parent_id, last_child) VALUES (?, ?)`, issue.ID, 3); err != nil {
t.Fatal(err)
}
// wisp_child_counters deliberately allows orphaned rows while a target wisp
// is absent. This duplicate is reached after the target issue, labels,
// comments, and events have been inserted, so it proves transaction rollback.
if _, err := store.db.ExecContext(ctx, `SET FOREIGN_KEY_CHECKS = 0`); err != nil {
t.Fatal(err)
}
if _, err := store.db.ExecContext(ctx, `INSERT INTO wisp_child_counters (parent_id, last_child) VALUES (?, ?)`, issue.ID, 9); err != nil {
t.Fatal(err)
}
if _, err := store.db.ExecContext(ctx, `SET FOREIGN_KEY_CHECKS = 1`); err != nil {
t.Fatal(err)
}
err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
_, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral, "test-actor")
return err
})
if err == nil {
t.Fatal("late child-counter conflict did not fail move")
}
var sourceIssue, targetIssue, sourceLabels, sourceComments, targetLabels, targetComments, sourceCounter, targetCounter int
for _, check := range []struct {
query string
dest *int
}{
{`SELECT COUNT(*) FROM issues WHERE id = ?`, &sourceIssue}, {`SELECT COUNT(*) FROM wisps WHERE id = ?`, &targetIssue},
{`SELECT COUNT(*) FROM labels WHERE issue_id = ?`, &sourceLabels}, {`SELECT COUNT(*) FROM comments WHERE issue_id = ?`, &sourceComments},
{`SELECT COUNT(*) FROM wisp_labels WHERE issue_id = ?`, &targetLabels}, {`SELECT COUNT(*) FROM wisp_comments WHERE issue_id = ?`, &targetComments},
{`SELECT COUNT(*) FROM child_counters WHERE parent_id = ? AND last_child = 3`, &sourceCounter}, {`SELECT COUNT(*) FROM wisp_child_counters WHERE parent_id = ? AND last_child = 9`, &targetCounter},
} {
if err := store.db.QueryRowContext(ctx, check.query, issue.ID).Scan(check.dest); err != nil {
t.Fatal(err)
}
}
if sourceIssue != 1 || targetIssue != 0 || sourceLabels != 1 || sourceComments != 1 || targetLabels != 0 || targetComments != 0 || sourceCounter != 1 || targetCounter != 1 {
t.Fatalf("rollback state issues(%d,%d) labels(%d,%d) comments(%d,%d) counters(%d,%d)", sourceIssue, targetIssue, sourceLabels, targetLabels, sourceComments, targetComments, sourceCounter, targetCounter)
}
}
// TestMoveIssuePersistenceInTxRepairsFlagsInTheIssuesPlane pins the same-plane
// branch against the row shape that actually reaches it.
//
// That branch runs when no MOVE is needed but the stored flags still disagree
// with the plane the row is in, and the reachable instance is a DURABLE row
// carrying ephemeral = 1 — what the pre-role proxied update produced. It used
// to issue `UPDATE wisps` unconditionally, so the repair matched no row in the
// issues plane and still reported Changed: true: `bd update <id> --persistent`
// printed success and left the flag set.
//
// The assertion is on the STORED ROW rather than on the result, because
// reporting the change is exactly what the bug did correctly.
func TestMoveIssuePersistenceInTxRepairsFlagsInTheIssuesPlane(t *testing.T) {
store, cleanup := setupTestStore(t)
defer cleanup()
ctx := context.Background()
issue := &types.Issue{ID: "persist-repair", Title: "repair", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatal(err)
}
// The corruption the changelog certifies exists: durable row, wisp flag.
if _, err := store.db.ExecContext(ctx, `UPDATE issues SET ephemeral = 1 WHERE id = ?`, issue.ID); err != nil {
t.Fatal(err)
}
var moved issueops.PersistenceMoveResult
if err := store.withRetryTx(ctx, func(tx *sql.Tx) error {
current, err := issueops.GetIssueInTx(ctx, tx, issue.ID)
if err != nil {
return err
}
moved, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModePersistent, "test-actor")
return err
}); err != nil {
t.Fatalf("repairing a durable row with the wisp flag set: %v", err)
}
if !moved.Changed || !moved.ChangedTables["issues"] {
t.Errorf("move result = %#v, want the issues table reported changed", moved)
}
var ephemeral bool
if err := store.db.QueryRowContext(ctx, `SELECT ephemeral FROM issues WHERE id = ?`, issue.ID).Scan(&ephemeral); err != nil {
t.Fatal(err)
}
if ephemeral {
t.Error("issues.ephemeral is still 1: --persistent reported success and repaired nothing")
}
var wisps int
if err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM wisps WHERE id = ?`, issue.ID).Scan(&wisps); err != nil {
t.Fatal(err)
}
if wisps != 0 {
t.Errorf("wisps rows = %d, want 0: a same-plane repair must not move the row", wisps)
}
}