Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8760: fix(server): heal a drifted issue_counter only when a number collides (#10117)

Kasper Stöckel0620f2bf9ccf
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 7acfbe2d12..0c4fad7df3 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -3597,6 +3597,9 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
if writeIssueLimitReached(w, err) {
return
}
+ if writeIssueNumberCollision(w, err) {
+ return
+ }
if err != nil {
slog.Warn("create issue failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
writeError(w, http.StatusInternalServerError, "failed to create issue")
diff --git a/server/internal/handler/issue_counter_test.go b/server/internal/handler/issue_counter_test.go
new file mode 100644
index 0000000000..cef1a831b4
--- /dev/null
+++ b/server/internal/handler/issue_counter_test.go
@@ -0,0 +1,38 @@
+package handler
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestIssueNumberCollisionResponse(t *testing.T) {
+ err := fmt.Errorf("create issue: %w", &service.IssueNumberCollisionError{
+ Allocated: 1095, Constraint: service.IssueNumberConstraint,
+ })
+ var response struct {
+ Code string `json:"code"`
+ Error string `json:"error"`
+ Allocated int32 `json:"allocated"`
+ Constraint string `json:"constraint"`
+ Repair string `json:"repair"`
+ }
+ testutil.Call(t, func(w http.ResponseWriter, r *http.Request) {
+ if !writeIssueNumberCollision(w, err) {
+ t.Fatal("issue number collision was not handled")
+ }
+ }, testutil.JSONRequest(http.MethodPost, "/api/issues", nil)).Want(http.StatusConflict).JSON(&response)
+ if response.Code != "issue_number_collision" || response.Allocated != 1095 || response.Constraint != service.IssueNumberConstraint {
+ t.Fatalf("collision response = %+v", response)
+ }
+ if response.Error == "" || response.Repair == "" {
+ t.Fatalf("collision response lacks an explanation or recovery guidance: %+v", response)
+ }
+ if strings.Contains(response.Repair, "server/") || strings.Contains(response.Repair, "HealIssueCounter") {
+ t.Errorf("recovery guidance exposes server implementation details: %q", response.Repair)
+ }
+}
diff --git a/server/internal/handler/issue_limit.go b/server/internal/handler/issue_limit.go
index 75547488c1..57055f2fee 100644
--- a/server/internal/handler/issue_limit.go
+++ b/server/internal/handler/issue_limit.go
@@ -47,3 +47,20 @@ func writeIssueLimitReached(w http.ResponseWriter, err error) bool {
})
return true
}
+
+// writeIssueNumberCollision reports a number conflict that automatic repair
+// could not resolve and directs the caller to a workspace administrator.
+func writeIssueNumberCollision(w http.ResponseWriter, err error) bool {
+ var collisionErr *service.IssueNumberCollisionError
+ if !errors.As(err, &collisionErr) {
+ return false
+ }
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "code": "issue_number_collision",
+ "error": "workspace issue counter is behind its highest issue number, so card creation cannot allocate a free number",
+ "allocated": collisionErr.Allocated,
+ "constraint": collisionErr.Constraint,
+ "repair": "Ask a workspace administrator to repair the issue counter, then retry.",
+ })
+ return true
+}
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 5b7de029d3..4105df60a0 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -619,7 +619,16 @@ func (s *AutopilotService) dispatchAutopilotRun(
switch autopilot.ExecutionMode {
case "create_issue":
triggerTimezone := s.resolveAutopilotTriggerTimezone(ctx, triggerID)
- if err := s.dispatchCreateIssue(ctx, autopilot, run, triggerTimezone, actorUserID); err != nil {
+ err := s.dispatchCreateIssue(ctx, autopilot, run, triggerTimezone, actorUserID)
+ // Same rule as IssueService.Create: a collision on uq_issue_workspace_number
+ // means the workspace counter trails MAX(issue.number), and the failed
+ // dispatch already rolled its own increment back. Heal, then dispatch once
+ // more — otherwise this run fails and every later dispatch of this autopilot
+ // fails with it, which is how one drifted workspace wedges a board.
+ if err != nil && healIssueCounterAfterCollision(ctx, s.Queries, autopilot.WorkspaceID, err) {
+ err = s.dispatchCreateIssue(ctx, autopilot, run, triggerTimezone, actorUserID)
+ }
+ if err != nil {
if skipped, code := s.handleDispatchSkip(ctx, autopilot, run, err); skipped != nil {
return skipped, code, nil
}
@@ -763,7 +772,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
OriginID: ap.ID,
})
if err != nil {
- return fmt.Errorf("create issue: %w", err)
+ return classifyIssueNumberCollision(fmt.Errorf("create issue: %w", err), issueNumber)
}
// Fan out the default subscriber template inside the same tx as the
diff --git a/server/internal/service/issue.go b/server/internal/service/issue.go
index 11a2ab8a9c..392f54f5f9 100644
--- a/server/internal/service/issue.go
+++ b/server/internal/service/issue.go
@@ -211,7 +211,48 @@ type IssueCreateResult struct {
DuplicateIssue *db.Issue
}
-// Create runs the full issue-creation pipeline atomically end-to-end:
+// Create is the entry point every creator shares. It runs the pipeline below and
+// reacts to exactly one failure: a collision on uq_issue_workspace_number, which
+// proves workspace.issue_counter trails MAX(issue.number). On that collision it
+// heals the counter and runs the whole transaction again, once.
+//
+// A healthy create is byte-identical to before this existed — the allocation
+// query is untouched and nothing extra is read on the way through. The collision
+// is the signal: AllocateIssueNumber bumps the counter inside the same
+// transaction as the INSERT, so the unique violation rolls the increment back
+// too and every later create in that workspace retries the same taken number
+// forever. Moving the counter first is what makes the second attempt land on a
+// free number, and healIssueCounterAfterCollision logs the before and after so a
+// healed workspace leaves a trace instead of a silent numbering gap.
+//
+// The retry is the whole transaction, not a savepoint around the INSERT: a
+// savepoint has to be established before the statement that might fail, so every
+// successful create would pay for it too.
+func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts IssueCreateOpts) (IssueCreateResult, error) {
+ res, err := s.createOnce(ctx, p, opts)
+ if err == nil {
+ return res, nil
+ }
+ if !healIssueCounterAfterCollision(ctx, s.Queries, p.WorkspaceID, err) {
+ // Pass the result through: callers read fields alongside some of these
+ // errors, e.g. DuplicateIssue with ErrActiveDuplicate.
+ return res, err
+ }
+ res, err = s.createOnce(ctx, p, opts)
+ if err != nil {
+ var collision *IssueNumberCollisionError
+ if errors.As(err, &collision) {
+ slog.Error("issue number still collides after counter repair",
+ "workspace_id", util.UUIDToString(p.WorkspaceID),
+ "allocated", collision.Allocated,
+ "constraint", collision.Constraint)
+ }
+ return res, err
+ }
+ return res, nil
+}
+
+// createOnce runs the full issue-creation pipeline atomically end-to-end:
//
// 1. Begin transaction.
// 2. Resolve & validate parent / project belong to the same workspace.
@@ -234,7 +275,7 @@ type IssueCreateResult struct {
// MCP/API-key callers — shares the same workspace boundary semantics.
// Caller-owned validation is limited to transport-shaped checks: title
// required, RFC3339 date format, assignee pair sanity.
-func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts IssueCreateOpts) (IssueCreateResult, error) {
+func (s *IssueService) createOnce(ctx context.Context, p IssueCreateParams, opts IssueCreateOpts) (IssueCreateResult, error) {
issueCountPolicy := ResolveIssueCountPolicy(ctx, s.Entitlements, p.WorkspaceID)
tx, err := s.TxStarter.Begin(ctx)
if err != nil {
@@ -427,7 +468,10 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss
if errors.As(err, &pgErr) && pgErr.ConstraintName == "issue_properties_size_limit" {
return IssueCreateResult{}, ErrIssuePropertiesTooLarge
}
- return IssueCreateResult{}, fmt.Errorf("create issue: %w", err)
+ // Typed before it is returned so both halves can act on it: Create decides
+ // whether to heal and retry, and the transport reports a board-integrity
+ // problem instead of a generic create failure.
+ return IssueCreateResult{}, classifyIssueNumberCollision(fmt.Errorf("create issue: %w", err), issueNumber)
}
if p.PRAutoCompleteDisabled {
diff --git a/server/internal/service/issue_counter.go b/server/internal/service/issue_counter.go
new file mode 100644
index 0000000000..5ec797e61f
--- /dev/null
+++ b/server/internal/service/issue_counter.go
@@ -0,0 +1,93 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// IssueNumberConstraint is the unique index that makes a workspace counter
+// trailing MAX(issue.number) observable at all: the number the counter handed out
+// is already persisted somewhere in the workspace.
+const IssueNumberConstraint = "uq_issue_workspace_number"
+
+// pgSQLStateUniqueViolation is Postgres' SQLSTATE for a unique constraint
+// violation.
+const pgSQLStateUniqueViolation = "23505"
+
+// IssueNumberCollisionError reports the board-integrity fault behind what would
+// otherwise be an opaque duplicate-key error: the number this create allocated is
+// already held by another issue in the workspace, so workspace.issue_counter is
+// below the highest number its issue rows carry. Allocated is the number the
+// counter handed out.
+type IssueNumberCollisionError struct {
+ Allocated int32
+ Constraint string
+}
+
+func (e *IssueNumberCollisionError) Error() string {
+ return fmt.Sprintf("issue number collision: allocated %d, already held by %s; workspace issue_counter is behind MAX(issue.number)", e.Allocated, e.Constraint)
+}
+
+// classifyIssueNumberCollision types exactly one constraint violation and leaves
+// every other error alone, so no unrelated unique index gets folded into this
+// meaning and no caller has to read a SQLSTATE.
+func classifyIssueNumberCollision(err error, allocated int32) error {
+ var pgErr *pgconn.PgError
+ if !errors.As(err, &pgErr) || pgErr.Code != pgSQLStateUniqueViolation || pgErr.ConstraintName != IssueNumberConstraint {
+ return err
+ }
+ return &IssueNumberCollisionError{Allocated: allocated, Constraint: pgErr.ConstraintName}
+}
+
+// healIssueCounterAfterCollision repairs a workspace counter that trails
+// MAX(issue.number), and reports whether the caller may retry its transaction.
+//
+// It only acts on a proven collision, and it runs on the committed path rather
+// than inside the transaction that failed: that transaction is already aborted,
+// and its own increment was rolled back with the INSERT. Successful creates never
+// reach this function at all.
+//
+// The repair is logged with the value it replaced and the value it wrote. A
+// counter that is not actually behind is not repaired and not retried either —
+// that collision has a different cause, and retrying it would land on the same
+// number while hiding why.
+func healIssueCounterAfterCollision(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID, cause error) bool {
+ var collision *IssueNumberCollisionError
+ if !errors.As(cause, &collision) {
+ return false
+ }
+ workspaceIDString := util.UUIDToString(workspaceID)
+
+ row, err := q.HealIssueCounter(ctx, workspaceID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ slog.Error("issue number collision without counter drift",
+ "workspace_id", workspaceIDString,
+ "allocated", collision.Allocated,
+ "constraint", collision.Constraint)
+ return false
+ }
+ if err != nil {
+ slog.Error("issue counter repair failed",
+ "workspace_id", workspaceIDString,
+ "allocated", collision.Allocated,
+ "error", err)
+ return false
+ }
+
+ slog.Warn("issue counter repaired after issue number collision",
+ "workspace_id", workspaceIDString,
+ "previous_counter", row.PreviousCounter,
+ "max_number", row.MaxNumber,
+ "repaired_to", row.IssueCounter,
+ "collision_allocated", collision.Allocated)
+ return true
+}
diff --git a/server/internal/service/issue_counter_test.go b/server/internal/service/issue_counter_test.go
new file mode 100644
index 0000000000..d6ad9158ae
--- /dev/null
+++ b/server/internal/service/issue_counter_test.go
@@ -0,0 +1,229 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestIssueCreateHealsCounterDrift drives a real create against a workspace whose
+// counter trails a positive MAX(issue.number): five issues hold 1..5 and the
+// counter is left at 2, so the next allocation lands on 3 — a number this
+// workspace already holds.
+//
+// Pre-fix, what fails here is the duplicate-key error itself: the create returns
+// the 23505 on uq_issue_workspace_number and every later create in the workspace
+// would retry the same taken number, because the failed transaction rolls its own
+// counter increment back with the INSERT. With the heal, the counter is repaired
+// to 5 and the create lands on 6.
+func TestIssueCreateHealsCounterDrift(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ queries := db.New(pool)
+ workspaceIDString, userIDString, _, _ := seedAttributionFixture(t, pool)
+ workspaceID := util.MustParseUUID(workspaceIDString)
+ userID := util.MustParseUUID(userIDString)
+
+ for number := 1; number <= 5; number++ {
+ var seededID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_type, creator_id, number)
+ VALUES ($1, $2, 'member', $3, $4)
+ RETURNING id`, workspaceID, fmt.Sprintf("drift seed %d", number), userID, number).Scan(&seededID); err != nil {
+ t.Fatalf("seed numbered issue %d: %v", number, err)
+ }
+ t.Cleanup(func() {
+ pool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, seededID)
+ })
+ }
+ if _, err := pool.Exec(ctx, `UPDATE workspace SET issue_counter = 2 WHERE id = $1`, workspaceID); err != nil {
+ t.Fatalf("set issue_counter behind MAX(number): %v", err)
+ }
+
+ svc := NewIssueService(queries, pool, nil, nil, nil)
+ result, err := svc.Create(ctx, IssueCreateParams{
+ WorkspaceID: workspaceID,
+ Title: "created against a drifted counter",
+ Status: "todo",
+ Priority: "none",
+ CreatorType: "member",
+ CreatorID: userID,
+ }, IssueCreateOpts{})
+ if err != nil {
+ t.Fatalf("create against a drifted counter: %v", err)
+ }
+ created := result.Issue
+ t.Cleanup(func() {
+ if err := queries.DeleteIssue(ctx, db.DeleteIssueParams{ID: created.ID, WorkspaceID: workspaceID}); err != nil {
+ t.Errorf("delete created issue: %v", err)
+ }
+ })
+
+ if created.Number != 6 {
+ t.Fatalf("allocated number = %d, want 6: counter was 2 and 1..5 are already held", created.Number)
+ }
+
+ var counter int32
+ if err := pool.QueryRow(ctx, `SELECT issue_counter FROM workspace WHERE id = $1`, workspaceID).Scan(&counter); err != nil {
+ t.Fatalf("read issue_counter: %v", err)
+ }
+ if counter < 6 {
+ t.Fatalf("issue_counter = %d after the create, want at least 6", counter)
+ }
+}
+
+func TestAutopilotCreateIssueHealsCounterDrift(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ numbers []int
+ counter int
+ want int32
+ }{
+ {name: "numbered issues", numbers: []int{1, 2, 3, 4, 5}, counter: 2, want: 6},
+ {name: "reported workspace", numbers: []int{1095, 1096}, counter: 1094, want: 1097},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fx, ownerID := newPrincipalFixture(t)
+ agentID := fx.privateAgentOwnedBy(t, ownerID, "counter-drift")
+ autopilotID, triggerID := fx.autopilotWithTrigger(t, agentID, ownerID, ownerID)
+ fx.Exec(t, `UPDATE autopilot SET execution_mode = 'create_issue' WHERE id = $1`, autopilotID)
+ for _, number := range tc.numbers {
+ fx.Issue(t, fmt.Sprintf("drift seed %d", number), testutil.Cols{"number": number})
+ }
+ fx.Exec(t, `UPDATE workspace SET issue_counter = $2 WHERE id = $1`, fx.WorkspaceID, tc.counter)
+ fx.Cleanup(t, `DELETE FROM issue WHERE workspace_id = $1 AND origin_type = 'autopilot' AND origin_id = $2`, fx.WorkspaceID, autopilotID)
+ fx.Cleanup(t, `DELETE FROM autopilot_run WHERE autopilot_id = $1`, autopilotID)
+ fx.Cleanup(t, `DELETE FROM agent_task_queue WHERE agent_id = $1`, agentID)
+
+ run := fx.dispatch(t, autopilotID, triggerID)
+ if run.Status != "issue_created" || !run.IssueID.Valid || !run.TaskID.Valid {
+ t.Fatalf("dispatch = %+v; want an issue_created run linked to an issue and task", run)
+ }
+
+ var number, counter int32
+ fx.QueryRow(t, `SELECT number FROM issue WHERE id = $1 AND workspace_id = $2`, run.IssueID, fx.WorkspaceID).Scan(&number)
+ if number != tc.want {
+ t.Fatalf("created issue number = %d, want %d", number, tc.want)
+ }
+ fx.QueryRow(t, `SELECT issue_counter FROM workspace WHERE id = $1`, fx.WorkspaceID).Scan(&counter)
+ if counter != tc.want {
+ t.Errorf("issue_counter = %d, want %d", counter, tc.want)
+ }
+ if n := fx.Count(t, `SELECT count(*) FROM issue WHERE workspace_id = $1 AND origin_type = 'autopilot' AND origin_id = $2`, fx.WorkspaceID, autopilotID); n != 1 {
+ t.Errorf("dispatch created %d issues, want 1", n)
+ }
+ if n := fx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2`, run.IssueID, agentID); n != 1 {
+ t.Errorf("dispatch enqueued %d tasks, want 1", n)
+ }
+ })
+ }
+}
+
+// TestIssueCreateOnHealthyWorkspaceAllocatesCounterPlusOne pins the healthy path:
+// a fresh workspace (counter 0, its only issue at the number default 0) advances
+// by exactly one and nothing else is consulted or rewritten.
+func TestIssueCreateOnHealthyWorkspaceAllocatesCounterPlusOne(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ queries := db.New(pool)
+ workspaceIDString, userIDString, _, _ := seedAttributionFixture(t, pool)
+ workspaceID := util.MustParseUUID(workspaceIDString)
+ userID := util.MustParseUUID(userIDString)
+
+ svc := NewIssueService(queries, pool, nil, nil, nil)
+ result, err := svc.Create(ctx, IssueCreateParams{
+ WorkspaceID: workspaceID,
+ Title: "created against a healthy counter",
+ Status: "todo",
+ Priority: "none",
+ CreatorType: "member",
+ CreatorID: userID,
+ }, IssueCreateOpts{})
+ if err != nil {
+ t.Fatalf("create on a healthy workspace: %v", err)
+ }
+ created := result.Issue
+ t.Cleanup(func() {
+ if err := queries.DeleteIssue(ctx, db.DeleteIssueParams{ID: created.ID, WorkspaceID: workspaceID}); err != nil {
+ t.Errorf("delete created issue: %v", err)
+ }
+ })
+
+ if created.Number != 1 {
+ t.Fatalf("allocated number = %d, want 1 (issue_counter 0 + 1)", created.Number)
+ }
+ var counter int32
+ if err := pool.QueryRow(ctx, `SELECT issue_counter FROM workspace WHERE id = $1`, workspaceID).Scan(&counter); err != nil {
+ t.Fatalf("read issue_counter: %v", err)
+ }
+ if counter != 1 {
+ t.Fatalf("issue_counter = %d, want 1", counter)
+ }
+}
+
+// TestConcurrentIssueCreatesNeverShareANumber is the other half of the same
+// guarantee: allocation is serialized on the workspace row, so two creates in
+// flight at once cannot both be handed the number they are about to insert.
+func TestConcurrentIssueCreatesNeverShareANumber(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ queries := db.New(pool)
+ workspaceIDString, userIDString, _, _ := seedAttributionFixture(t, pool)
+ workspaceID := util.MustParseUUID(workspaceIDString)
+ userID := util.MustParseUUID(userIDString)
+
+ const creates = 8
+ svc := NewIssueService(queries, pool, nil, nil, nil)
+
+ start := make(chan struct{})
+ type createResult struct {
+ issue db.Issue
+ err error
+ }
+ results := make(chan createResult, creates)
+ var wg sync.WaitGroup
+ for i := range creates {
+ wg.Add(1)
+ go func(index int) {
+ defer wg.Done()
+ <-start
+ result, err := svc.Create(ctx, IssueCreateParams{
+ WorkspaceID: workspaceID,
+ Title: fmt.Sprintf("concurrent create %d", index),
+ Status: "todo",
+ Priority: "none",
+ CreatorType: "member",
+ CreatorID: userID,
+ }, IssueCreateOpts{})
+ results <- createResult{issue: result.Issue, err: err}
+ }(i)
+ }
+ close(start)
+ wg.Wait()
+ close(results)
+
+ seen := make(map[int32]bool, creates)
+ for result := range results {
+ if result.err != nil {
+ t.Fatalf("concurrent create: %v", result.err)
+ }
+ issue := result.issue
+ t.Cleanup(func() {
+ if err := queries.DeleteIssue(ctx, db.DeleteIssueParams{ID: issue.ID, WorkspaceID: workspaceID}); err != nil {
+ t.Errorf("delete created issue: %v", err)
+ }
+ })
+ if seen[issue.Number] {
+ t.Fatalf("two concurrent creates were both handed number %d", issue.Number)
+ }
+ seen[issue.Number] = true
+ }
+ if len(seen) != creates {
+ t.Fatalf("distinct numbers = %d, want %d", len(seen), creates)
+ }
+}
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index 703ea3f302..f2e72e4a46 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -295,6 +295,46 @@ func (q *Queries) GetWorkspaceBySlug(ctx context.Context, slug string) (Workspac
return i, err
}
+const healIssueCounter = `-- name: HealIssueCounter :one
+WITH target AS (
+ SELECT w.id, w.issue_counter,
+ (SELECT COALESCE(MAX(i.number), 0)::int FROM issue i WHERE i.workspace_id = w.id) AS max_number
+ FROM workspace w
+ WHERE w.id = $1
+)
+UPDATE workspace w SET issue_counter = t.max_number
+FROM target t
+WHERE w.id = t.id AND w.issue_counter < t.max_number
+RETURNING w.issue_counter AS issue_counter,
+ t.issue_counter AS previous_counter,
+ t.max_number AS max_number
+`
+
+type HealIssueCounterRow struct {
+ IssueCounter int32 `json:"issue_counter"`
+ PreviousCounter int32 `json:"previous_counter"`
+ MaxNumber int32 `json:"max_number"`
+}
+
+// Operator-shaped repair for a workspace whose issue_counter sits below
+// MAX(issue.number): something persisted a numbered issue row without this
+// counter ever being advanced for it. Deliberately a separate statement from
+// IncrementIssueCounter so a healthy create pays nothing for it, and scoped to
+// one workspace.
+//
+// The WHERE guard is what makes a retry meaningful: no row is updated, and sqlc
+// returns no row, unless the counter really is behind — so a collision caused by
+// anything else is never retried against the same taken number. It returns the
+// value it wrote, the value it replaced and the highest number the workspace
+// holds, so a repair can be logged with its before and after instead of leaving
+// no trace for whoever debugs the next occurrence.
+func (q *Queries) HealIssueCounter(ctx context.Context, id pgtype.UUID) (HealIssueCounterRow, error) {
+ row := q.db.QueryRow(ctx, healIssueCounter, id)
+ var i HealIssueCounterRow
+ err := row.Scan(&i.IssueCounter, &i.PreviousCounter, &i.MaxNumber)
+ return i, err
+}
+
const incrementIssueCounter = `-- name: IncrementIssueCounter :one
UPDATE workspace SET issue_counter = issue_counter + 1
WHERE id = $1
diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sql
index 281b973564..c3f7d9e4f7 100644
--- a/server/pkg/db/queries/workspace.sql
+++ b/server/pkg/db/queries/workspace.sql
@@ -62,6 +62,32 @@ UPDATE workspace SET issue_counter = issue_counter + 1
WHERE id = $1
RETURNING issue_counter;
+-- name: HealIssueCounter :one
+-- Operator-shaped repair for a workspace whose issue_counter sits below
+-- MAX(issue.number): something persisted a numbered issue row without this
+-- counter ever being advanced for it. Deliberately a separate statement from
+-- IncrementIssueCounter so a healthy create pays nothing for it, and scoped to
+-- one workspace.
+--
+-- The WHERE guard is what makes a retry meaningful: no row is updated, and sqlc
+-- returns no row, unless the counter really is behind — so a collision caused by
+-- anything else is never retried against the same taken number. It returns the
+-- value it wrote, the value it replaced and the highest number the workspace
+-- holds, so a repair can be logged with its before and after instead of leaving
+-- no trace for whoever debugs the next occurrence.
+WITH target AS (
+ SELECT w.id, w.issue_counter,
+ (SELECT COALESCE(MAX(i.number), 0)::int FROM issue i WHERE i.workspace_id = w.id) AS max_number
+ FROM workspace w
+ WHERE w.id = $1
+)
+UPDATE workspace w SET issue_counter = t.max_number
+FROM target t
+WHERE w.id = t.id AND w.issue_counter < t.max_number
+RETURNING w.issue_counter AS issue_counter,
+ t.issue_counter AS previous_counter,
+ t.max_number AS max_number;
+
-- name: LockWorkspaceForDelete :one
-- Taken first by DeleteWorkspace, before it enumerates the workspace's chat
-- sessions. LockChatSessionsByWorkspace only covers sessions that exist when it