beads/internal/storage/domain/db/issue.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

1322 lines
50 KiB
Go

package db
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"slices"
"strconv"
"strings"
"time"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/storage/sqlbuild"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
func NewIssueSQLRepository(runner Runner) domain.IssueSQLRepository {
return &issueSQLRepositoryImpl{
runner: runner,
events: NewEventsSQLRepository(runner),
}
}
type issueSQLRepositoryImpl struct {
runner Runner
events domain.EventsSQLRepository
}
var _ domain.IssueSQLRepository = (*issueSQLRepositoryImpl)(nil)
// issueSelectColumns aliases the shared canonical column list; the scan side
// delegates to issueops.ScanIssueFrom, which scans it positionally.
const issueSelectColumns = sqlbuild.IssueSelectColumns
var allowedUpdateFields = map[string]struct{}{
"status": {}, "priority": {}, "title": {}, "assignee": {}, "owner": {},
"description": {}, "design": {}, "acceptance_criteria": {}, "notes": {},
"issue_type": {}, "estimated_minutes": {}, "external_ref": {}, "spec_id": {},
"started_at": {}, "closed_at": {}, "close_reason": {}, "closed_by_session": {},
"source_repo": {}, "sender": {}, "wisp": {}, "wisp_type": {}, "no_history": {}, "pinned": {},
"mol_type": {}, "event_kind": {}, "actor": {}, "target": {}, "payload": {},
"due_at": {}, "defer_until": {}, "await_id": {}, "waiters": {},
"metadata": {},
}
var updateFieldColumnRename = map[string]string{
"wisp": "ephemeral",
}
func (r *issueSQLRepositoryImpl) Insert(ctx context.Context, issue *types.Issue, actor string, opts domain.InsertIssueOpts) error {
if issue == nil {
return errors.New("db: Insert: issue must not be nil")
}
normalizeIssueTimestamps(issue)
if issue.ContentHash == "" {
issue.ContentHash = issue.ComputeContentHash()
}
if issue.ID == "" {
return errors.New("db: Insert: explicit ID required (ID generation belongs to CreateIssueUseCase)")
}
table := pickIssueTable(opts.UseWispsTable)
if opts.CreateOnly {
if err := issueops.EnsureIssueIDAvailableInTx(ctx, r.runner, issue.ID); err != nil {
return err
}
if err := issueops.InsertIssueStrictInTx(ctx, r.runner, table, issue); err != nil {
return err
}
if err := r.events.Record(ctx, domain.Event{
IssueID: issue.ID,
Type: types.EventCreated,
Actor: actor,
}, domain.RecordEventOpts{UseWispsTable: opts.UseWispsTable}); err != nil {
return err
}
if err := issueops.RecordEventInTx(ctx, r.runner, issueops.EventCreate, issue.ID, actor); err != nil {
return err
}
return issueops.RecordVersionInTx(ctx, r.runner, issue.ID, actor)
}
if err := insertIssueRow(ctx, r.runner, table, issue); err != nil {
return err
}
if err := r.events.Record(ctx, domain.Event{
IssueID: issue.ID,
Type: types.EventCreated,
Actor: actor,
}, domain.RecordEventOpts{UseWispsTable: opts.UseWispsTable}); err != nil {
return err
}
if err := issueops.RecordEventInTx(ctx, r.runner, issueops.EventCreate, issue.ID, actor); err != nil {
return err
}
return issueops.RecordVersionInTx(ctx, r.runner, issue.ID, actor)
}
func (r *issueSQLRepositoryImpl) InsertBatch(ctx context.Context, issues []*types.Issue, actor string, opts domain.InsertIssueOpts) error {
for _, issue := range issues {
if err := r.Insert(ctx, issue, actor, opts); err != nil {
return err
}
}
return nil
}
// PromoteFromEphemeral promotes an active wisp into the Dolt-versioned issues
// plane in place: same id, wisp_type retained, labels/dependencies/events/
// comments carried across to the permanent tables, inbound wisp-targeted
// dependency edges retargeted, and blocked state recomputed. It runs the
// issueops implementation DoltStorage.PromoteFromEphemeral runs and returns
// its error unwrapped ("wisp <id> not found"). `bd promote` no longer reaches
// it on any route: issueops.Promote makes the persistence move instead
// (MovePersistence below, on this layer), which also carries the child
// counter.
func (r *issueSQLRepositoryImpl) PromoteFromEphemeral(ctx context.Context, id, actor string) error {
if id == "" {
return errors.New("db: PromoteFromEphemeral: id must not be empty")
}
return issueops.PromoteFromEphemeralInTx(ctx, r.runner, id, actor)
}
func (r *issueSQLRepositoryImpl) MovePersistence(ctx context.Context, id string, mode types.PersistenceMode, actor string) (bool, error) {
issue, err := issueops.GetIssueInTx(ctx, r.runner, id)
if err != nil {
return false, fmt.Errorf("db: MovePersistence %s: get issue: %w", id, err)
}
result, err := issueops.MoveIssuePersistenceInTx(ctx, r.runner, issue, mode, actor)
if err != nil {
return false, fmt.Errorf("db: MovePersistence %s: %w", id, err)
}
return result.Changed, nil
}
func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates map[string]any, actor string, opts domain.IssueTableOpts) error {
if id == "" {
return errors.New("db: Update: id must not be empty")
}
if len(updates) == 0 {
return nil
}
updates = cloneUpdateFields(updates)
// Pop the close-policy override before anything reads the map as a set of
// columns, mirroring issueops.updateIssueInTx. The no-op filter below keeps
// unrecognized keys, so a surviving override would reach the field
// allowlist and be refused by name.
forceClosePolicy := issueops.PopForceClosePolicy(updates)
// Bound the VARCHAR(255) assignment columns before touching SQL, mirroring
// issueops.updateIssueInTx: an over-length assignee/owner aborts with a typed
// ErrFieldTooLong instead of a raw backend "data too long" error.
for _, field := range []string{"assignee", "owner"} {
if raw, ok := updates[field]; ok {
if val, ok := raw.(string); ok {
if err := types.CheckFieldLen(field, val); err != nil {
return err
}
}
}
}
table := pickIssueTable(opts.UseWispsTable)
mergeOps := issueops.HasMergeOps(updates)
// Read the prior row once. Status and merge updates need it for their
// transaction-local resolution, and every update uses it to suppress true
// no-ops before changing row_lock or recording an event.
oldIssue, err := r.Get(ctx, id, opts)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("db: Update %s: %w", id, sql.ErrNoRows)
}
return fmt.Errorf("db: Update %s: read old issue: %w", id, err)
}
// Resolve read-merge-write operation keys (issueops.OpMergeMetadata,
// OpSetMetadata, OpUnsetMetadata, OpAppendNotes) into concrete column
// values inside the mutation transaction, mirroring the embedded path
// (issueops.updateIssueInTx). Callers must pass the OPERATION, never a
// value pre-merged from an earlier read: this runner is a Dolt sql-server
// session where FOR UPDATE is a parse-only no-op, so a stale-snapshot merge
// is only made safe by Dolt's commit-time conflict detection plus the
// caller redoing the whole unit of work on a serialization failure — and
// that redo re-runs this in-transaction resolution against the winner's
// committed row.
if mergeOps {
resolved, err := issueops.ResolveMergeOps(oldIssue, updates)
if err != nil {
return fmt.Errorf("db: Update %s: %w", id, err)
}
updates = resolved
}
// closed_at coherence parity with issueops.updateIssueInTx: an explicit
// closed_at must agree with the status this update lands, checked against
// the row this unit of work already read and ahead of the close-policy gate
// so a refusal writes nothing at all. It runs on the merge-resolved map
// BEFORE the no-op filter for the same reason it does there — the guard
// reads the caller's intent, and a closed_at equal to the stored value is
// still a request to keep the column, not an absent key.
if err := issueops.ValidateClosedAtCoherence(oldIssue, updates); err != nil {
return fmt.Errorf("db: Update %s: %w", id, err)
}
filteredUpdates, err := issueops.DiscardNoopIssueUpdates(oldIssue, updates)
if err != nil {
return fmt.Errorf("db: Update %s: compare updates: %w", id, err)
}
updates = filteredUpdates
if len(updates) == 0 {
return nil
}
// A status that matched the row was already dropped as a no-op, so the
// lifecycle side effects below only fire on a real transition.
_, statusChanging := updates["status"]
// Close-policy parity with issueops.updateIssueInTx: a status that crosses
// into the done category is a close by another name and answers to close
// policy, and, as there, to close policy only: the pin and assignee close
// guards stay on the close verbs (see updateIssueInTx for why). A refusal
// returns before any write and aborts the caller's unit of work. The wrap
// keeps the sentinels matchable, so a caller distinguishes these refusals
// here exactly as it does on the close path.
if statusChanging {
crossing, err := issueops.CrossesIntoDoneCategoryInTx(ctx, r.runner, oldIssue.Status, updates)
if err != nil {
return fmt.Errorf("db: Update %s: %w", id, err)
}
if crossing {
if _, err := issueops.EnforceClosePolicyInTx(ctx, r.runner, id, forceClosePolicy); err != nil {
return fmt.Errorf("db: Update %s: %w", id, err)
}
}
}
setClauses := make([]string, 0, len(updates)+3)
args := make([]any, 0, len(updates)+4)
for key, value := range updates {
if _, ok := allowedUpdateFields[key]; !ok {
return fmt.Errorf("db: Update: field %q is not allowed", key)
}
column := key
if renamed, ok := updateFieldColumnRename[key]; ok {
column = renamed
}
setClauses = append(setClauses, fmt.Sprintf("`%s` = ?", column))
args = append(args, normalizeUpdateValue(key, value))
}
setClauses = append(setClauses, "updated_at = ?")
args = append(args, time.Now().UTC())
// Lifecycle parity with issueops.updateIssueInTx: auto-manage closed_at and
// started_at from the status transition unless the caller set them
// explicitly.
if statusChanging {
setClauses, args = issueops.ManageClosedAt(oldIssue, updates, setClauses, args)
setClauses, args = issueops.ManageStartedAt(oldIssue, updates, setClauses, args)
}
clearLease := issueops.ManageLeaseOnUpdate(oldIssue, updates)
// Rewrite row_lock on every generic update, mirroring the classic
// issueops.updateIssueInTx invariant (update.go): a concurrent
// status/ownership mutation collides on this shared cell instead of
// silently cell-merging, and the row's RowVersion CAS token advances so
// the "generic update path changes RowVersion" contract
// (types.Issue.RowVersion) holds on the proxied backend too.
rowLockClause, rowLockArgs := issueops.RowLockClause()
setClauses = append(setClauses, rowLockClause)
args = append(args, rowLockArgs...)
args = append(args, id)
//nolint:gosec // G201: table is one of two hardcoded constants
q := fmt.Sprintf("UPDATE %s SET %s WHERE id = ?", table, strings.Join(setClauses, ", "))
res, err := r.runner.ExecContext(ctx, q, args...)
if err != nil {
return fmt.Errorf("db: Update %s: %w", id, err)
}
rows, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("db: Update %s: rows affected: %w", id, err)
}
if rows == 0 {
return fmt.Errorf("db: Update %s: %w", id, sql.ErrNoRows)
}
if clearLease && !opts.UseWispsTable {
if err := issueops.DeleteLeaseInTx(ctx, r.runner, id); err != nil {
return fmt.Errorf("db: Update %s: clear lease: %w", id, err)
}
}
// Event-type parity: embedded records EventClosed / EventReopened /
// EventStatusChanged for status transitions (issueops.DetermineEventType),
// EventUpdated otherwise.
eventType := types.EventUpdated
if statusChanging {
eventType = issueops.DetermineEventType(oldIssue, updates)
}
if err := r.events.Record(ctx, domain.Event{
IssueID: id,
Type: eventType,
Actor: actor,
}, domain.RecordEventOpts{UseWispsTable: opts.UseWispsTable}); err != nil {
return err
}
if statusChanging {
newStatus := coerceStatus(updates["status"])
oldActive := oldIssue.Status != types.StatusClosed && oldIssue.Status != types.StatusPinned
newActive := newStatus != types.StatusClosed && newStatus != types.StatusPinned
if oldActive != newActive {
var (
affectedIssues, affectedWisps []string
aerr error
)
if opts.UseWispsTable {
affectedIssues, affectedWisps, aerr = issueops.AffectedByStatusChangeForWispInTx(ctx, r.runner, id)
} else {
affectedIssues, affectedWisps, aerr = issueops.AffectedByStatusChangeInTx(ctx, r.runner, id)
}
if aerr != nil {
return fmt.Errorf("db: Update %s: affected by status change: %w", id, aerr)
}
if err := issueops.RecomputeIsBlockedInTx(ctx, r.runner, affectedIssues, affectedWisps); err != nil {
return fmt.Errorf("db: Update %s: recompute is_blocked: %w", id, err)
}
if !newActive {
issueops.NoteStatusChangeBlockedRecheck(r.runner, id, string(newStatus), affectedIssues, affectedWisps)
}
}
}
// Snapshot only after all derived blocked-state maintenance has completed.
// The no-op early returns above wrote nothing and journal nothing.
if err := issueops.RecordEventInTx(ctx, r.runner, issueops.EventUpdate, id, actor); err != nil {
return err
}
return issueops.RecordVersionInTx(ctx, r.runner, id, actor)
}
// CompareAndSetMetadataKey runs the SHARED compare-and-set body, unwrapped.
//
// It is the whole of this leg's implementation, and that is the point: the two
// store backends wrap the same function in their own transaction, so the third
// leg is a wrapper check rather than an independent vote — which is what the
// conformance contract's header says.
//
// It does NOT wrap the error the way its siblings above do, for the reason
// WalkDependencyTree gives: the body publishes storage.ErrNotFound and
// storage.ErrValidation as the role's own vocabulary, both classified by
// errors.Is at every front door, and a "db: ..." prefix would put this
// repository's name into a message the direct route never shows a user.
func (r *issueSQLRepositoryImpl) CompareAndSetMetadataKey(ctx context.Context, plan storage.CompareAndSetKeyPlan) (publicops.CompareAndSetKeyResult, bool, error) {
result, write, err := issueops.CompareAndSetMetadataKeyInTx(ctx, r.runner, plan)
return result, write.Wrote, err
}
// ReleaseIssue runs the SHARED claim-release body, unwrapped.
//
// It is the whole of this leg's implementation, and that is the point: the two
// store backends wrap the same function in their own transaction, so the third
// leg is a wrapper check rather than an independent vote — which is what the
// conformance contract's header says.
//
// It reports the body's Wrote — "a row was written" — and NOT the durable table
// set beside it, which is the half of ReleaseWrite the two STORE legs want. The
// difference is load-bearing on this leg and it cost a red test to find: an
// ephemeral release writes a wisp row and changes no versioned table, and this
// leg's commit message is what commits the SQL transaction as well as what
// versions it, so reporting the table set here composes no message and rolls the
// release back — the wisp comes out still claimed. The version-control layer
// below already demotes a commit with nothing pending to a plain SQL COMMIT, so
// answering the row fact costs no spurious history entry.
//
// It does NOT wrap the error, for the reason CompareAndSetMetadataKey gives.
func (r *issueSQLRepositoryImpl) ReleaseIssue(ctx context.Context, req publicops.ReleaseRequest) (publicops.ReleaseResult, bool, error) {
result, write, err := issueops.ReleaseIssueInTx(ctx, r.runner, req)
return result, write.Wrote, err
}
func cloneUpdateFields(updates map[string]any) map[string]any {
cloned := make(map[string]any, len(updates))
for key, value := range updates {
cloned[key] = value
}
return cloned
}
func coerceStatus(v any) types.Status {
switch s := v.(type) {
case string:
return types.Status(s)
case types.Status:
return s
default:
return ""
}
}
func (r *issueSQLRepositoryImpl) Claim(ctx context.Context, id, actor string, opts domain.IssueTableOpts) (domain.ClaimRowResult, error) {
if id == "" {
return domain.ClaimRowResult{}, errors.New("db: Claim: id must not be empty")
}
// The CAS below writes assignee = actor. actor is user-settable (--actor /
// BEADS_ACTOR), so bound it against the VARCHAR(255) assignee column up front
// and return a typed ErrFieldTooLong rather than a raw backend error.
if err := types.CheckFieldLen("actor", actor); err != nil {
return domain.ClaimRowResult{}, err
}
oldIssue, err := r.Get(ctx, id, opts)
if err != nil {
return domain.ClaimRowResult{}, fmt.Errorf("db: Claim %s: read old issue: %w", id, err)
}
table := pickIssueTable(opts.UseWispsTable)
now := time.Now().UTC()
startedWasZero := oldIssue.StartedAt == nil
// Rewrite row_lock exactly like the primary claim path (issueops.
// ClaimIssueInTx). Without this, a claim made through the proxied-server
// (uow) path leaves row_lock unchanged — open to the cell-merge bug the
// row_lock invariant guards against (see issueops/lease.go). The lease
// itself is granted into the ephemeral leases table below, after the CAS.
rowLockClause, rowLockArgs := issueops.RowLockClause()
// Mirror the primary path's pool-aware predicate (bd-bguz6): aliases in
// the claim.pools config are claimable by any actor. This dual must stay
// in lockstep with issueops.ClaimIssueInTx — the lease comment above is
// the scar from the last time it drifted.
pools, err := issueops.ClaimPoolAliasesInTx(ctx, r.runner)
if err != nil {
return domain.ClaimRowResult{}, fmt.Errorf("db: Claim %s: resolve claim pools: %w", id, err)
}
// Claimability of the assignee slot, judged in Go against oldIssue rather
// than as a spelling-sensitive SQL predicate (ga-v2k49, mirroring the
// same-day fix to issueops.ClaimIssueInTx — this dual must stay in
// lockstep, per the comment above): empty/unassigned, already this actor
// — including a spelling difference across layers (ga-wzl83) — or a
// claim-pool alias. issueops.ActorMatches is the exported form of the
// primary path's package-local actorMatches, kept for exactly this dual.
assigneeOK := oldIssue.Assignee == "" || issueops.ActorMatches(oldIssue.Assignee, actor) || slices.Contains(pools, oldIssue.Assignee)
// Same lockstep for the source statuses (bd-pq7m2): claimable from "open"
// plus custom active-category statuses, like the primary path — not a
// hardcoded status = 'open'.
claimableStatuses, err := issueops.ClaimableSourceStatusesInTx(ctx, r.runner)
if err != nil {
return domain.ClaimRowResult{}, fmt.Errorf("db: Claim %s: resolve claimable statuses: %w", id, err)
}
statusPredicate := "status = ?"
statusArgs := []any{claimableStatuses[0]}
for _, st := range claimableStatuses[1:] {
statusPredicate += " OR status = ?"
statusArgs = append(statusArgs, st)
}
// Conditional UPDATE, attempted only while assigneeOK — otherwise there
// is nothing this actor could win, so skip straight to the rows==0
// disambiguation below (matches the primary path's ga-v2k49 fix). CASed
// on row_lock rather than re-checking assignee in SQL: row_lock is
// rewritten by every path that mutates status/assignee/started_at (see
// the freshRowLock invariant in issueops/lease.go), so requiring it to
// still equal oldIssue.RowVersion detects a race exactly as precisely as
// the old assignee predicate did, without embedding a spelling-sensitive
// string comparison in SQL.
var rows int64
if assigneeOK {
var res sql.Result
if startedWasZero {
args := append([]any{actor, now, now}, rowLockArgs...)
args = append(args, id, oldIssue.RowVersion)
args = append(args, statusArgs...)
//nolint:gosec // G201: table is one of two hardcoded constants
res, err = r.runner.ExecContext(ctx, fmt.Sprintf(`
UPDATE %s
SET assignee = ?, status = 'in_progress', updated_at = ?, started_at = ?, %s
WHERE id = ? AND row_lock = ? AND (%s)
`, table, rowLockClause, statusPredicate), args...)
} else {
args := append([]any{actor, now}, rowLockArgs...)
args = append(args, id, oldIssue.RowVersion)
args = append(args, statusArgs...)
//nolint:gosec // G201: table is one of two hardcoded constants
res, err = r.runner.ExecContext(ctx, fmt.Sprintf(`
UPDATE %s
SET assignee = ?, status = 'in_progress', updated_at = ?, %s
WHERE id = ? AND row_lock = ? AND (%s)
`, table, rowLockClause, statusPredicate), args...)
}
if err != nil {
return domain.ClaimRowResult{}, fmt.Errorf("db: Claim %s: %w", id, err)
}
rows, err = res.RowsAffected()
if err != nil {
return domain.ClaimRowResult{}, fmt.Errorf("db: Claim %s: rows affected: %w", id, err)
}
}
if rows == 0 {
var currentAssignee sql.NullString
var currentStatus types.Status
//nolint:gosec // G201: table is one of two hardcoded constants
if err := r.runner.QueryRowContext(ctx,
fmt.Sprintf("SELECT assignee, status FROM %s WHERE id = ?", table), id,
).Scan(&currentAssignee, &currentStatus); err != nil {
return domain.ClaimRowResult{}, fmt.Errorf("db: Claim %s: read current state: %w", id, err)
}
assignee := ""
if currentAssignee.Valid {
assignee = currentAssignee.String
}
return domain.ClaimRowResult{
Updated: false,
CurrentAssignee: assignee,
CurrentAssigneeIsPool: slices.Contains(pools, assignee),
CurrentStatus: currentStatus,
StartedAtWasZero: startedWasZero,
OldIssue: oldIssue,
}, nil
}
// Grant the lease in the ephemeral leases table, mirroring
// issueops.ClaimIssueInTx. Wisps are never leased. This dual must stay in
// lockstep with the primary path (see the row_lock comment above).
if !opts.UseWispsTable {
if err := issueops.UpsertLeaseInTx(ctx, r.runner, id, actor, now, issueops.LeaseTTL(ctx)); err != nil {
return domain.ClaimRowResult{}, fmt.Errorf("db: Claim %s: %w", id, err)
}
}
oldData, _ := json.Marshal(oldIssue)
newData, _ := json.Marshal(map[string]any{"assignee": actor, "status": "in_progress"})
if err := r.events.Record(ctx, domain.Event{
IssueID: id,
Type: types.EventType("claimed"),
Actor: actor,
OldValue: string(oldData),
NewValue: string(newData),
}, domain.RecordEventOpts{UseWispsTable: opts.UseWispsTable}); err != nil {
return domain.ClaimRowResult{}, fmt.Errorf("db: Claim %s: record event: %w", id, err)
}
// A claim changes assignee and status; the lost-CAS path returns above
// without writing and journals nothing — nor mints anything. A claim that
// rewrote the row is versioned, as issueops.ClaimIssueInTx is.
if err := issueops.RecordEventInTx(ctx, r.runner, issueops.EventUpdate, id, actor); err != nil {
return domain.ClaimRowResult{}, err
}
if err := issueops.RecordVersionInTx(ctx, r.runner, id, actor); err != nil {
return domain.ClaimRowResult{}, err
}
return domain.ClaimRowResult{
Updated: true,
CurrentAssignee: actor,
CurrentStatus: types.StatusInProgress,
StartedAtWasZero: startedWasZero,
OldIssue: oldIssue,
}, nil
}
func (r *issueSQLRepositoryImpl) Get(ctx context.Context, id string, opts domain.IssueTableOpts) (*types.Issue, error) {
if id == "" {
return nil, errors.New("db: Get: id must not be empty")
}
table := pickIssueTable(opts.UseWispsTable)
//nolint:gosec // G201: table is one of two hardcoded constants
row := r.runner.QueryRowContext(ctx, fmt.Sprintf("SELECT %s FROM %s %s WHERE id = ?",
issueSelectColumns, table, sqlbuild.LeaseJoin(table)), id)
issue, err := scanIssue(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, sql.ErrNoRows
}
if err != nil {
return nil, fmt.Errorf("db: Get %s: %w", id, err)
}
return issue, nil
}
func (r *issueSQLRepositoryImpl) GetByIDs(ctx context.Context, ids []string, opts domain.IssueTableOpts) ([]*types.Issue, error) {
table := pickIssueTable(opts.UseWispsTable)
var out []*types.Issue
err := forEachIDBatch(ids, func(batch []string) error {
placeholders, args := buildInPlaceholders(batch)
//nolint:gosec // G201: table is one of two hardcoded constants
q := fmt.Sprintf("SELECT %s FROM %s %s WHERE id IN (%s)",
issueSelectColumns, table, sqlbuild.LeaseJoin(table), placeholders)
rows, err := r.runner.QueryContext(ctx, q, args...)
if err != nil {
return fmt.Errorf("db: GetByIDs: %w", err)
}
defer rows.Close()
for rows.Next() {
issue, err := scanIssue(rows)
if err != nil {
return fmt.Errorf("db: GetByIDs: scan: %w", err)
}
out = append(out, issue)
}
if err := rows.Err(); err != nil {
return fmt.Errorf("db: GetByIDs: rows: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
return out, nil
}
// GetMany runs the SHARED batch-read body on r.runner, which publishes
// exactly the DBTX method set issueops.ExecuteGetMany takes. There is no
// table option here, the way CompareAndSetMetadataKey has none: the shared
// body routes both planes itself through GetIssuesByIDsInTx.
func (r *issueSQLRepositoryImpl) GetMany(ctx context.Context, request publicops.GetManyRequest) (publicops.GetManyResult, error) {
return issueops.ExecuteGetMany(ctx, r.runner, request)
}
func (r *issueSQLRepositoryImpl) Exists(ctx context.Context, id string, opts domain.IssueTableOpts) (bool, error) {
if id == "" {
return false, errors.New("db: Exists: id must not be empty")
}
table := pickIssueTable(opts.UseWispsTable)
//nolint:gosec // G201: table is one of two hardcoded constants
row := r.runner.QueryRowContext(ctx, fmt.Sprintf("SELECT 1 FROM %s WHERE id = ? LIMIT 1", table), id)
var one int
err := row.Scan(&one)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("db: Exists %s: %w", id, err)
}
return true, nil
}
func (r *issueSQLRepositoryImpl) CountForPrefix(ctx context.Context, prefix string, opts domain.IssueTableOpts) (int, error) {
if prefix == "" {
return 0, errors.New("db: CountForPrefix: prefix must not be empty")
}
table := pickIssueTable(opts.UseWispsTable)
var count int
//nolint:gosec // G201: table is one of two hardcoded constants
err := r.runner.QueryRowContext(ctx, fmt.Sprintf(`
SELECT COUNT(*)
FROM %s
WHERE id LIKE CONCAT(?, '-%%')
AND INSTR(SUBSTRING(id, LENGTH(?) + 2), '.') = 0
`, table), prefix, prefix).Scan(&count)
if err != nil {
return 0, fmt.Errorf("db: CountForPrefix %s: %w", prefix, err)
}
return count, nil
}
func (r *issueSQLRepositoryImpl) NextCounterID(ctx context.Context, prefix string) (int, error) {
if prefix == "" {
return 0, errors.New("db: NextCounterID: prefix must not be empty")
}
res, err := r.runner.ExecContext(ctx, "UPDATE issue_counter SET last_id = last_id + 1 WHERE prefix = ?", prefix)
if err != nil {
return 0, fmt.Errorf("db: NextCounterID: increment %q: %w", prefix, err)
}
rows, err := res.RowsAffected()
if err != nil {
return 0, fmt.Errorf("db: NextCounterID: rows affected %q: %w", prefix, err)
}
if rows == 0 {
if err := r.seedCounterFromExisting(ctx, prefix); err != nil {
return 0, fmt.Errorf("db: NextCounterID: seed %q: %w", prefix, err)
}
res, err = r.runner.ExecContext(ctx, "UPDATE issue_counter SET last_id = last_id + 1 WHERE prefix = ?", prefix)
if err != nil {
return 0, fmt.Errorf("db: NextCounterID: increment after seed %q: %w", prefix, err)
}
rows, err = res.RowsAffected()
if err != nil {
return 0, fmt.Errorf("db: NextCounterID: rows affected after seed %q: %w", prefix, err)
}
if rows == 0 {
if _, err := r.runner.ExecContext(ctx, "INSERT INTO issue_counter (prefix, last_id) VALUES (?, 1)", prefix); err != nil {
return 0, fmt.Errorf("db: NextCounterID: insert initial %q: %w", prefix, err)
}
}
}
var nextID int
if err := r.runner.QueryRowContext(ctx, "SELECT last_id FROM issue_counter WHERE prefix = ?", prefix).Scan(&nextID); err != nil {
return 0, fmt.Errorf("db: NextCounterID: read last_id %q: %w", prefix, err)
}
return nextID, nil
}
func (r *issueSQLRepositoryImpl) seedCounterFromExisting(ctx context.Context, prefix string) error {
var existing int
err := r.runner.QueryRowContext(ctx, "SELECT last_id FROM issue_counter WHERE prefix = ?", prefix).Scan(&existing)
if err == nil {
return nil
}
if !errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("read existing counter %q: %w", prefix, err)
}
rows, err := r.runner.QueryContext(ctx, "SELECT id FROM issues WHERE id LIKE CONCAT(?, '-%')", prefix)
if err != nil {
return fmt.Errorf("scan issues for %q: %w", prefix, err)
}
defer rows.Close()
maxNum := 0
pfxDash := prefix + "-"
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
continue
}
suffix := strings.TrimPrefix(id, pfxDash)
if strings.Contains(suffix, ".") {
continue
}
if n, err := strconv.Atoi(suffix); err == nil && n > maxNum {
maxNum = n
}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate issues for %q: %w", prefix, err)
}
if maxNum > 0 {
if _, err := r.runner.ExecContext(ctx, "INSERT INTO issue_counter (prefix, last_id) VALUES (?, ?)", prefix, maxNum); err != nil {
return fmt.Errorf("seed counter %q at %d: %w", prefix, maxNum, err)
}
}
return nil
}
func normalizeIssueTimestamps(issue *types.Issue) {
now := time.Now().UTC()
if issue.CreatedAt.IsZero() {
issue.CreatedAt = now
} else {
issue.CreatedAt = issue.CreatedAt.UTC()
}
if issue.UpdatedAt.IsZero() {
issue.UpdatedAt = now
} else {
issue.UpdatedAt = issue.UpdatedAt.UTC()
}
// Optional timestamps (closed_at, started_at, due_at, …) may arrive from a
// JSONL import carrying a non-UTC offset; normalize them to UTC so the stored
// instant matches created_at/updated_at instead of keeping local wall-clock.
issue.NormalizeOptionalTimestampsToUTC()
}
func pickIssueTable(useWisps bool) string {
if useWisps {
return "wisps"
}
return "issues"
}
//nolint:gosec // G201: table is a hardcoded constant ("issues" or "wisps")
func insertIssueRow(ctx context.Context, runner Runner, table string, issue *types.Issue) error {
// Bound the VARCHAR(255) assignment columns at the raw-SQL chokepoint, so
// every proxied-server (uow) create — single, batch, and import — rejects an
// over-length assignee/owner with a typed ErrFieldTooLong instead of a raw
// backend "data too long" error. Mirrors ValidateWithCustom on the embedded
// create path.
if err := types.CheckFieldLen("assignee", issue.Assignee); err != nil {
return err
}
if err := types.CheckFieldLen("owner", issue.Owner); err != nil {
return err
}
// Stamp a fresh non-zero row_lock at create, exactly like the classic
// insertIssueIntoTable (issueops/helpers.go). Without it a proxied-server
// (uow) create leaves row_lock at the schema DEFAULT 0, so the row's
// RowVersion CAS token is stale-zero on read — the backend-divergent break
// the RowVersion contract (types.Issue.RowVersion) forbids. The duplicate-key
// path rewrites it too so an upsert also advances the token.
_, err := runner.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO %s (
id, content_hash, title, description, design, acceptance_criteria, notes,
status, priority, issue_type, assignee, estimated_minutes,
created_at, created_by, owner, updated_at, started_at, closed_at, external_ref, spec_id,
compaction_level, compacted_at, compacted_at_commit, original_size,
sender, ephemeral, no_history, wisp_type, pinned, is_template,
mol_type, work_type, source_system, source_repo, close_reason,
event_kind, actor, target, payload,
await_type, await_id, timeout_ns, waiters,
due_at, defer_until, metadata,
row_lock, storage_class
) VALUES (
?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?,
?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?,
?, ?, ?, ?,
?, ?, ?,
?, ?
)
ON DUPLICATE KEY UPDATE
content_hash = VALUES(content_hash),
title = VALUES(title),
description = VALUES(description),
design = VALUES(design),
acceptance_criteria = VALUES(acceptance_criteria),
notes = VALUES(notes),
status = VALUES(status),
priority = VALUES(priority),
issue_type = VALUES(issue_type),
assignee = VALUES(assignee),
estimated_minutes = VALUES(estimated_minutes),
updated_at = VALUES(updated_at),
started_at = VALUES(started_at),
closed_at = VALUES(closed_at),
external_ref = VALUES(external_ref),
source_repo = VALUES(source_repo),
close_reason = VALUES(close_reason),
metadata = VALUES(metadata),
row_lock = VALUES(row_lock)
`, table),
issue.ID, issue.ContentHash, issue.Title, issue.Description, issue.Design, issue.AcceptanceCriteria, issue.Notes,
string(issue.Status), issue.Priority, string(issue.IssueType), nullString(issue.Assignee), nullIntPtr(issue.EstimatedMinutes),
issue.CreatedAt, issue.CreatedBy, issue.Owner, issue.UpdatedAt, issue.StartedAt, issue.ClosedAt, nullStringPtr(issue.ExternalRef), issue.SpecID,
issue.CompactionLevel, issue.CompactedAt, nullStringPtr(issue.CompactedAtCommit), nullIntVal(issue.OriginalSize),
issue.Sender, issue.Ephemeral, issue.NoHistory, string(issue.WispType), issue.Pinned, issue.IsTemplate,
string(issue.MolType), string(issue.WorkType), issue.SourceSystem, issue.SourceRepo, issue.CloseReason,
issue.EventKind, issue.Actor, issue.Target, issue.Payload,
issue.AwaitType, issue.AwaitID, issue.Timeout.Nanoseconds(), formatJSONStringArray(issue.Waiters),
issue.DueAt, issue.DeferUntil, jsonMetadata(issue.Metadata),
issueops.FreshRowLock(), nullString(string(issue.StorageClass.Normalize())),
)
if err != nil {
return fmt.Errorf("db: insert into %s: %w", table, err)
}
return nil
}
type issueScanner interface {
Scan(dest ...any) error
}
// scanIssue delegates to the classic scan so both stacks hydrate issues with
// identical semantics (bd-6dnrw.44 item 12, extract-don't-duplicate per .46).
// The shared scan reads created_at/updated_at as strings with format
// fallbacks where a hand-rolled sql.NullTime scan hard-fails on any driver
// that hands timestamps back as text.
func scanIssue(s issueScanner) (*types.Issue, error) {
return issueops.ScanIssueFrom(s)
}
func nullString(s string) any {
if s == "" {
return nil
}
return s
}
func nullStringPtr(s *string) any {
if s == nil || *s == "" {
return nil
}
return *s
}
func nullIntPtr(i *int) any {
if i == nil {
return nil
}
return *i
}
func nullIntVal(i int) any {
if i == 0 {
return nil
}
return i
}
func jsonMetadata(raw json.RawMessage) any {
if len(raw) == 0 {
return "{}"
}
return string(raw)
}
func formatJSONStringArray(items []string) string {
if len(items) == 0 {
return ""
}
b, err := json.Marshal(items)
if err != nil {
return ""
}
return string(b)
}
var timestampUpdateFields = map[string]struct{}{
"started_at": {}, "closed_at": {}, "due_at": {}, "defer_until": {},
}
func normalizeUpdateValue(key string, value any) any {
if _, ok := timestampUpdateFields[key]; ok {
switch v := value.(type) {
case time.Time:
return v.UTC()
case *time.Time:
if v == nil {
return nil
}
t := v.UTC()
return t
}
return value
}
switch key {
case "status":
if s, ok := value.(types.Status); ok {
return string(s)
}
case "issue_type":
if t, ok := value.(types.IssueType); ok {
return string(t)
}
case "metadata":
switch v := value.(type) {
case json.RawMessage:
return string(v)
case []byte:
return string(v)
}
case "waiters":
// The column is TEXT holding a JSON array; the embedded path
// (issueops.updateIssueInTx) marshals unconditionally, and a raw
// []string would be refused by the SQL driver here.
waitersJSON, _ := json.Marshal(value)
return string(waitersJSON)
}
return value
}
func (r *issueSQLRepositoryImpl) SearchAcrossIssuesAndWisps(ctx context.Context, query string, filter types.IssueFilter) (domain.SearchPage, error) {
return r.searchAcrossIssuesAndWisps(ctx, query, filter)
}
func (r *issueSQLRepositoryImpl) SearchAcrossIssuesAndWispsWithCounts(ctx context.Context, query string, filter types.IssueFilter) (domain.SearchCountsPage, error) {
return r.searchAcrossIssuesAndWispsWithCounts(ctx, query, filter)
}
// SearchWispsPlane runs the shared wisps-plane search body on this
// repository's transaction, so the unit-of-work provider and the two store
// backends read the plane through one function.
func (r *issueSQLRepositoryImpl) SearchWispsPlane(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) {
return issueops.SearchWispsPlaneInTx(ctx, r.runner, query, filter)
}
func (r *issueSQLRepositoryImpl) SearchIssueIDs(ctx context.Context, query string, filter types.IssueFilter) ([]string, error) {
return issueops.SearchIssueIDsInTx(ctx, r.runner, query, filter)
}
func (r *issueSQLRepositoryImpl) GetReadyWork(ctx context.Context, filter types.WorkFilter) (domain.SearchPage, error) {
return r.getReadyWorkUnion(ctx, filter)
}
func (r *issueSQLRepositoryImpl) GetReadyWorkWithCounts(ctx context.Context, filter types.WorkFilter) (domain.SearchCountsPage, error) {
return r.getReadyWorkWithCountsUnion(ctx, filter)
}
func (r *issueSQLRepositoryImpl) Delete(ctx context.Context, id string, opts domain.IssueTableOpts, actor string) error {
table := "issues"
if opts.UseWispsTable {
table = "wisps"
}
// Edges are journaled before the row goes, while its snapshot can still be
// read.
if err := issueops.RecordDependencyRemovalsForIssuesInTx(ctx, r.runner, []string{id}, actor); err != nil {
return fmt.Errorf("db: IssueSQLRepository.Delete %s: journal dependency removals: %w", id, err)
}
//nolint:gosec // G201: table is a hardcoded constant.
res, err := r.runner.ExecContext(ctx, fmt.Sprintf("DELETE FROM %s WHERE id = ?", table), id)
if err != nil {
return fmt.Errorf("db: IssueSQLRepository.Delete %s from %s: %w", id, table, err)
}
rows, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("db: IssueSQLRepository.Delete rows affected: %w", err)
}
if rows == 0 {
return fmt.Errorf("issue not found: %s", id)
}
// A deleted issue holds no lease (no-op for wisps, which are never leased).
if err := issueops.DeleteLeaseInTx(ctx, r.runner, id); err != nil {
return err
}
// The rows==0 return above keeps this actually-deleted-only.
return issueops.RecordDeleteInTx(ctx, r.runner, id, actor)
}
func (r *issueSQLRepositoryImpl) DeleteByIDs(ctx context.Context, ids []string, opts domain.IssueTableOpts, actor string) (int, error) {
if len(ids) == 0 {
return 0, nil
}
table := "issues"
if opts.UseWispsTable {
table = "wisps"
}
// Resolve WHICH ids this delete actually removes before the batched DELETE
// runs: afterwards the rows are gone, and RowsAffected reports a count, not
// a set. A journal record for an id that was already absent would tell a
// consumer to drop a bead this transaction never touched.
actualIDs, err := issueops.ExistingIssueIDsInTableInTx(ctx, r.runner, table, ids)
if err != nil {
return 0, fmt.Errorf("db: IssueSQLRepository.DeleteByIDs resolve existing ids: %w", err)
}
// Edges are journaled before the rows go, while their source snapshots can
// still be read.
if err := issueops.RecordDependencyRemovalsForIssuesInTx(ctx, r.runner, actualIDs, actor); err != nil {
return 0, fmt.Errorf("db: IssueSQLRepository.DeleteByIDs journal dependency removals: %w", err)
}
total := 0
for start := 0; start < len(ids); start += deleteBatchSize {
end := start + deleteBatchSize
if end > len(ids) {
end = len(ids)
}
batch := ids[start:end]
placeholders := make([]string, len(batch))
args := make([]any, len(batch))
for i, id := range batch {
placeholders[i] = "?"
args[i] = id
}
//nolint:gosec // G201: table is a hardcoded constant; placeholders are ?.
res, err := r.runner.ExecContext(ctx,
fmt.Sprintf("DELETE FROM %s WHERE id IN (%s)", table, strings.Join(placeholders, ",")),
args...)
if err != nil {
return total, fmt.Errorf("db: IssueSQLRepository.DeleteByIDs from %s: %w", table, err)
}
n, err := res.RowsAffected()
if err != nil {
return total, fmt.Errorf("db: IssueSQLRepository.DeleteByIDs rows affected: %w", err)
}
total += int(n)
if !opts.UseWispsTable {
// Deleted issues hold no leases.
//nolint:gosec // G201: placeholders are ?.
if _, err := r.runner.ExecContext(ctx,
fmt.Sprintf("DELETE FROM leases WHERE issue_id IN (%s)", strings.Join(placeholders, ",")),
args...); err != nil {
return total, fmt.Errorf("db: IssueSQLRepository.DeleteByIDs leases: %w", err)
}
}
}
for _, id := range actualIDs {
if err := issueops.RecordDeleteInTx(ctx, r.runner, id, actor); err != nil {
return total, err
}
}
return total, nil
}
func (r *issueSQLRepositoryImpl) PartitionWispIDs(ctx context.Context, ids []string) ([]string, []string, error) {
return issueops.PartitionWispIDsInTx(ctx, r.runner, ids)
}
func (r *issueSQLRepositoryImpl) FindAllDependents(ctx context.Context, ids []string) ([]string, error) {
set, err := issueops.FindAllDependentsInTx(ctx, r.runner, ids)
if err != nil {
return nil, err
}
out := make([]string, 0, len(set))
for id := range set {
out = append(out, id)
}
return out, nil
}
func (r *issueSQLRepositoryImpl) FindWispDependentsRecursive(ctx context.Context, ids []string) (map[string]bool, error) {
return issueops.FindWispDependentsRecursiveInTx(ctx, r.runner, ids)
}
func (r *issueSQLRepositoryImpl) AffectedByDeletion(ctx context.Context, issueIDs, wispIDs []string) ([]string, []string, error) {
return issueops.AffectedByDeletionInTx(ctx, r.runner, issueIDs, wispIDs)
}
func (r *issueSQLRepositoryImpl) RecomputeIsBlockedAfterDelete(ctx context.Context, deletedIDs, issueIDs, wispIDs []string) error {
if err := issueops.RecomputeIsBlockedInTx(ctx, r.runner, issueIDs, wispIDs); err != nil {
return err
}
issueops.NoteDeleteBlockedRecheck(r.runner, deletedIDs, "", issueIDs, wispIDs)
return nil
}
func (r *issueSQLRepositoryImpl) AsOf(ctx context.Context, id, ref string) (*types.Issue, error) {
return issueops.AsOfInTx(ctx, r.runner, id, ref)
}
func (r *issueSQLRepositoryImpl) Close(ctx context.Context, id string, params domain.CloseRowParams, actor string, opts domain.IssueTableOpts) (domain.CloseRowResult, error) {
res, err := issueops.CloseIssueInTx(ctx, r.runner, id, params.Reason, actor, params.Session)
if err != nil {
return domain.CloseRowResult{}, fmt.Errorf("db: IssueSQLRepository.Close %s: %w", id, err)
}
return domain.CloseRowResult{
Updated: !res.AlreadyClosed,
AlreadyClosed: res.AlreadyClosed,
IsWisp: res.IsWisp,
}, nil
}
func (r *issueSQLRepositoryImpl) CloseChecked(ctx context.Context, id string, params domain.CloseRowParams, actor string, force bool) (domain.CloseRowResult, error) {
res, err := issueops.CloseIssueCheckedInTx(ctx, r.runner, id, params.Reason, actor, params.Session, force, nil)
if err != nil {
return domain.CloseRowResult{}, fmt.Errorf("db: IssueSQLRepository.CloseChecked %s: %w", id, err)
}
return domain.CloseRowResult{
Updated: !res.AlreadyClosed,
AlreadyClosed: res.AlreadyClosed,
IsWisp: res.IsWisp,
OpenChildren: res.OpenChildren,
}, nil
}
func (r *issueSQLRepositoryImpl) Reopen(ctx context.Context, id string, params domain.ReopenRowParams, actor string, opts domain.IssueTableOpts) (domain.ReopenRowResult, error) {
res, err := issueops.ReopenIssueInTx(ctx, r.runner, id, params.Reason, actor)
if err != nil {
return domain.ReopenRowResult{}, fmt.Errorf("db: IssueSQLRepository.Reopen %s: %w", id, err)
}
return domain.ReopenRowResult{
Updated: res.Changed,
AlreadyOpen: res.AlreadyOpen,
IsWisp: res.IsWisp,
}, nil
}
func (r *issueSQLRepositoryImpl) GetNewlyUnblockedByClose(ctx context.Context, closedID string) ([]*types.Issue, error) {
out, err := issueops.GetNewlyUnblockedByCloseInTx(ctx, r.runner, closedID)
if err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.GetNewlyUnblockedByClose %s: %w", closedID, err)
}
return out, nil
}
func (r *issueSQLRepositoryImpl) ClaimReadyIssue(ctx context.Context, filter types.WorkFilter, actor string) (*types.Issue, error) {
out, err := issueops.ClaimReadyIssueInTx(ctx, r.runner, filter, actor)
if err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.ClaimReadyIssue: %w", err)
}
return out, nil
}
func (r *issueSQLRepositoryImpl) ClaimReadyWisp(ctx context.Context, filter types.WorkFilter, actor string) (*types.Issue, error) {
out, err := issueops.ClaimReadyIssueInTx(ctx, r.runner, filter, actor)
if err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.ClaimReadyWisp: %w", err)
}
return out, nil
}
func (r *issueSQLRepositoryImpl) GetBlockedIssues(ctx context.Context, filter types.WorkFilter) ([]*types.BlockedIssue, error) {
out, err := issueops.GetBlockedIssuesInTx(ctx, r.runner, filter)
if err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.GetBlockedIssues: %w", err)
}
return out, nil
}
func (r *issueSQLRepositoryImpl) GetStatistics(ctx context.Context) (*types.Statistics, error) {
stats := &types.Statistics{}
if err := issueops.ScanIssueCountsInTx(ctx, r.runner, stats); err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.GetStatistics: scan counts: %w", err)
}
var blocked int
if err := r.runner.QueryRowContext(ctx, `
SELECT COUNT(*) FROM issues
WHERE is_blocked = 1 AND status <> 'closed' AND status <> 'pinned'
`).Scan(&blocked); err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.GetStatistics: count blocked: %w", err)
}
stats.BlockedIssues = &blocked
ready := stats.OpenIssues - blocked
if ready < 0 {
ready = 0
}
stats.ReadyIssues = &ready
return stats, nil
}
func (r *issueSQLRepositoryImpl) CountIssues(ctx context.Context, query string, filter types.IssueFilter) (int64, error) {
n, err := issueops.CountIssuesInTx(ctx, r.runner, query, filter)
if err != nil {
return 0, fmt.Errorf("db: IssueSQLRepository.CountIssues: %w", err)
}
return int64(n), nil
}
func (r *issueSQLRepositoryImpl) CountIssuesByGroup(ctx context.Context, filter types.IssueFilter, groupBy string) (map[string]int, error) {
out, err := issueops.CountIssuesByGroupInTx(ctx, r.runner, filter, groupBy)
if err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.CountIssuesByGroup: %w", err)
}
return out, nil
}
func (r *issueSQLRepositoryImpl) History(ctx context.Context, id string) ([]*storage.HistoryEntry, error) {
out, err := issueops.HistoryInTx(ctx, r.runner, id)
if err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.History: %w", err)
}
return out, nil
}
func (r *issueSQLRepositoryImpl) IterEvents(ctx context.Context, id string, limit int) (storage.Iter[types.Event], error) {
events, err := issueops.GetEventsInTx(ctx, r.runner, id, limit)
if err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.IterEvents: %w", err)
}
return storage.NewSliceIter(events), nil
}
func (r *issueSQLRepositoryImpl) GetStaleIssues(ctx context.Context, filter types.StaleFilter) ([]*types.Issue, error) {
out, err := issueops.GetStaleIssuesInTx(ctx, r.runner, filter)
if err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.GetStaleIssues: %w", err)
}
return out, nil
}
func (r *issueSQLRepositoryImpl) GetEpicsEligibleForClosure(ctx context.Context) ([]*types.EpicStatus, error) {
out, err := issueops.GetEpicsEligibleForClosureInTx(ctx, r.runner)
if err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.GetEpicsEligibleForClosure: %w", err)
}
return out, nil
}
func (r *issueSQLRepositoryImpl) UnclaimIssue(ctx context.Context, id, actor string, force bool) error {
if err := issueops.UnclaimIssueInTx(ctx, r.runner, id, actor, force); err != nil {
return fmt.Errorf("db: IssueSQLRepository.UnclaimIssue: %w", err)
}
return nil
}
// UnclaimIssueIfAssignee runs the classic compare-and-swap release against this
// runner. Like UnclaimIssue it takes no IssueTableOpts: issueops routes the
// write to the issues or wisps tables from the row itself, so a wisp's claim is
// released against the wisp tables on both backends. The mismatch verdict
// (storage.ErrAssigneeMismatch, nothing written) is produced by the shared
// helper, not restated here.
func (r *issueSQLRepositoryImpl) UnclaimIssueIfAssignee(ctx context.Context, id, actor, expectedAssignee string) error {
if err := issueops.UnclaimIssueIfAssigneeInTx(ctx, r.runner, id, actor, expectedAssignee); err != nil {
return fmt.Errorf("db: IssueSQLRepository.UnclaimIssueIfAssignee: %w", err)
}
return nil
}
// HeartbeatIssue refreshes the lease on an issue actor holds in_progress,
// mirroring DoltStore.HeartbeatIssue: wisps are ephemeral and never leased,
// and the SQL work is the classic issueops.HeartbeatIssueInTx — same clock
// (time.Now().UTC()), same TTL resolution (issueops.LeaseTTL), and the same
// only-current-owner classification (storage.ErrAlreadyClaimed /
// ErrNotClaimable) — so classic `bd reclaim` staleness semantics see proxied
// heartbeats identically. Deliberately NO Dolt commit: the leases table is
// dolt_ignored (bd-lrgn1), and the cmd layer commits this transaction with
// uow.RunTxEphemeral (plain SQL COMMIT, nothing in dolt_log).
func (r *issueSQLRepositoryImpl) HeartbeatIssue(ctx context.Context, id, actor string) error {
if issueops.IsActiveWispInTx(ctx, r.runner, id) {
return fmt.Errorf("db: IssueSQLRepository.HeartbeatIssue: %w: %s is ephemeral", storage.ErrNotClaimable, id)
}
if err := issueops.HeartbeatIssueInTx(ctx, r.runner, id, actor); err != nil {
return fmt.Errorf("db: IssueSQLRepository.HeartbeatIssue: %w", err)
}
return nil
}
// WakeExpiredDefers runs the shared lazy defer-wake body against this
// repository's runner (the same DBTX-shaped seam ReclaimExpiredLeases uses)
// and reports how many rows woke per table. The issues count decides whether
// the transaction's owner mints a dolt commit; the wisps count decides
// whether it must still issue a plain SQL commit — wisp tables are
// dolt_ignored, so a wisp-only wake mints no version commit, but a caller
// that treats it as "nothing happened" rolls the wisp writes back.
func (r *issueSQLRepositoryImpl) WakeExpiredDefers(ctx context.Context) (issues, wisps int, err error) {
out, err := issueops.WakeExpiredDefersInTx(ctx, r.runner)
if err != nil {
return 0, 0, fmt.Errorf("db: IssueSQLRepository.WakeExpiredDefers: %w", err)
}
return len(out.Issues), len(out.Wisps), nil
}
func (r *issueSQLRepositoryImpl) ReclaimExpiredLeases(ctx context.Context, olderThan time.Duration, filter types.ReclaimFilter, actor string) ([]types.ReclaimedLease, error) {
cutoff := time.Now().UTC().Add(-olderThan)
out, err := issueops.ReclaimExpiredLeasesInTx(ctx, r.runner, cutoff, filter, actor)
if err != nil {
return nil, fmt.Errorf("db: IssueSQLRepository.ReclaimExpiredLeases: %w", err)
}
return out, nil
}
// Reclaim runs the shared sweep body directly on r.runner, matching GetMany's
// bare-passthrough shape: validation and error-wrapping both happen inside
// issueops.ExecuteReclaimInTx.
func (r *issueSQLRepositoryImpl) Reclaim(ctx context.Context, request publicops.ReclaimRequest) (publicops.ReclaimResult, error) {
return issueops.ExecuteReclaimInTx(ctx, r.runner, request)
}
const deleteBatchSize = 200