Skip to content

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

Go

MUL-6407: mint UUIDv7 primary keys for append-heavy tables (#7230)

Multica Eveb4bfe083becc
diff --git a/server/cmd/server/activity_listeners.go b/server/cmd/server/activity_listeners.go
index 9af0141c9c..3735a2158c 100644
--- a/server/cmd/server/activity_listeners.go
+++ b/server/cmd/server/activity_listeners.go
@@ -9,6 +9,7 @@ import (
"github.com/multica-ai/multica/server/internal/handler"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -31,6 +32,7 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
}
activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: parseUUID(issue.WorkspaceID),
IssueID: parseUUID(issue.ID),
ActorType: util.StrToText(e.ActorType),
@@ -70,6 +72,7 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
"to": issue.Status,
})
activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: parseUUID(issue.WorkspaceID),
IssueID: parseUUID(issue.ID),
ActorType: util.StrToText(e.ActorType),
@@ -92,6 +95,7 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
"to": issue.Priority,
})
activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: parseUUID(issue.WorkspaceID),
IssueID: parseUUID(issue.ID),
ActorType: util.StrToText(e.ActorType),
@@ -127,6 +131,7 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
details, _ := json.Marshal(detailsMap)
activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: parseUUID(issue.WorkspaceID),
IssueID: parseUUID(issue.ID),
ActorType: util.StrToText(e.ActorType),
@@ -156,6 +161,7 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
"to": newStartDate,
})
activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: parseUUID(issue.WorkspaceID),
IssueID: parseUUID(issue.ID),
ActorType: util.StrToText(e.ActorType),
@@ -185,6 +191,7 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
"to": newDueDate,
})
activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: parseUUID(issue.WorkspaceID),
IssueID: parseUUID(issue.ID),
ActorType: util.StrToText(e.ActorType),
@@ -207,6 +214,7 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
"to": issue.Title,
})
activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: parseUUID(issue.WorkspaceID),
IssueID: parseUUID(issue.ID),
ActorType: util.StrToText(e.ActorType),
@@ -224,6 +232,7 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
if descriptionChanged {
activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: parseUUID(issue.WorkspaceID),
IssueID: parseUUID(issue.ID),
ActorType: util.StrToText(e.ActorType),
@@ -272,6 +281,7 @@ func handleTaskActivity(ctx context.Context, bus *events.Bus, queries *db.Querie
}
activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: issue.WorkspaceID,
IssueID: parseUUID(issueID),
ActorType: util.StrToText("agent"),
diff --git a/server/cmd/server/autopilot_failure_monitor.go b/server/cmd/server/autopilot_failure_monitor.go
index 14d5f65f17..99c18c297c 100644
--- a/server/cmd/server/autopilot_failure_monitor.go
+++ b/server/cmd/server/autopilot_failure_monitor.go
@@ -17,6 +17,7 @@ import (
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -245,6 +246,7 @@ func emitAutopilotPausedNotifications(
emitted[key] = true
item, err := queries.CreateInboxItem(ctx, db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
WorkspaceID: autopilot.WorkspaceID,
RecipientType: r.Type,
RecipientID: r.ID,
diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.go
index 53f2b3cd25..ccec27a27c 100644
--- a/server/cmd/server/notification_listeners.go
+++ b/server/cmd/server/notification_listeners.go
@@ -11,6 +11,7 @@ import (
"github.com/multica-ai/multica/server/internal/issuestatus"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -413,6 +414,7 @@ func notifyIssueSubscribers(
}
item, err := queries.CreateInboxItem(ctx, db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
WorkspaceID: parseUUID(workspaceID),
RecipientType: "member",
RecipientID: sub.UserID,
@@ -478,6 +480,7 @@ func notifyDirect(
}
item, err := queries.CreateInboxItem(ctx, db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
WorkspaceID: parseUUID(workspaceID),
RecipientType: recipientType,
RecipientID: parseUUID(recipientID),
@@ -592,6 +595,7 @@ func notifyMentionedMembers(
continue
}
item, err := queries.CreateInboxItem(context.Background(), db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
WorkspaceID: parseUUID(e.WorkspaceID),
RecipientType: "member",
RecipientID: parseUUID(id),
diff --git a/server/internal/handler/agent_builder.go b/server/internal/handler/agent_builder.go
index 0860a7cd2c..40d5f6c5d6 100644
--- a/server/internal/handler/agent_builder.go
+++ b/server/internal/handler/agent_builder.go
@@ -13,6 +13,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
)
const agentBuilderInstructions = `You are Multica Agent Builder. Help the user design one practical AI agent through a short conversation.
@@ -121,6 +122,7 @@ func (h *Handler) CreateAgentBuilderSession(w http.ResponseWriter, r *http.Reque
}
session, err := qtx.CreateChatSession(r.Context(), db.CreateChatSessionParams{
+ ID: dbid.NewV7(),
WorkspaceID: workspaceUUID,
AgentID: builder.ID,
CreatorID: ownerUUID,
diff --git a/server/internal/handler/agent_env.go b/server/internal/handler/agent_env.go
index 122652b5ab..440ce73172 100644
--- a/server/internal/handler/agent_env.go
+++ b/server/internal/handler/agent_env.go
@@ -11,6 +11,7 @@ import (
"github.com/multica-ai/multica/server/internal/logger"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -153,6 +154,7 @@ func (h *Handler) GetAgentEnv(w http.ResponseWriter, r *http.Request) {
"key_count": len(revealedKeys),
})
if _, err := h.Queries.CreateActivity(r.Context(), db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: agent.WorkspaceID,
IssueID: pgtype.UUID{}, // env access is not tied to an issue
ActorType: pgtype.Text{String: "member", Valid: true},
@@ -240,6 +242,7 @@ func (h *Handler) UpdateAgentEnv(w http.ResponseWriter, r *http.Request) {
}
details, _ := json.Marshal(auditDetails)
if _, err := qtx.CreateActivity(r.Context(), db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: agent.WorkspaceID,
IssueID: pgtype.UUID{},
ActorType: pgtype.Text{String: "member", Valid: true},
diff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.go
index 1dd32c803b..25b7b3b045 100644
--- a/server/internal/handler/autopilot_webhook.go
+++ b/server/internal/handler/autopilot_webhook.go
@@ -26,6 +26,7 @@ import (
"github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
)
// maxWebhookBodyBytes is the request body size cap for webhook ingress.
@@ -799,6 +800,7 @@ type persistDeliveryInput struct {
// Any other error bubbles up so the handler can 500 cleanly.
func (h *Handler) persistInboundDelivery(r *http.Request, in persistDeliveryInput) (db.WebhookDelivery, bool, error) {
params := db.CreateWebhookDeliveryParams{
+ ID: dbid.NewV7(),
WorkspaceID: in.WorkspaceID,
AutopilotID: in.AutopilotID,
TriggerID: in.TriggerID,
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index da678ce0fa..fa81a1f1aa 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -19,6 +19,7 @@ import (
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -126,6 +127,7 @@ func (h *Handler) CreateChatSession(w http.ResponseWriter, r *http.Request) {
}
session, err := qtx.CreateChatSession(r.Context(), db.CreateChatSessionParams{
+ ID: dbid.NewV7(),
WorkspaceID: workspaceUUID,
AgentID: agentID,
CreatorID: parseUUID(userID),
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index f20093a473..e185fe108b 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -20,6 +20,7 @@ import (
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -1869,6 +1870,7 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
}
created, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
+ ID: dbid.NewV7(),
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
AuthorType: authorType,
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 91b41453b4..f3f68cdea5 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -32,6 +32,7 @@ import (
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
"github.com/multica-ai/multica/server/pkg/redact"
"github.com/multica-ai/multica/server/pkg/skillbundle"
@@ -1747,6 +1748,7 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {
// the exact claim is requeued and omitted from this batch.
commentBackedTask := task.TriggerCommentID.Valid || len(task.CoalescedCommentIds) > 0
receipt, ferr := h.TaskService.FinalizeTaskClaim(r.Context(), task, db.CreateTaskTokenParams{
+ ID: dbid.NewV7(),
TokenHash: auth.HashToken(tokenStr),
TaskID: task.ID,
AgentID: task.AgentID,
@@ -3234,6 +3236,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
return
}
receipt, ferr := h.TaskService.FinalizeTaskClaim(r.Context(), *task, db.CreateTaskTokenParams{
+ ID: dbid.NewV7(),
TokenHash: auth.HashToken(tokenStr),
TaskID: task.ID,
AgentID: task.AgentID,
diff --git a/server/internal/handler/issue_child_done.go b/server/internal/handler/issue_child_done.go
index be16f75599..145f97741b 100644
--- a/server/internal/handler/issue_child_done.go
+++ b/server/internal/handler/issue_child_done.go
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/issuestatus"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -313,6 +314,7 @@ func (h *Handler) postChildDoneComment(ctx context.Context, parent, completed db
// byte value and the column is NOT NULL; frontend code should branch on
// author_type === 'system' rather than on the UUID value.
created, err := h.Queries.CreateComment(ctx, db.CreateCommentParams{
+ ID: dbid.NewV7(),
IssueID: parent.ID,
WorkspaceID: parent.WorkspaceID,
AuthorType: "system",
diff --git a/server/internal/handler/mika_agent.go b/server/internal/handler/mika_agent.go
index 419977519a..ddd483e2c1 100644
--- a/server/internal/handler/mika_agent.go
+++ b/server/internal/handler/mika_agent.go
@@ -11,6 +11,7 @@ import (
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
"log/slog"
"net/http"
@@ -296,6 +297,7 @@ func (h *Handler) getOrCreateMikaSession(ctx context.Context, agent db.Agent, wo
}
created, err := qtx.CreateChatSession(ctx, db.CreateChatSessionParams{
+ ID: dbid.NewV7(),
WorkspaceID: wsUUID,
AgentID: agent.ID,
CreatorID: creatorUUID,
diff --git a/server/internal/handler/onboarding_shim.go b/server/internal/handler/onboarding_shim.go
index f461c4f1fe..3fc66b4883 100644
--- a/server/internal/handler/onboarding_shim.go
+++ b/server/internal/handler/onboarding_shim.go
@@ -35,6 +35,7 @@ import (
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -255,6 +256,7 @@ func (h *Handler) BootstrapOnboardingRuntime(w http.ResponseWriter, r *http.Requ
description = req.StarterPrompt
}
issue, err = qtx.CreateIssue(r.Context(), db.CreateIssueParams{
+ ID: dbid.NewV7(),
WorkspaceID: wsUUID,
Title: onboardingIssueTitle,
Description: strOrNullText(description),
@@ -414,6 +416,7 @@ func (h *Handler) BootstrapOnboardingNoRuntime(w http.ResponseWriter, r *http.Re
return
}
issue, err = qtx.CreateIssue(r.Context(), db.CreateIssueParams{
+ ID: dbid.NewV7(),
WorkspaceID: wsUUID,
Title: noRuntimeIssueTitle,
Description: strOrNullText(noRuntimeIssueDescription(userBefore.Language)),
diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.go
index 11d8324b74..120cd8c126 100644
--- a/server/internal/handler/plugin_action.go
+++ b/server/internal/handler/plugin_action.go
@@ -12,6 +12,7 @@ import (
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/plugincontract"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -461,6 +462,7 @@ func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {
}
createdComment, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
+ ID: dbid.NewV7(),
IssueID: issue.ID,
WorkspaceID: caller.WorkspaceID,
AuthorType: authorType,
diff --git a/server/internal/handler/quick_action.go b/server/internal/handler/quick_action.go
index 8246e42e92..7f6580f469 100644
--- a/server/internal/handler/quick_action.go
+++ b/server/internal/handler/quick_action.go
@@ -14,6 +14,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/logger"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -886,6 +887,7 @@ func (h *Handler) RunQuickAction(w http.ResponseWriter, r *http.Request) {
body := sanitizeNullBytes(buildQuickActionBody(qa, target))
created, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
+ ID: dbid.NewV7(),
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
AuthorType: actorType,
diff --git a/server/internal/handler/runtime_unusable_notice.go b/server/internal/handler/runtime_unusable_notice.go
index f8ec291d5f..0dc714116e 100644
--- a/server/internal/handler/runtime_unusable_notice.go
+++ b/server/internal/handler/runtime_unusable_notice.go
@@ -7,6 +7,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -27,6 +28,7 @@ func (h *Handler) noteRuntimeUnusable(ctx context.Context, issue db.Issue, agent
// author_type='system', author_id=zero UUID — same shape as the sub-issue
// completion notice; clients branch on author_type, not the UUID value.
created, err := h.Queries.CreateComment(ctx, db.CreateCommentParams{
+ ID: dbid.NewV7(),
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
AuthorType: "system",
diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.go
index 07a29ede19..0171adb534 100644
--- a/server/internal/handler/squad.go
+++ b/server/internal/handler/squad.go
@@ -14,6 +14,7 @@ import (
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -1008,6 +1009,7 @@ func (h *Handler) RecordSquadLeaderEvaluation(w http.ResponseWriter, r *http.Req
})
activity, err := h.Queries.CreateActivity(r.Context(), db.CreateActivityParams{
+ ID: dbid.NewV7(),
WorkspaceID: issue.WorkspaceID,
IssueID: issue.ID,
ActorType: pgtype.Text{String: "agent", Valid: true},
diff --git a/server/internal/handler/uuidv7_ids_test.go b/server/internal/handler/uuidv7_ids_test.go
new file mode 100644
index 0000000000..6d25d367e4
--- /dev/null
+++ b/server/internal/handler/uuidv7_ids_test.go
@@ -0,0 +1,227 @@
+package handler
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+// TestHotTableInsertsPersistUUIDv7 runs the converted INSERTs against Postgres
+// and asserts the id the application minted is the id that landed in the row.
+// The static checks in pkg/dbid prove the queries and call sites are wired; this
+// proves the round trip — parameter binding, column order, and the COALESCE
+// wrapper all agree.
+func TestHotTableInsertsPersistUUIDv7(t *testing.T) {
+ ctx := context.Background()
+ q := testHandler.Queries
+
+ runtimeID := dbfx.Runtime(t, "uuidv7-runtime")
+ agentID := dbfx.Agent(t, "uuidv7-agent", runtimeID)
+ issueID := dbfx.Issue(t, "uuidv7 issue")
+
+ t.Run("issue", func(t *testing.T) {
+ var maxNumber int32
+ dbfx.QueryRow(t, `SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1`,
+ testWorkspaceID).Scan(&maxNumber)
+
+ created, err := q.CreateIssue(ctx, db.CreateIssueParams{
+ ID: dbid.NewV7(),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ Title: "uuidv7 create issue",
+ Status: "todo",
+ Priority: "none",
+ CreatorType: "member",
+ CreatorID: parseUUID(testUserID),
+ Number: maxNumber,
+ })
+ if err != nil {
+ t.Fatalf("CreateIssue: %v", err)
+ }
+ cleanupRow(t, "issue", created.ID)
+ assertV7(t, "issue.id", created.ID)
+ })
+
+ t.Run("comment", func(t *testing.T) {
+ created, err := q.CreateComment(ctx, db.CreateCommentParams{
+ ID: dbid.NewV7(),
+ IssueID: parseUUID(issueID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ AuthorType: "member",
+ AuthorID: parseUUID(testUserID),
+ Content: "uuidv7 comment",
+ Type: "comment",
+ })
+ if err != nil {
+ t.Fatalf("CreateComment: %v", err)
+ }
+ cleanupRow(t, "comment", created.ID)
+ assertV7(t, "comment.id", created.ID)
+ })
+
+ t.Run("activity_log", func(t *testing.T) {
+ created, err := q.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ IssueID: parseUUID(issueID),
+ ActorType: pgtype.Text{String: "member", Valid: true},
+ ActorID: parseUUID(testUserID),
+ Action: "uuidv7_test",
+ Details: []byte(`{}`),
+ })
+ if err != nil {
+ t.Fatalf("CreateActivity: %v", err)
+ }
+ cleanupRow(t, "activity_log", created.ID)
+ assertV7(t, "activity_log.id", created.ID)
+ })
+
+ t.Run("inbox_item", func(t *testing.T) {
+ created, err := q.CreateInboxItem(ctx, db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ RecipientType: "member",
+ RecipientID: parseUUID(testUserID),
+ Type: "issue_assigned",
+ Severity: "info",
+ IssueID: parseUUID(issueID),
+ Title: "uuidv7 inbox item",
+ Details: []byte(`{}`),
+ })
+ if err != nil {
+ t.Fatalf("CreateInboxItem: %v", err)
+ }
+ cleanupRow(t, "inbox_item", created.ID)
+ assertV7(t, "inbox_item.id", created.ID)
+ })
+
+ t.Run("chat_session_and_chat_message", func(t *testing.T) {
+ session, err := q.CreateChatSession(ctx, db.CreateChatSessionParams{
+ ID: dbid.NewV7(),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ AgentID: parseUUID(agentID),
+ CreatorID: parseUUID(testUserID),
+ Title: "uuidv7 chat",
+ })
+ if err != nil {
+ t.Fatalf("CreateChatSession: %v", err)
+ }
+ cleanupRow(t, "chat_session", session.ID)
+ assertV7(t, "chat_session.id", session.ID)
+
+ msg, err := q.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ ID: dbid.NewV7(),
+ ChatSessionID: session.ID,
+ Role: "user",
+ Content: "hello",
+ })
+ if err != nil {
+ t.Fatalf("CreateChatMessage: %v", err)
+ }
+ cleanupRow(t, "chat_message", msg.ID)
+ assertV7(t, "chat_message.id", msg.ID)
+ })
+
+ t.Run("agent_task_queue_and_task_token", func(t *testing.T) {
+ task, err := q.CreateAgentTask(ctx, db.CreateAgentTaskParams{
+ ID: dbid.NewV7(),
+ AgentID: parseUUID(agentID),
+ RuntimeID: parseUUID(runtimeID),
+ IssueID: parseUUID(issueID),
+ Priority: 1,
+ })
+ if err != nil {
+ t.Fatalf("CreateAgentTask: %v", err)
+ }
+ cleanupRow(t, "agent_task_queue", task.ID)
+ assertV7(t, "agent_task_queue.id", task.ID)
+
+ token, err := q.CreateTaskToken(ctx, db.CreateTaskTokenParams{
+ ID: dbid.NewV7(),
+ TokenHash: "uuidv7-test-token-hash",
+ TaskID: task.ID,
+ AgentID: parseUUID(agentID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ UserID: parseUUID(testUserID),
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("CreateTaskToken: %v", err)
+ }
+ cleanupRow(t, "task_token", token.ID)
+ assertV7(t, "task_token.id", token.ID)
+ })
+
+ t.Run("channel_inbound_audit", func(t *testing.T) {
+ const eventID = "uuidv7-audit-event"
+ dbfx.Cleanup(t, `DELETE FROM channel_inbound_audit WHERE channel_event_id = $1`, eventID)
+
+ if err := q.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
+ ID: dbid.NewV7(),
+ ChannelType: "slack",
+ EventType: "message",
+ DropReason: "uuidv7_test",
+ ChannelEventID: pgtype.Text{String: eventID, Valid: true},
+ }); err != nil {
+ t.Fatalf("RecordChannelInboundDrop: %v", err)
+ }
+
+ var got pgtype.UUID
+ dbfx.QueryRow(t, `SELECT id FROM channel_inbound_audit WHERE channel_event_id = $1`, eventID).Scan(&got)
+ assertV7(t, "channel_inbound_audit.id", got)
+ })
+}
+
+// TestUnsetIDFallsBackToTheDatabaseDefault covers the safety net: a caller that
+// does not mint an id must still get a row, with a database-generated v4, rather
+// than a NOT NULL violation. This is what makes the COALESCE wrapper — and
+// dbid.NewV7's silent degradation on an entropy failure — safe.
+func TestUnsetIDFallsBackToTheDatabaseDefault(t *testing.T) {
+ ctx := context.Background()
+
+ issueID := dbfx.Issue(t, "uuidv7 fallback issue")
+ created, err := testHandler.Queries.CreateActivity(ctx, db.CreateActivityParams{
+ WorkspaceID: parseUUID(testWorkspaceID),
+ IssueID: parseUUID(issueID),
+ ActorType: pgtype.Text{String: "member", Valid: true},
+ ActorID: parseUUID(testUserID),
+ Action: "uuidv7_fallback_test",
+ Details: []byte(`{}`),
+ })
+ if err != nil {
+ t.Fatalf("CreateActivity without an id: %v", err)
+ }
+ cleanupRow(t, "activity_log", created.ID)
+
+ if !created.ID.Valid {
+ t.Fatal("row was inserted without an id")
+ }
+ if v := uuid.UUID(created.ID.Bytes).Version(); v != 4 {
+ t.Fatalf("database default produced a v%d id, want v4", v)
+ }
+}
+
+func assertV7(t *testing.T, label string, id pgtype.UUID) {
+ t.Helper()
+
+ if !id.Valid {
+ t.Fatalf("%s: no id returned", label)
+ }
+ parsed := uuid.UUID(id.Bytes)
+ if v := parsed.Version(); v != 7 {
+ t.Errorf("%s: stored id is v%d (%s), want v7", label, v, parsed)
+ }
+}
+
+// cleanupRow deletes a row the query under test created. Fixtures registered
+// through testutil clean themselves up; rows created by the production query do
+// not, so they are registered by hand.
+func cleanupRow(t *testing.T, table string, id pgtype.UUID) {
+ t.Helper()
+
+ dbfx.Cleanup(t, `DELETE FROM `+table+` WHERE id = $1`, id)
+}
diff --git a/server/internal/handler/webhook_delivery.go b/server/internal/handler/webhook_delivery.go
index 183b954fee..1b11571d34 100644
--- a/server/internal/handler/webhook_delivery.go
+++ b/server/internal/handler/webhook_delivery.go
@@ -14,6 +14,7 @@ import (
"github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
)
// ── Response types ──────────────────────────────────────────────────────────
@@ -308,6 +309,7 @@ func (h *Handler) ReplayAutopilotDelivery(w http.ResponseWriter, r *http.Request
contentType = original.ContentType.String
}
replay, err := h.Queries.CreateWebhookDelivery(r.Context(), db.CreateWebhookDeliveryParams{
+ ID: dbid.NewV7(),
WorkspaceID: autopilot.WorkspaceID,
AutopilotID: autopilot.ID,
TriggerID: original.TriggerID,
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index 489404de7e..f6272effce 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -16,6 +16,7 @@ import (
"github.com/multica-ai/multica/server/internal/channelmedia"
"github.com/multica-ai/multica/server/internal/integrations/channel"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
)
// This file is the SHARED, channel-agnostic chat-session service every IM
@@ -239,6 +240,7 @@ func (s *ChatSession) createSessionAndBinding(ctx context.Context, in EnsureSess
}
session, err := qtx.CreateChatSession(ctx, db.CreateChatSessionParams{
+ ID: dbid.NewV7(),
WorkspaceID: in.WorkspaceID,
AgentID: in.AgentID,
CreatorID: in.Sender,
@@ -353,6 +355,7 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
// it must be stamped in the same transaction as the message so no later
// binding deletion (archive, installation rebind) can strip it.
msg, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ ID: dbid.NewV7(),
ChatSessionID: in.SessionID,
Role: "user",
Content: in.Body,
diff --git a/server/internal/integrations/dingtalk/resolvers.go b/server/internal/integrations/dingtalk/resolvers.go
index d55c6c7209..46c97727ae 100644
--- a/server/internal/integrations/dingtalk/resolvers.go
+++ b/server/internal/integrations/dingtalk/resolvers.go
@@ -13,6 +13,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
)
// originDingTalkChat is the issue.origin_type label for issues created through
@@ -418,6 +419,7 @@ type auditor struct{ q *db.Queries }
func (r *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason engine.DropReason) error {
return r.q.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
+ ID: dbid.NewV7(),
ChannelType: string(TypeDingTalk),
EventType: "message",
DropReason: string(reason),
diff --git a/server/internal/integrations/lark/channel_store.go b/server/internal/integrations/lark/channel_store.go
index 351653bdf5..9274d794ef 100644
--- a/server/internal/integrations/lark/channel_store.go
+++ b/server/internal/integrations/lark/channel_store.go
@@ -21,6 +21,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
)
// channelTypeFeishu is the channel_type discriminator for every row this
@@ -334,6 +335,7 @@ func (s *ChannelStore) ReleaseLarkInboundDedup(ctx context.Context, arg ReleaseI
func (s *ChannelStore) RecordLarkInboundDrop(ctx context.Context, arg RecordInboundDropParams) error {
return s.Queries.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
+ ID: dbid.NewV7(),
ChannelType: channelTypeFeishu,
EventType: arg.EventType,
DropReason: arg.DropReason,
diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.go
index 5f891ccae0..6d9d362322 100644
--- a/server/internal/integrations/slack/resolvers.go
+++ b/server/internal/integrations/slack/resolvers.go
@@ -12,6 +12,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
)
// Slack resolvers connect the channel-agnostic inbound pipeline to Slack
@@ -375,6 +376,7 @@ type auditor struct{ q *db.Queries }
func (r *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason engine.DropReason) error {
raw, _ := decodeSlackRaw(msg) // event_type is best-effort; a decode miss still audits the drop
return r.q.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
+ ID: dbid.NewV7(),
ChannelType: string(TypeSlack),
EventType: raw.EventType,
DropReason: string(reason),
diff --git a/server/internal/integrations/telegram/resolvers.go b/server/internal/integrations/telegram/resolvers.go
index a935234fde..da7cca7bbd 100644
--- a/server/internal/integrations/telegram/resolvers.go
+++ b/server/internal/integrations/telegram/resolvers.go
@@ -15,6 +15,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
)
// This file is the Telegram ResolverSet: the platform-specific seams the
@@ -246,6 +247,7 @@ type auditor struct{ q *db.Queries }
func (r *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason engine.DropReason) error {
raw, _ := decodeTelegramRaw(msg) // best-effort; a decode miss still audits
return r.q.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
+ ID: dbid.NewV7(),
ChannelType: string(TypeTelegram),
EventType: raw.EventType,
DropReason: string(reason),
diff --git a/server/internal/integrations/wecom/wecom_resolvers.go b/server/internal/integrations/wecom/wecom_resolvers.go
index 1868ae26c3..64932337cb 100644
--- a/server/internal/integrations/wecom/wecom_resolvers.go
+++ b/server/internal/integrations/wecom/wecom_resolvers.go
@@ -20,6 +20,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
)
// originWecomChat is the issue.origin_type label written for issues created
@@ -294,6 +295,7 @@ func (a *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channe
instIDArg = instID
}
return a.store.Queries.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
+ ID: dbid.NewV7(),
InstallationID: instIDArg,
ChannelType: channelTypeWecom,
ChannelChatID: textOrNull(msg.Source.ChatID),
diff --git a/server/internal/scheduler/claim_uuidv7_test.go b/server/internal/scheduler/claim_uuidv7_test.go
new file mode 100644
index 0000000000..2768974a33
--- /dev/null
+++ b/server/internal/scheduler/claim_uuidv7_test.go
@@ -0,0 +1,51 @@
+package scheduler
+
+import (
+ "context"
+ "testing"
+
+ "github.com/google/uuid"
+)
+
+// TestClaimIDIsUUIDv7 covers the one converted INSERT that does not go through
+// sqlc: tryClaim's hand-written statement in db_ops.go. Execution rows are
+// append-only and written on every tick of every job, so their primary key is
+// minted as a v7 for index locality — while lease_token stays random, because a
+// claim token must not leak a guessable timestamp.
+func TestClaimIDIsUUIDv7(t *testing.T) {
+ pool := integrationPool(t)
+ job := newTestJobSpec(uniqueJobName(t, "claim_uuidv7"))
+ t.Cleanup(func() { cleanupExecutions(t, pool, job.Name) })
+
+ ctx := context.Background()
+ now, err := dbNow(ctx, pool)
+ if err != nil {
+ t.Fatalf("dbNow: %v", err)
+ }
+ planTime := FloorPlan(now, job.Cadence)
+
+ c, err := tryClaim(ctx, pool, job, ScopeGlobal, planTime, now, "runner-uuidv7")
+ if err != nil {
+ t.Fatalf("tryClaim: %v", err)
+ }
+ if !c.Won {
+ t.Fatal("expected a fresh insert to win the claim")
+ }
+ if v := c.ID.Version(); v != 7 {
+ t.Errorf("sys_cron_executions.id is v%d (%s), want v7", v, c.ID)
+ }
+ if v := c.LeaseToken.Version(); v != 4 {
+ t.Errorf("lease_token is v%d (%s), want a random v4 — a lease token must not embed its creation time", v, c.LeaseToken)
+ }
+
+ // The value the row holds, not just the value RETURNING echoed back.
+ var stored uuid.UUID
+ if err := pool.QueryRow(ctx,
+ `SELECT id FROM sys_cron_executions WHERE job_name = $1 AND plan_time = $2`,
+ job.Name, planTime).Scan(&stored); err != nil {
+ t.Fatalf("read back execution row: %v", err)
+ }
+ if stored != c.ID {
+ t.Errorf("stored id %s != claimed id %s", stored, c.ID)
+ }
+}
diff --git a/server/internal/scheduler/db_ops.go b/server/internal/scheduler/db_ops.go
index 8b804f4121..7bd256456e 100644
--- a/server/internal/scheduler/db_ops.go
+++ b/server/internal/scheduler/db_ops.go
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/pkg/dbid"
)
// ErrLeaseLost is returned by heartbeat / terminal-update primitives
@@ -72,13 +73,15 @@ func tryClaim(
status, attempt, max_attempts,
runner_id, lease_token,
heartbeat_at, stale_after,
- started_at, updated_at
+ started_at, updated_at,
+ id
) VALUES (
$1, $2, $3, $4,
'RUNNING', 1, $5,
$6, gen_random_uuid(),
$7::timestamptz, $7::timestamptz + make_interval(secs => $8),
- $7::timestamptz, $7::timestamptz
+ $7::timestamptz, $7::timestamptz,
+ COALESCE($9::uuid, gen_random_uuid())
)
ON CONFLICT ON CONSTRAINT uq_sys_cron_execution DO NOTHING
RETURNING id, lease_token, attempt
@@ -94,6 +97,10 @@ func tryClaim(
job.MaxAttempts,
runnerID,
dbTime, staleSecs,
+ // Execution rows are append-only and high-churn, so the id is a v7 for
+ // primary-key locality. lease_token stays gen_random_uuid(): it is a
+ // claim token, and it must not carry a guessable timestamp.
+ dbid.NewV7(),
).Scan(&c.ID, &c.LeaseToken, &c.Attempt)
if err == nil {
c.Won = true
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 8b8fc31625..0da3484b11 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -24,6 +24,7 @@ import (
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -216,6 +217,7 @@ func (s *AutopilotService) AdmitAutopilotWebhookDelivery(
initialStatus = "running"
}
run, _, err := s.createAutopilotRunWithQuota(ctx, autopilot.WorkspaceID, "webhook", "webhook:"+util.UUIDToString(deliveryID), db.CreateAutopilotRunParams{
+ ID: dbid.NewV7(),
AutopilotID: autopilot.ID,
TriggerID: triggerID,
Source: "webhook",
@@ -532,6 +534,7 @@ func (s *AutopilotService) dispatchAutopilot(
}
run, reused, err := s.createAutopilotRunWithQuota(ctx, autopilot.WorkspaceID, source, idempotencyKey, db.CreateAutopilotRunParams{
+ ID: dbid.NewV7(),
AutopilotID: autopilot.ID,
TriggerID: triggerID,
Source: source,
@@ -682,6 +685,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
}
issue, err := qtx.CreateIssueWithOrigin(ctx, db.CreateIssueWithOriginParams{
+ ID: dbid.NewV7(),
WorkspaceID: ap.WorkspaceID,
Title: title,
Description: description,
@@ -847,6 +851,7 @@ func (s *AutopilotService) notifyAutopilotSubscribersOnCreate(
continue
}
item, err := s.Queries.CreateInboxItem(ctx, db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
WorkspaceID: ap.WorkspaceID,
RecipientType: "member",
RecipientID: sub.UserID,
@@ -975,6 +980,7 @@ func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot,
}
apSource, _, apEvidenceKind, apEvidenceRef := attributionCreateParams(autopilotAttr)
task, err := s.Queries.CreateAutopilotTask(ctx, db.CreateAutopilotTaskParams{
+ ID: dbid.NewV7(),
AgentID: agent.ID,
RuntimeID: agent.RuntimeID,
Priority: 0,
@@ -1445,6 +1451,7 @@ func (s *AutopilotService) recordSkippedRun(
code = pgtype.Text{String: string(reasonCode[0]), Valid: true}
}
run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{
+ ID: dbid.NewV7(),
AutopilotID: autopilot.ID,
TriggerID: triggerID,
Source: source,
diff --git a/server/internal/service/issue.go b/server/internal/service/issue.go
index 1268d4464b..52908be05b 100644
--- a/server/internal/service/issue.go
+++ b/server/internal/service/issue.go
@@ -18,6 +18,7 @@ import (
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -297,6 +298,7 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss
var assignedTask db.AgentTaskQueue
if p.OriginType.Valid {
issue, err = qtx.CreateIssueWithOrigin(ctx, db.CreateIssueWithOriginParams{
+ ID: dbid.NewV7(),
WorkspaceID: p.WorkspaceID,
Title: p.Title,
Description: p.Description,
@@ -318,6 +320,7 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss
})
} else {
issue, err = qtx.CreateIssue(ctx, db.CreateIssueParams{
+ ID: dbid.NewV7(),
WorkspaceID: p.WorkspaceID,
Title: p.Title,
Description: p.Description,
diff --git a/server/internal/service/runtime_unusable_notice.go b/server/internal/service/runtime_unusable_notice.go
index aed1556d91..875e54ca0b 100644
--- a/server/internal/service/runtime_unusable_notice.go
+++ b/server/internal/service/runtime_unusable_notice.go
@@ -8,6 +8,7 @@ import (
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -29,6 +30,7 @@ func (s *IssueService) noteRuntimeUnusable(ctx context.Context, issue db.Issue,
// author_type='system', author_id=zero UUID. The zero UUID is a valid 16
// byte value and the column is NOT NULL; clients branch on author_type.
created, err := s.Queries.CreateComment(ctx, db.CreateCommentParams{
+ ID: dbid.NewV7(),
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
AuthorType: "system",
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index d4ffd13f0b..086c5aab0c 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -26,6 +26,7 @@ import (
"github.com/multica-ai/multica/server/internal/runtimeapps"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/featureflag"
"github.com/multica-ai/multica/server/pkg/protocol"
"github.com/multica-ai/multica/server/pkg/redact"
@@ -1113,6 +1114,7 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue
runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)
attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
createParams := db.CreateAgentTaskParams{
+ ID: dbid.NewV7(),
AgentID: issue.AssigneeID,
RuntimeID: agent.RuntimeID,
IssueID: issue.ID,
@@ -1139,6 +1141,7 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue
var task db.AgentTaskQueue
if fireAt.Valid {
task, err = s.Queries.CreateDeferredChannelIssueTask(ctx, db.CreateDeferredChannelIssueTaskParams{
+ ID: dbid.NewV7(),
AgentID: createParams.AgentID,
RuntimeID: createParams.RuntimeID,
IssueID: createParams.IssueID,
@@ -1263,6 +1266,7 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, iss
runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)
attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
task, err := s.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{
+ ID: dbid.NewV7(),
AgentID: agentID,
RuntimeID: agent.RuntimeID,
IssueID: issue.ID,
@@ -1344,6 +1348,7 @@ func (s *TaskService) EnqueueDeferredAssigneeFallback(ctx context.Context, issue
attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
isLeader := squadID.Valid
task, err := s.Queries.CreateDeferredAgentTask(ctx, db.CreateDeferredAgentTaskParams{
+ ID: dbid.NewV7(),
AgentID: agentID,
RuntimeID: agent.RuntimeID,
IssueID: issue.ID,
@@ -1492,6 +1497,7 @@ func (s *TaskService) EnqueueQuickCreateTask(ctx context.Context, workspaceID, r
attrSource, _, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, requesterID, agent)
task, err := s.Queries.CreateQuickCreateTask(ctx, db.CreateQuickCreateTaskParams{
+ ID: dbid.NewV7(),
AgentID: agentID,
RuntimeID: agent.RuntimeID,
Priority: priorityToInt("high"),
@@ -1682,6 +1688,7 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
mediaPendingUntil = pgtype.Timestamptz{}
}
task, err := qtx.CreateChatTask(ctx, db.CreateChatTaskParams{
+ ID: dbid.NewV7(),
AgentID: chatSession.AgentID,
RuntimeID: agent.RuntimeID,
Priority: 2, // medium priority for chat
@@ -1971,6 +1978,7 @@ func (s *TaskService) SendDirectChatMessage(
out.Queued = queued
task, err := qtx.CreateChatTask(ctx, db.CreateChatTaskParams{
+ ID: dbid.NewV7(),
AgentID: session.AgentID,
RuntimeID: carrier.RuntimeID,
Priority: 2, // medium priority for chat; matches EnqueueChatTask
@@ -2014,6 +2022,7 @@ func (s *TaskService) SendDirectChatMessage(
// Create the user message already owned by this task (task_id = task.id),
// so it belongs to this immutable input batch the instant it exists.
msg, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ ID: dbid.NewV7(),
ChatSessionID: session.ID,
Role: "user",
Content: content,
@@ -2107,6 +2116,7 @@ func (s *TaskService) OpenMikaOnboardingChat(ctx context.Context, session db.Cha
}
kickoffRow, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ ID: dbid.NewV7(),
ChatSessionID: session.ID,
Role: "user",
Content: kickoff,
@@ -2120,6 +2130,7 @@ func (s *TaskService) OpenMikaOnboardingChat(ctx context.Context, session db.Cha
// Ordered one microsecond after the kickoff — see the query comment for
// why a shared transaction timestamp is not good enough here.
openingRow, err := qtx.CreateMikaOnboardingOpening(ctx, db.CreateMikaOnboardingOpeningParams{
+ ID: dbid.NewV7(),
ChatSessionID: session.ID,
KickoffCreatedAt: kickoffRow.CreatedAt,
Content: opening,
@@ -2604,6 +2615,7 @@ func (s *TaskService) settleQueuedChatInput(
}
if channelIngested {
if _, err := createAssistantChatMessage(ctx, qtx, db.CreateChatMessageParams{
+ ID: dbid.NewV7(),
ChatSessionID: task.ChatSessionID,
Role: "assistant",
Content: "Stopped.",
@@ -2751,6 +2763,7 @@ func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.
return nil
}
if _, err := createAssistantChatMessage(ctx, qtx, db.CreateChatMessageParams{
+ ID: dbid.NewV7(),
ChatSessionID: task.ChatSessionID,
Role: "assistant",
Content: "Stopped.",
@@ -2906,6 +2919,7 @@ func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID
return nil
}
row, err := createAssistantChatMessage(ctx, qtx, db.CreateChatMessageParams{
+ ID: dbid.NewV7(),
ChatSessionID: claimed.ChatSessionID,
Role: "assistant",
Content: "Stopped.",
@@ -3910,6 +3924,7 @@ func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Qu
}
params := db.CreateChatMessageParams{
+ ID: dbid.NewV7(),
ChatSessionID: task.ChatSessionID,
Role: "assistant",
TaskID: task.ID,
@@ -4191,6 +4206,7 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
// and the bumped chat-retry priority; broadcast/notify happen after commit.
if wantRetry {
child, cerr := qtx.CreateRetryTask(ctx, db.CreateRetryTaskParams{
+ NewTaskID: dbid.NewV7(),
ID: taskID,
FireAt: retryFireAt,
MaxAttempts: retryMaxAttempts,
@@ -4226,6 +4242,7 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
return fmt.Errorf("release onboarding kickoff: %w", err)
}
if _, err := createAssistantChatMessage(ctx, qtx, db.CreateChatMessageParams{
+ ID: dbid.NewV7(),
ChatSessionID: t.ChatSessionID,
Role: "assistant",
Content: redact.Text(errMsg),
@@ -4556,6 +4573,7 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
retryFireAt = pgtype.Timestamptz{Time: time.Now().Add(delay), Valid: true}
}
child, err := s.Queries.CreateRetryTask(ctx, db.CreateRetryTaskParams{
+ NewTaskID: dbid.NewV7(),
ID: parent.ID,
FireAt: retryFireAt,
MaxAttempts: pgtype.Int4{Int32: retryAttemptCeiling(reason, parent.MaxAttempts), Valid: true},
@@ -5076,6 +5094,7 @@ func (s *TaskService) ensureDelegatedFailureRecoveryComment(ctx context.Context,
return fmt.Errorf("find recovery comment: %w", err)
}
createdComment, err := qtx.CreateComment(ctx, db.CreateCommentParams{
+ ID: dbid.NewV7(),
IssueID: target.issue.ID,
WorkspaceID: target.issue.WorkspaceID,
AuthorType: "system",
@@ -5181,6 +5200,7 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targe
}
createdComment, err := qtx.CreateComment(ctx, db.CreateCommentParams{
+ ID: dbid.NewV7(),
IssueID: target.issue.ID,
WorkspaceID: target.issue.WorkspaceID,
AuthorType: "system",
@@ -5222,6 +5242,7 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targe
return fmt.Errorf("encode delegated failure exhaustion details: %w", err)
}
exhaustedInbox, err = qtx.CreateInboxItem(ctx, db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
WorkspaceID: target.issue.WorkspaceID,
RecipientType: "member",
RecipientID: recipient,
@@ -5361,6 +5382,7 @@ func (s *TaskService) dispatchDelegatedFailureRecovery(ctx context.Context, targ
}
overlay := s.buildRuntimeMCPOverlay(ctx, originator, target.agent)
task, err := s.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{
+ ID: dbid.NewV7(),
AgentID: target.agent.ID,
RuntimeID: target.agent.RuntimeID,
IssueID: target.issue.ID,
@@ -6022,6 +6044,7 @@ func (s *TaskService) createAgentComment(ctx context.Context, issueID, agentID p
}
}
created, err := s.Queries.CreateComment(ctx, db.CreateCommentParams{
+ ID: dbid.NewV7(),
IssueID: issueID,
WorkspaceID: issue.WorkspaceID,
AuthorType: "agent",
@@ -6333,6 +6356,7 @@ func (s *TaskService) notifyQuickCreateCompleted(ctx context.Context, task db.Ag
"original_prompt": qc.Prompt,
})
item, err := s.Queries.CreateInboxItem(ctx, db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
WorkspaceID: workspaceID,
RecipientType: "member",
RecipientID: requesterID,
@@ -6432,6 +6456,7 @@ func (s *TaskService) writeQuickCreateOutcomeInbox(ctx context.Context, task db.
"error": redact.Text(errMsg),
})
item, err := s.Queries.CreateInboxItem(ctx, db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
WorkspaceID: workspaceID,
RecipientType: "member",
RecipientID: requesterID,
diff --git a/server/pkg/db/generated/activity.sql.go b/server/pkg/db/generated/activity.sql.go
index 87f7db0bea..badd12f9c2 100644
--- a/server/pkg/db/generated/activity.sql.go
+++ b/server/pkg/db/generated/activity.sql.go
@@ -60,8 +60,8 @@ func (q *Queries) CountAssigneeChangesByActor(ctx context.Context, arg CountAssi
const createActivity = `-- name: CreateActivity :one
INSERT INTO activity_log (
- workspace_id, issue_id, actor_type, actor_id, action, details
-) VALUES ($1, $2, $3, $4, $5, $6)
+ workspace_id, issue_id, actor_type, actor_id, action, details, id
+) VALUES ($1, $2, $3, $4, $5, $6, COALESCE($7::uuid, gen_random_uuid()))
RETURNING id, workspace_id, issue_id, actor_type, actor_id, action, details, created_at
`
@@ -72,6 +72,7 @@ type CreateActivityParams struct {
ActorID pgtype.UUID `json:"actor_id"`
Action string `json:"action"`
Details []byte `json:"details"`
+ ID pgtype.UUID `json:"id"`
}
func (q *Queries) CreateActivity(ctx context.Context, arg CreateActivityParams) (ActivityLog, error) {
@@ -82,6 +83,7 @@ func (q *Queries) CreateActivity(ctx context.Context, arg CreateActivityParams)
arg.ActorID,
arg.Action,
arg.Details,
+ arg.ID,
)
var i ActivityLog
err := row.Scan(
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 9c016ecfd6..c333b20800 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -2104,7 +2104,8 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,
squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
- originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id
+ originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,
+ id
)
SELECT
$1, $2, $3, 'queued', $4, $5,
@@ -2128,7 +2129,8 @@ SELECT
$19,
$20,
$21,
- $22
+ $22,
+ COALESCE($23::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
`
@@ -2156,6 +2158,7 @@ type CreateAgentTaskParams struct {
RerunOfTaskID pgtype.UUID `json:"rerun_of_task_id"`
TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ ID pgtype.UUID `json:"id"`
}
// Fenced against workspace teardown: lock_task_owner_rows (migration 284)
@@ -2169,6 +2172,13 @@ type CreateAgentTaskParams struct {
// issues with no linked PR. Issue-linked tasks never hit quick-create context
// parsing (parseQuickCreateContext short-circuits on IssueID.Valid), so this
// key rides harmlessly alongside.
+// id is minted by the application as a UUIDv7 (pkg/dbid) so consecutive
+// enqueues cluster in a narrow contiguous primary-key range instead of
+// scattering across the B-tree. On a table with existing v4 ids, that range
+// is not necessarily the tree's right edge.
+// COALESCE keeps the column's gen_random_uuid() default reachable, so a caller
+// that passes no id still inserts — it just gets a random v4, exactly as before.
+// The same pattern is used by every INSERT listed in pkg/dbid's write table.
func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, createAgentTask,
arg.AgentID,
@@ -2193,6 +2203,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
arg.RerunOfTaskID,
arg.TriggerEvidenceKind,
arg.TriggerEvidenceRefID,
+ arg.ID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -2258,7 +2269,8 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
trigger_summary, is_leader_task, squad_id, escalation_for_task_id, fire_at,
originator_user_id, accountable_user_id, originator_source,
- delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id
+ delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id,
+ id
)
SELECT
$4, $5, $6, 'deferred', $7,
@@ -2273,7 +2285,8 @@ SELECT
$16,
$17,
$18,
- $19
+ $19,
+ COALESCE($20::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
`
@@ -2298,6 +2311,7 @@ type CreateDeferredAgentTaskParams struct {
DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`
TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ ID pgtype.UUID `json:"id"`
}
// Fenced against workspace teardown: lock_task_owner_rows (migration 284)
@@ -2332,6 +2346,7 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
arg.DelegatedFromTaskID,
arg.TriggerEvidenceKind,
arg.TriggerEvidenceRefID,
+ arg.ID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -2398,7 +2413,8 @@ INSERT INTO agent_task_queue (
coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,
squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id,
- trigger_evidence_kind, trigger_evidence_ref_id, fire_at
+ trigger_evidence_kind, trigger_evidence_ref_id, fire_at,
+ id
)
SELECT
$1, $2, $3, 'deferred', $4, $5,
@@ -2422,7 +2438,8 @@ SELECT
$20,
$21,
$22,
- $23
+ $23,
+ COALESCE($24::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
`
@@ -2451,6 +2468,7 @@ type CreateDeferredChannelIssueTaskParams struct {
TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
FireAt pgtype.Timestamptz `json:"fire_at"`
+ ID pgtype.UUID `json:"id"`
}
// Fenced against workspace teardown: lock_task_owner_rows (migration 284)
@@ -2485,6 +2503,7 @@ func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg Create
arg.TriggerEvidenceKind,
arg.TriggerEvidenceRefID,
arg.FireAt,
+ arg.ID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -2549,7 +2568,8 @@ const createQuickCreateTask = `-- name: CreateQuickCreateTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, context, originator_user_id,
accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
- originator_source, trigger_evidence_kind, trigger_evidence_ref_id
+ originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
+ id
)
SELECT
$1, $2, NULL, 'queued', $3, $4,
@@ -2559,7 +2579,8 @@ SELECT
$8,
$9,
$10,
- $11
+ $11,
+ COALESCE($12::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
`
@@ -2576,6 +2597,7 @@ type CreateQuickCreateTaskParams struct {
OriginatorSource pgtype.Text `json:"originator_source"`
TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ ID pgtype.UUID `json:"id"`
}
// Fenced against workspace teardown: lock_task_owner_rows (migration 284)
@@ -2601,6 +2623,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
arg.OriginatorSource,
arg.TriggerEvidenceKind,
arg.TriggerEvidenceRefID,
+ arg.ID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -2670,7 +2693,8 @@ INSERT INTO agent_task_queue (
squad_id, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id,
trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,
- chat_input_task_id, fire_at
+ chat_input_task_id, fire_at,
+ id
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
@@ -2689,7 +2713,9 @@ SELECT
$5,
p.originator_source, p.delegated_from_task_id, p.rule_version_id,
p.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,
- p.chat_input_task_id, $2
+ p.chat_input_task_id, $2,
+ -- Named new_task_id, not id: $1 above is the PARENT task's id.
+ COALESCE($6::uuid, gen_random_uuid())
FROM agent_task_queue p
WHERE p.id = $1
AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_id)
@@ -2702,6 +2728,7 @@ type CreateRetryTaskParams struct {
MaxAttempts pgtype.Int4 `json:"max_attempts"`
RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ NewTaskID pgtype.UUID `json:"new_task_id"`
}
// Fenced against workspace teardown: lock_task_owner_rows (migration 284)
@@ -2768,6 +2795,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
arg.MaxAttempts,
arg.RuntimeMcpOverlay,
arg.RuntimeConnectedApps,
+ arg.NewTaskID,
)
var i AgentTaskQueue
err := row.Scan(
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 1059c1daa2..aae27ba5ac 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -207,12 +207,12 @@ const createAutopilotRun = `-- name: CreateAutopilotRun :one
INSERT INTO autopilot_run (
autopilot_id, trigger_id, source, status, trigger_payload, squad_id, planned_at,
- webhook_delivery_id, quota_reservation_id, reason_code
+ webhook_delivery_id, quota_reservation_id, reason_code, id
) VALUES (
$1, $4, $2, $3, $5,
$6, $7,
$8, $9,
- $10
+ $10, COALESCE($11::uuid, gen_random_uuid())
) RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at, webhook_delivery_id, quota_reservation_id, reason_code
`
@@ -227,6 +227,7 @@ type CreateAutopilotRunParams struct {
WebhookDeliveryID pgtype.UUID `json:"webhook_delivery_id"`
QuotaReservationID pgtype.UUID `json:"quota_reservation_id"`
ReasonCode pgtype.Text `json:"reason_code"`
+ ID pgtype.UUID `json:"id"`
}
// =====================
@@ -255,6 +256,7 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRun
arg.WebhookDeliveryID,
arg.QuotaReservationID,
arg.ReasonCode,
+ arg.ID,
)
var i AutopilotRun
err := row.Scan(
@@ -285,7 +287,8 @@ const createAutopilotTask = `-- name: CreateAutopilotTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary,
originator_user_id, accountable_user_id, rule_version_id,
- originator_source, trigger_evidence_kind, trigger_evidence_ref_id
+ originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
+ id
)
SELECT
$1, $2, NULL, 'queued', $3, $4, $5,
@@ -294,7 +297,8 @@ SELECT
$8,
$9,
$10,
- $11
+ $11,
+ COALESCE($12::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
`
@@ -311,6 +315,7 @@ type CreateAutopilotTaskParams struct {
OriginatorSource pgtype.Text `json:"originator_source"`
TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ ID pgtype.UUID `json:"id"`
}
// =====================
@@ -345,6 +350,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
arg.OriginatorSource,
arg.TriggerEvidenceKind,
arg.TriggerEvidenceRefID,
+ arg.ID,
)
var i AgentTaskQueue
err := row.Scan(
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index ff8d9ee0c1..7f9a4b145f 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -1635,7 +1635,7 @@ const recordChannelInboundDrop = `-- name: RecordChannelInboundDrop :exec
INSERT INTO channel_inbound_audit (
installation_id, channel_type, channel_chat_id, event_type,
- channel_event_id, channel_message_id, drop_reason
+ channel_event_id, channel_message_id, drop_reason, id
) VALUES (
$4,
$1,
@@ -1643,7 +1643,8 @@ INSERT INTO channel_inbound_audit (
$2,
$6,
$7,
- $3
+ $3,
+ COALESCE($8::uuid, gen_random_uuid())
)
`
@@ -1655,6 +1656,7 @@ type RecordChannelInboundDropParams struct {
ChannelChatID pgtype.Text `json:"channel_chat_id"`
ChannelEventID pgtype.Text `json:"channel_event_id"`
ChannelMessageID pgtype.Text `json:"channel_message_id"`
+ ID pgtype.UUID `json:"id"`
}
// =====================
@@ -1671,6 +1673,7 @@ func (q *Queries) RecordChannelInboundDrop(ctx context.Context, arg RecordChanne
arg.ChannelChatID,
arg.ChannelEventID,
arg.ChannelMessageID,
+ arg.ID,
)
return err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index e2da81b36e..32d19badfe 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -221,7 +221,7 @@ func (q *Queries) CreateChatDraftRestore(ctx context.Context, arg CreateChatDraf
const createChatMessage = `-- name: CreateChatMessage :one
INSERT INTO chat_message (
chat_session_id, role, content, task_id, failure_reason, elapsed_ms,
- message_kind, quick_actions, channel_media_pending_until, channel_ingested
+ message_kind, quick_actions, channel_media_pending_until, channel_ingested, id
)
VALUES (
$1, $2, $3, $4, $5, $6,
@@ -235,7 +235,8 @@ VALUES (
-- fallback window.
CASE WHEN $9::float8 IS NULL THEN NULL
ELSE now() + make_interval(secs => $9::float8) END,
- COALESCE($10::boolean, FALSE)
+ COALESCE($10::boolean, FALSE),
+ COALESCE($11::uuid, gen_random_uuid())
)
RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions
`
@@ -251,6 +252,7 @@ type CreateChatMessageParams struct {
QuickActions []byte `json:"quick_actions"`
ChannelMediaPendingSecs pgtype.Float8 `json:"channel_media_pending_secs"`
ChannelIngested pgtype.Bool `json:"channel_ingested"`
+ ID pgtype.UUID `json:"id"`
}
// message_kind and quick_actions default via COALESCE so every existing caller
@@ -268,6 +270,7 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
arg.QuickActions,
arg.ChannelMediaPendingSecs,
arg.ChannelIngested,
+ arg.ID,
)
var i ChatMessage
err := row.Scan(
@@ -288,8 +291,8 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
}
const createChatSession = `-- name: CreateChatSession :one
-INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id, is_agent_intro, project_id)
-VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2), $5, $6)
+INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id, is_agent_intro, project_id, id)
+VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2), $5, $6, COALESCE($7::uuid, gen_random_uuid()))
RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
`
@@ -300,6 +303,7 @@ type CreateChatSessionParams struct {
Title string `json:"title"`
IsAgentIntro bool `json:"is_agent_intro"`
ProjectID pgtype.UUID `json:"project_id"`
+ ID pgtype.UUID `json:"id"`
}
func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionParams) (ChatSession, error) {
@@ -310,6 +314,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa
arg.Title,
arg.IsAgentIntro,
arg.ProjectID,
+ arg.ID,
)
var i ChatSession
err := row.Scan(
@@ -338,7 +343,7 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
- fire_at
+ fire_at, id
)
SELECT
$1, $2, NULL,
@@ -352,7 +357,8 @@ SELECT
$12,
$13,
$14,
- $6::timestamptz
+ $6::timestamptz,
+ COALESCE($15::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
`
@@ -372,6 +378,7 @@ type CreateChatTaskParams struct {
OriginatorSource pgtype.Text `json:"originator_source"`
TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ ID pgtype.UUID `json:"id"`
}
// Fenced against workspace teardown: lock_task_owner_rows (migration 284)
@@ -397,6 +404,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
arg.OriginatorSource,
arg.TriggerEvidenceKind,
arg.TriggerEvidenceRefID,
+ arg.ID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -458,13 +466,14 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
}
const createMikaOnboardingOpening = `-- name: CreateMikaOnboardingOpening :one
-INSERT INTO chat_message (chat_session_id, role, content, message_kind, created_at)
+INSERT INTO chat_message (chat_session_id, role, content, message_kind, created_at, id)
VALUES (
$1,
'assistant',
$2,
'onboarding_opening',
- $3::timestamptz + interval '1 microsecond'
+ $3::timestamptz + interval '1 microsecond',
+ COALESCE($4::uuid, gen_random_uuid())
)
RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions
`
@@ -473,6 +482,7 @@ type CreateMikaOnboardingOpeningParams struct {
ChatSessionID pgtype.UUID `json:"chat_session_id"`
Content string `json:"content"`
KickoffCreatedAt pgtype.Timestamptz `json:"kickoff_created_at"`
+ ID pgtype.UUID `json:"id"`
}
// Mika's opening reply, written by the server rather than produced by an agent
@@ -488,7 +498,12 @@ type CreateMikaOnboardingOpeningParams struct {
// task_id stays NULL: no agent run produced this row, and nothing may treat it
// as a turn to regenerate or resume.
func (q *Queries) CreateMikaOnboardingOpening(ctx context.Context, arg CreateMikaOnboardingOpeningParams) (ChatMessage, error) {
- row := q.db.QueryRow(ctx, createMikaOnboardingOpening, arg.ChatSessionID, arg.Content, arg.KickoffCreatedAt)
+ row := q.db.QueryRow(ctx, createMikaOnboardingOpening,
+ arg.ChatSessionID,
+ arg.Content,
+ arg.KickoffCreatedAt,
+ arg.ID,
+ )
var i ChatMessage
err := row.Scan(
&i.ID,
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index 3dbb1c4e6c..bd4bc4bcc0 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -206,8 +206,8 @@ WITH touched_issue AS (
WHERE issue.id = $1 AND issue.workspace_id = $2
RETURNING issue.id, issue.workspace_id, issue.revision
), inserted_comment AS (
- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id)
- SELECT ti.id, ti.workspace_id, $3, $4, $5, $6, $7, $8, $9, $10
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id, id)
+ SELECT ti.id, ti.workspace_id, $3, $4, $5, $6, $7, $8, $9, $10, COALESCE($11::uuid, gen_random_uuid())
FROM touched_issue ti
RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision
)
@@ -227,6 +227,7 @@ type CreateCommentParams struct {
SourceTaskID pgtype.UUID `json:"source_task_id"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
ViaPluginID pgtype.UUID `json:"via_plugin_id"`
+ ID pgtype.UUID `json:"id"`
}
type CreateCommentRow struct {
@@ -278,6 +279,7 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (C
arg.SourceTaskID,
arg.QuickActionID,
arg.ViaPluginID,
+ arg.ID,
)
var i CreateCommentRow
err := row.Scan(
diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.go
index 189d9c1bdf..062cb0e212 100644
--- a/server/pkg/db/generated/inbox.sql.go
+++ b/server/pkg/db/generated/inbox.sql.go
@@ -234,8 +234,8 @@ const createInboxItem = `-- name: CreateInboxItem :one
INSERT INTO inbox_item (
workspace_id, recipient_type, recipient_id,
type, severity, issue_id, title, body,
- actor_type, actor_id, details
-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
+ actor_type, actor_id, details, id
+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE($12::uuid, gen_random_uuid()))
RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details
`
@@ -251,6 +251,7 @@ type CreateInboxItemParams struct {
ActorType pgtype.Text `json:"actor_type"`
ActorID pgtype.UUID `json:"actor_id"`
Details []byte `json:"details"`
+ ID pgtype.UUID `json:"id"`
}
func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParams) (InboxItem, error) {
@@ -266,6 +267,7 @@ func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParams
arg.ActorType,
arg.ActorID,
arg.Details,
+ arg.ID,
)
var i InboxItem
err := row.Scan(
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index 91f10cde2e..7f27b2da44 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -175,10 +175,10 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- stage, last_activity_at
+ stage, last_activity_at, id
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- $16, now()
+ $16, now(), COALESCE($17::uuid, gen_random_uuid())
) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at
`
@@ -199,6 +199,7 @@ type CreateIssueParams struct {
Number int32 `json:"number"`
ProjectID pgtype.UUID `json:"project_id"`
Stage pgtype.Int4 `json:"stage"`
+ ID pgtype.UUID `json:"id"`
}
func (q *Queries) CreateIssue(ctx context.Context, arg CreateIssueParams) (Issue, error) {
@@ -219,6 +220,7 @@ func (q *Queries) CreateIssue(ctx context.Context, arg CreateIssueParams) (Issue
arg.Number,
arg.ProjectID,
arg.Stage,
+ arg.ID,
)
var i Issue
err := row.Scan(
@@ -259,10 +261,10 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- origin_type, origin_id, stage, last_activity_at
+ origin_type, origin_id, stage, last_activity_at, id
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- $16, $17, $18, now()
+ $16, $17, $18, now(), COALESCE($19::uuid, gen_random_uuid())
) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at
`
@@ -285,6 +287,7 @@ type CreateIssueWithOriginParams struct {
OriginType pgtype.Text `json:"origin_type"`
OriginID pgtype.UUID `json:"origin_id"`
Stage pgtype.Int4 `json:"stage"`
+ ID pgtype.UUID `json:"id"`
}
func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWithOriginParams) (Issue, error) {
@@ -307,6 +310,7 @@ func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWith
arg.OriginType,
arg.OriginID,
arg.Stage,
+ arg.ID,
)
var i Issue
err := row.Scan(
diff --git a/server/pkg/db/generated/task_token.sql.go b/server/pkg/db/generated/task_token.sql.go
index abd7e0cabc..f05c5e1901 100644
--- a/server/pkg/db/generated/task_token.sql.go
+++ b/server/pkg/db/generated/task_token.sql.go
@@ -12,8 +12,8 @@ import (
)
const createTaskToken = `-- name: CreateTaskToken :one
-INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at)
-VALUES ($1, $2, $3, $4, $5, $6)
+INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at, id)
+VALUES ($1, $2, $3, $4, $5, $6, COALESCE($7::uuid, gen_random_uuid()))
RETURNING id, token_hash, task_id, agent_id, workspace_id, user_id, expires_at, created_at
`
@@ -24,6 +24,7 @@ type CreateTaskTokenParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
UserID pgtype.UUID `json:"user_id"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+ ID pgtype.UUID `json:"id"`
}
func (q *Queries) CreateTaskToken(ctx context.Context, arg CreateTaskTokenParams) (TaskToken, error) {
@@ -34,6 +35,7 @@ func (q *Queries) CreateTaskToken(ctx context.Context, arg CreateTaskTokenParams
arg.WorkspaceID,
arg.UserID,
arg.ExpiresAt,
+ arg.ID,
)
var i TaskToken
err := row.Scan(
diff --git a/server/pkg/db/generated/webhook_delivery.sql.go b/server/pkg/db/generated/webhook_delivery.sql.go
index 174aa8cc3e..eaae099d3a 100644
--- a/server/pkg/db/generated/webhook_delivery.sql.go
+++ b/server/pkg/db/generated/webhook_delivery.sql.go
@@ -246,13 +246,13 @@ INSERT INTO webhook_delivery (
workspace_id, autopilot_id, trigger_id, provider, event,
dedupe_key, dedupe_source, signature_status, status,
selected_headers, content_type, raw_body,
- replayed_from_delivery_id, replay_idempotency_key, reason_code
+ replayed_from_delivery_id, replay_idempotency_key, reason_code, id
) VALUES (
$1, $2, $3, $4, $5,
$9, $10, $6, $7,
$8, $11, $12,
$13, $14,
- $15
+ $15, COALESCE($16::uuid, gen_random_uuid())
) RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key
`
@@ -272,6 +272,7 @@ type CreateWebhookDeliveryParams struct {
ReplayedFromDeliveryID pgtype.UUID `json:"replayed_from_delivery_id"`
ReplayIdempotencyKey pgtype.Text `json:"replay_idempotency_key"`
ReasonCode pgtype.Text `json:"reason_code"`
+ ID pgtype.UUID `json:"id"`
}
// =====================
@@ -297,6 +298,7 @@ func (q *Queries) CreateWebhookDelivery(ctx context.Context, arg CreateWebhookDe
arg.ReplayedFromDeliveryID,
arg.ReplayIdempotencyKey,
arg.ReasonCode,
+ arg.ID,
)
var i WebhookDelivery
err := row.Scan(
diff --git a/server/pkg/db/queries/activity.sql b/server/pkg/db/queries/activity.sql
index 0517e74511..6a1dde26c7 100644
--- a/server/pkg/db/queries/activity.sql
+++ b/server/pkg/db/queries/activity.sql
@@ -28,8 +28,8 @@ WHERE id = $1;
-- name: CreateActivity :one
INSERT INTO activity_log (
- workspace_id, issue_id, actor_type, actor_id, action, details
-) VALUES ($1, $2, $3, $4, $5, $6)
+ workspace_id, issue_id, actor_type, actor_id, action, details, id
+) VALUES ($1, $2, $3, $4, $5, $6, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid()))
RETURNING *;
-- name: HasSquadLeaderNoActionEvaluationForTask :one
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 04cdf91605..2e4cfcf79b 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -320,11 +320,19 @@ LIMIT 5;
-- issues with no linked PR. Issue-linked tasks never hit quick-create context
-- parsing (parseQuickCreateContext short-circuits on IssueID.Valid), so this
-- key rides harmlessly alongside.
+-- id is minted by the application as a UUIDv7 (pkg/dbid) so consecutive
+-- enqueues cluster in a narrow contiguous primary-key range instead of
+-- scattering across the B-tree. On a table with existing v4 ids, that range
+-- is not necessarily the tree's right edge.
+-- COALESCE keeps the column's gen_random_uuid() default reachable, so a caller
+-- that passes no id still inserts — it just gets a random v4, exactly as before.
+-- The same pattern is used by every INSERT listed in pkg/dbid's write table.
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,
squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
- originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id
+ originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,
+ id
)
SELECT
$1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),
@@ -348,7 +356,8 @@ SELECT
sqlc.narg(rule_version_id),
sqlc.narg(rerun_of_task_id),
sqlc.narg(trigger_evidence_kind),
- sqlc.narg(trigger_evidence_ref_id)
+ sqlc.narg(trigger_evidence_ref_id),
+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
RETURNING *;
@@ -365,7 +374,8 @@ INSERT INTO agent_task_queue (
coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,
squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id,
- trigger_evidence_kind, trigger_evidence_ref_id, fire_at
+ trigger_evidence_kind, trigger_evidence_ref_id, fire_at,
+ id
)
SELECT
$1, $2, $3, 'deferred', $4, sqlc.narg(trigger_comment_id),
@@ -389,7 +399,8 @@ SELECT
sqlc.narg(rerun_of_task_id),
sqlc.narg(trigger_evidence_kind),
sqlc.narg(trigger_evidence_ref_id),
- @fire_at
+ @fire_at,
+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
RETURNING *;
@@ -428,7 +439,8 @@ WHERE id = @id
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, context, originator_user_id,
accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
- originator_source, trigger_evidence_kind, trigger_evidence_ref_id
+ originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
+ id
)
SELECT
$1, $2, NULL, 'queued', $3, $4,
@@ -438,7 +450,8 @@ SELECT
sqlc.narg(runtime_connected_apps),
sqlc.narg(originator_source),
sqlc.narg(trigger_evidence_kind),
- sqlc.narg(trigger_evidence_ref_id)
+ sqlc.narg(trigger_evidence_ref_id),
+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
RETURNING *;
@@ -458,7 +471,8 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
trigger_summary, is_leader_task, squad_id, escalation_for_task_id, fire_at,
originator_user_id, accountable_user_id, originator_source,
- delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id
+ delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id,
+ id
)
SELECT
@agent_id, @runtime_id, @issue_id, 'deferred', @priority,
@@ -473,7 +487,8 @@ SELECT
sqlc.narg(originator_source),
sqlc.narg(delegated_from_task_id),
sqlc.narg(trigger_evidence_kind),
- sqlc.narg(trigger_evidence_ref_id)
+ sqlc.narg(trigger_evidence_ref_id),
+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
RETURNING *;
@@ -558,7 +573,8 @@ INSERT INTO agent_task_queue (
squad_id, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
originator_source, delegated_from_task_id, rule_version_id,
trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,
- chat_input_task_id, fire_at
+ chat_input_task_id, fire_at,
+ id
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
@@ -577,7 +593,9 @@ SELECT
sqlc.narg(runtime_connected_apps),
p.originator_source, p.delegated_from_task_id, p.rule_version_id,
p.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,
- p.chat_input_task_id, sqlc.narg(fire_at)
+ p.chat_input_task_id, sqlc.narg(fire_at),
+ -- Named new_task_id, not id: $1 above is the PARENT task's id.
+ COALESCE(sqlc.narg('new_task_id')::uuid, gen_random_uuid())
FROM agent_task_queue p
WHERE p.id = $1
AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_id)
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index 9a9c0f21d9..dbe3e15070 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -297,12 +297,12 @@ RETURNING *;
-- a second run for the same (trigger_id, planned_at) pair (MUL-3551).
INSERT INTO autopilot_run (
autopilot_id, trigger_id, source, status, trigger_payload, squad_id, planned_at,
- webhook_delivery_id, quota_reservation_id, reason_code
+ webhook_delivery_id, quota_reservation_id, reason_code, id
) VALUES (
$1, sqlc.narg('trigger_id'), $2, $3, sqlc.narg('trigger_payload'),
sqlc.narg('squad_id'), sqlc.narg('planned_at'),
sqlc.narg('webhook_delivery_id'), sqlc.narg('quota_reservation_id'),
- sqlc.narg('reason_code')
+ sqlc.narg('reason_code'), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
) RETURNING *;
-- name: GetAutopilotRunByTriggerAndPlanned :one
@@ -571,7 +571,8 @@ ORDER BY t.id;
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary,
originator_user_id, accountable_user_id, rule_version_id,
- originator_source, trigger_evidence_kind, trigger_evidence_ref_id
+ originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
+ id
)
SELECT
$1, $2, NULL, 'queued', $3, $4, sqlc.narg(trigger_summary),
@@ -580,7 +581,8 @@ SELECT
sqlc.narg(rule_version_id),
sqlc.narg(originator_source),
sqlc.narg(trigger_evidence_kind),
- sqlc.narg(trigger_evidence_ref_id)
+ sqlc.narg(trigger_evidence_ref_id),
+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
RETURNING *;
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index 11d74ac164..3f6c712b76 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -626,7 +626,7 @@ WHERE received_at < $1;
-- column — only routing / identity / drop_reason / timestamp.
INSERT INTO channel_inbound_audit (
installation_id, channel_type, channel_chat_id, event_type,
- channel_event_id, channel_message_id, drop_reason
+ channel_event_id, channel_message_id, drop_reason, id
) VALUES (
sqlc.narg('installation_id'),
$1,
@@ -634,7 +634,8 @@ INSERT INTO channel_inbound_audit (
$2,
sqlc.narg('channel_event_id'),
sqlc.narg('channel_message_id'),
- $3
+ $3,
+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
);
-- name: ListChannelInboundAuditByInstallation :many
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 17e0c42430..e0ff9cb066 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -1,6 +1,6 @@
-- name: CreateChatSession :one
-INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id, is_agent_intro, project_id)
-VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2), $5, sqlc.narg('project_id'))
+INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id, is_agent_intro, project_id, id)
+VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2), $5, sqlc.narg('project_id'), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid()))
RETURNING *;
-- name: ClearChatSessionProjectByProject :exec
@@ -450,7 +450,7 @@ WHERE id = $1;
-- 'no_response' to mark a visible turn with no text output (MUL-4351).
INSERT INTO chat_message (
chat_session_id, role, content, task_id, failure_reason, elapsed_ms,
- message_kind, quick_actions, channel_media_pending_until, channel_ingested
+ message_kind, quick_actions, channel_media_pending_until, channel_ingested, id
)
VALUES (
$1, $2, $3, sqlc.narg(task_id), sqlc.narg(failure_reason), sqlc.narg(elapsed_ms),
@@ -464,7 +464,8 @@ VALUES (
-- fallback window.
CASE WHEN sqlc.narg(channel_media_pending_secs)::float8 IS NULL THEN NULL
ELSE now() + make_interval(secs => sqlc.narg(channel_media_pending_secs)::float8) END,
- COALESCE(sqlc.narg(channel_ingested)::boolean, FALSE)
+ COALESCE(sqlc.narg(channel_ingested)::boolean, FALSE),
+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
)
RETURNING *;
@@ -926,7 +927,7 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
- fire_at
+ fire_at, id
)
SELECT
$1, $2, NULL,
@@ -940,7 +941,8 @@ SELECT
sqlc.narg(originator_source),
sqlc.narg(trigger_evidence_kind),
sqlc.narg(trigger_evidence_ref_id),
- sqlc.narg('fire_at')::timestamptz
+ sqlc.narg('fire_at')::timestamptz,
+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
RETURNING *;
@@ -1423,13 +1425,14 @@ SELECT
--
-- task_id stays NULL: no agent run produced this row, and nothing may treat it
-- as a turn to regenerate or resume.
-INSERT INTO chat_message (chat_session_id, role, content, message_kind, created_at)
+INSERT INTO chat_message (chat_session_id, role, content, message_kind, created_at, id)
VALUES (
sqlc.arg(chat_session_id),
'assistant',
sqlc.arg(content),
'onboarding_opening',
- sqlc.arg(kickoff_created_at)::timestamptz + interval '1 microsecond'
+ sqlc.arg(kickoff_created_at)::timestamptz + interval '1 microsecond',
+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
)
RETURNING *;
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index ca015d56fa..07127eb37d 100644
--- a/server/pkg/db/queries/comment.sql
+++ b/server/pkg/db/queries/comment.sql
@@ -445,8 +445,8 @@ WITH touched_issue AS (
WHERE issue.id = sqlc.arg(issue_id) AND issue.workspace_id = sqlc.arg(workspace_id)
RETURNING issue.id, issue.workspace_id, issue.revision
), inserted_comment AS (
- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id)
- SELECT ti.id, ti.workspace_id, sqlc.arg(author_type), sqlc.arg(author_id), sqlc.arg(content), sqlc.arg(type), sqlc.narg(parent_id), sqlc.narg(source_task_id), sqlc.narg(quick_action_id), sqlc.narg(via_plugin_id)
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id, id)
+ SELECT ti.id, ti.workspace_id, sqlc.arg(author_type), sqlc.arg(author_id), sqlc.arg(content), sqlc.arg(type), sqlc.narg(parent_id), sqlc.narg(source_task_id), sqlc.narg(quick_action_id), sqlc.narg(via_plugin_id), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
FROM touched_issue ti
RETURNING *
)
diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sql
index 1256bd4e41..5116968344 100644
--- a/server/pkg/db/queries/inbox.sql
+++ b/server/pkg/db/queries/inbox.sql
@@ -51,8 +51,8 @@ WHERE id = $1 AND workspace_id = $2;
INSERT INTO inbox_item (
workspace_id, recipient_type, recipient_id,
type, severity, issue_id, title, body,
- actor_type, actor_id, details
-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
+ actor_type, actor_id, details, id
+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid()))
RETURNING *;
-- name: MarkInboxRead :one
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index 0e6a7f1721..6f226c23dc 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -134,10 +134,10 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- stage, last_activity_at
+ stage, last_activity_at, id
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- sqlc.narg('stage'), now()
+ sqlc.narg('stage'), now(), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
) RETURNING *;
-- name: GetIssueByNumber :one
@@ -225,10 +225,10 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- origin_type, origin_id, stage, last_activity_at
+ origin_type, origin_id, stage, last_activity_at, id
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- sqlc.narg('origin_type'), sqlc.narg('origin_id'), sqlc.narg('stage'), now()
+ sqlc.narg('origin_type'), sqlc.narg('origin_id'), sqlc.narg('stage'), now(), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
) RETURNING *;
-- name: LockIssueDuplicateKey :exec
diff --git a/server/pkg/db/queries/task_token.sql b/server/pkg/db/queries/task_token.sql
index f9eea21459..fe98438e71 100644
--- a/server/pkg/db/queries/task_token.sql
+++ b/server/pkg/db/queries/task_token.sql
@@ -1,6 +1,6 @@
-- name: CreateTaskToken :one
-INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at)
-VALUES ($1, $2, $3, $4, $5, $6)
+INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at, id)
+VALUES ($1, $2, $3, $4, $5, $6, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid()))
RETURNING *;
-- name: GetTaskTokenByHash :one
diff --git a/server/pkg/db/queries/webhook_delivery.sql b/server/pkg/db/queries/webhook_delivery.sql
index fe365b4656..12d5504661 100644
--- a/server/pkg/db/queries/webhook_delivery.sql
+++ b/server/pkg/db/queries/webhook_delivery.sql
@@ -10,13 +10,13 @@ INSERT INTO webhook_delivery (
workspace_id, autopilot_id, trigger_id, provider, event,
dedupe_key, dedupe_source, signature_status, status,
selected_headers, content_type, raw_body,
- replayed_from_delivery_id, replay_idempotency_key, reason_code
+ replayed_from_delivery_id, replay_idempotency_key, reason_code, id
) VALUES (
$1, $2, $3, $4, $5,
sqlc.narg('dedupe_key'), sqlc.narg('dedupe_source'), $6, $7,
$8, sqlc.narg('content_type'), sqlc.narg('raw_body'),
sqlc.narg('replayed_from_delivery_id'), sqlc.narg('replay_idempotency_key'),
- sqlc.narg('reason_code')
+ sqlc.narg('reason_code'), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
) RETURNING *;
-- name: GetWebhookReplayByIdempotencyKey :one
diff --git a/server/pkg/dbid/dbid.go b/server/pkg/dbid/dbid.go
new file mode 100644
index 0000000000..e38efdb4c7
--- /dev/null
+++ b/server/pkg/dbid/dbid.go
@@ -0,0 +1,58 @@
+// Package dbid mints primary keys for rows the application inserts.
+//
+// Every id produced here is a UUIDv7 (RFC 9562): a 48-bit big-endian
+// millisecond timestamp followed by random bits. Consecutive inserts therefore
+// cluster in a narrow contiguous key range instead of scattering across the
+// primary-key B-tree the way random v4 keys do. On tables that already contain
+// v4 ids, that range is not necessarily the tree's right edge.
+//
+// Scope and rules of use:
+//
+// - Only for identity columns of rows we insert and keep — task queue entries,
+// messages, comments, activity and audit rows. NOT for lease/claim tokens,
+// idempotency keys, or anything used as a secret: those want
+// unpredictability and no embedded timestamp, so they stay on
+// gen_random_uuid()/v4.
+// - The DB-side `DEFAULT gen_random_uuid()` on these columns stays in place,
+// and every query that takes an id from here wraps it in
+// `COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())`. A table therefore
+// holds a mix of v4 and v7 ids forever, which Postgres's uuid type and every
+// parser in this repo accept, and an unset id degrades to today's behaviour
+// instead of violating NOT NULL.
+// - The database fallback makes NewV7 suitable only when the id is used solely
+// as the inserted row's identity. If the application must also use the id as
+// an object key, filename, correlation id, or any other external reference,
+// call uuid.NewV7 directly and handle its error instead; otherwise the
+// database may mint a different id after entropy generation fails.
+// - A v7 embeds its creation time only to millisecond precision and is only
+// approximately ordered across writers. It is not a substitute for
+// created_at and must not be used to derive ordering guarantees.
+// - On an INSERT ... ON CONFLICT, an id passed in is used only if the row is
+// actually inserted; the conflicting row keeps its own id. Callers must read
+// the id back from RETURNING rather than assume the value they minted won.
+package dbid
+
+import (
+ "log/slog"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+// NewV7 returns a fresh UUIDv7 wrapped as a pgtype.UUID, ready to assign to a
+// sqlc-generated parameter struct's ID field.
+//
+// It deliberately has no error return. uuid.NewV7 only fails when the OS
+// entropy source does, which does not happen on a healthy host; if it ever
+// does, this returns the zero (NULL) pgtype.UUID and the query's
+// COALESCE(..., gen_random_uuid()) fallback lets Postgres mint the id instead.
+// That keeps the insert working rather than failing a user request over an id
+// flavour, and keeps ~60 call sites free of an error path that would never run.
+func NewV7() pgtype.UUID {
+ id, err := uuid.NewV7()
+ if err != nil {
+ slog.Error("dbid: uuidv7 generation failed, falling back to the database default", "error", err)
+ return pgtype.UUID{}
+ }
+ return pgtype.UUID{Bytes: [16]byte(id), Valid: true}
+}
diff --git a/server/pkg/dbid/dbid_test.go b/server/pkg/dbid/dbid_test.go
new file mode 100644
index 0000000000..5d284c78e6
--- /dev/null
+++ b/server/pkg/dbid/dbid_test.go
@@ -0,0 +1,50 @@
+package dbid
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/google/uuid"
+)
+
+func TestNewV7ReturnsAValidVersion7UUID(t *testing.T) {
+ got := NewV7()
+ if !got.Valid {
+ t.Fatal("NewV7 returned an invalid pgtype.UUID; the insert would fall back to the DB default")
+ }
+ parsed := uuid.UUID(got.Bytes)
+ if v := parsed.Version(); v != 7 {
+ t.Fatalf("uuid version = %d, want 7 (%s)", v, parsed)
+ }
+ if vr := parsed.Variant(); vr != uuid.RFC4122 {
+ t.Fatalf("uuid variant = %v, want RFC4122 (%s)", vr, parsed)
+ }
+}
+
+func TestNewV7IsUniqueAndNonDecreasing(t *testing.T) {
+ const n = 500
+
+ seen := make(map[uuid.UUID]struct{}, n)
+ var prev []byte
+ for i := 0; i < n; i++ {
+ id := NewV7()
+ if !id.Valid {
+ t.Fatalf("call %d returned an invalid uuid", i)
+ }
+ parsed := uuid.UUID(id.Bytes)
+ if _, dup := seen[parsed]; dup {
+ t.Fatalf("call %d produced a duplicate id %s", i, parsed)
+ }
+ seen[parsed] = struct{}{}
+
+ // The first 6 bytes are the big-endian millisecond timestamp. Within one
+ // process they must never go backwards, which is the whole point of using
+ // v7 for a primary key: byte order tracks insert order, so consecutive
+ // rows land on the same B-tree page.
+ ts := id.Bytes[:6]
+ if prev != nil && bytes.Compare(ts, prev) < 0 {
+ t.Fatalf("call %d timestamp prefix went backwards: %x < %x", i, ts, prev)
+ }
+ prev = append(prev[:0:0], ts...)
+ }
+}
diff --git a/server/pkg/dbid/writes_test.go b/server/pkg/dbid/writes_test.go
new file mode 100644
index 0000000000..a1751a1d14
--- /dev/null
+++ b/server/pkg/dbid/writes_test.go
@@ -0,0 +1,261 @@
+package dbid
+
+import (
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// The tables whose primary keys the application mints as UUIDv7, and the sqlc
+// query that inserts each one. Keeping the list here — rather than deriving it —
+// is deliberate: adding a table to the v7 set is a decision, and it should show
+// up as an edit to this list in review.
+//
+// query is the sqlc query name; arg is the parameter name the query binds the id
+// to (CreateRetryTask already had an `id` parameter for the PARENT task, so its
+// new id is named new_task_id); field is the Go field on the params struct.
+var v7Writes = []struct {
+ table string
+ file string
+ query string
+ arg string
+ field string
+}{
+ {"activity_log", "activity.sql", "CreateActivity", "id", "ID"},
+ {"agent_task_queue", "agent.sql", "CreateAgentTask", "id", "ID"},
+ {"agent_task_queue", "agent.sql", "CreateDeferredChannelIssueTask", "id", "ID"},
+ {"agent_task_queue", "agent.sql", "CreateQuickCreateTask", "id", "ID"},
+ {"agent_task_queue", "agent.sql", "CreateDeferredAgentTask", "id", "ID"},
+ {"agent_task_queue", "agent.sql", "CreateRetryTask", "new_task_id", "NewTaskID"},
+ {"agent_task_queue", "autopilot.sql", "CreateAutopilotTask", "id", "ID"},
+ {"agent_task_queue", "chat.sql", "CreateChatTask", "id", "ID"},
+ {"autopilot_run", "autopilot.sql", "CreateAutopilotRun", "id", "ID"},
+ {"channel_inbound_audit", "channel.sql", "RecordChannelInboundDrop", "id", "ID"},
+ {"chat_message", "chat.sql", "CreateChatMessage", "id", "ID"},
+ {"chat_message", "chat.sql", "CreateMikaOnboardingOpening", "id", "ID"},
+ {"chat_session", "chat.sql", "CreateChatSession", "id", "ID"},
+ {"comment", "comment.sql", "CreateComment", "id", "ID"},
+ {"inbox_item", "inbox.sql", "CreateInboxItem", "id", "ID"},
+ {"issue", "issue.sql", "CreateIssue", "id", "ID"},
+ {"issue", "issue.sql", "CreateIssueWithOrigin", "id", "ID"},
+ {"task_token", "task_token.sql", "CreateTaskToken", "id", "ID"},
+ {"webhook_delivery", "webhook_delivery.sql", "CreateWebhookDelivery", "id", "ID"},
+}
+
+var queryNameRE = regexp.MustCompile(`(?m)^--\s*name:\s*(\w+)\s*:(\w+)`)
+
+// TestV7QueriesBindAnIDWithADatabaseFallback locks in the shape of every
+// converted INSERT: it must accept an id from the application AND keep
+// gen_random_uuid() as the fallback, so a caller that leaves the parameter unset
+// degrades to the pre-change behaviour instead of violating NOT NULL.
+func TestV7QueriesBindAnIDWithADatabaseFallback(t *testing.T) {
+ for _, w := range v7Writes {
+ t.Run(w.query, func(t *testing.T) {
+ block := queryBlock(t, w.file, w.query)
+
+ want := fmt.Sprintf("COALESCE(sqlc.narg('%s')::uuid, gen_random_uuid())", w.arg)
+ if !strings.Contains(block, want) {
+ t.Errorf("%s in %s does not bind its id as %s\n%s", w.query, w.file, want, block)
+ }
+
+ insert := fmt.Sprintf("INSERT INTO %s (", w.table)
+ i := strings.Index(block, insert)
+ if i < 0 {
+ t.Fatalf("%s does not INSERT INTO %s", w.query, w.table)
+ }
+ cols := block[i+len(insert):]
+ cols = cols[:strings.Index(cols, ")")]
+ if !hasColumn(cols, "id") {
+ t.Errorf("%s does not list the id column:\ncolumns: %s", w.query, strings.Join(strings.Fields(cols), " "))
+ }
+ })
+ }
+}
+
+const (
+ dbImportPath = "github.com/multica-ai/multica/server/pkg/db/generated"
+ dbidImportPath = "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+// TestEveryV7ParamsLiteralSetsAnIDAndImportsDBID walks production Go sources
+// and fails if a converted params literal leaves its id unset or lives in a file
+// that does not import dbid. The AST-based check deliberately does not prescribe
+// whether the value is an inline dbid.NewV7 call or a local variable, so routine
+// refactors do not weaken this guard by forcing one source spelling.
+func TestEveryV7ParamsLiteralSetsAnIDAndImportsDBID(t *testing.T) {
+ fields := map[string]string{}
+ for _, w := range v7Writes {
+ fields[w.query+"Params"] = w.field
+ }
+
+ found := map[string]int{}
+ for _, path := range productionGoFiles(t) {
+ fset := token.NewFileSet()
+ file, err := parser.ParseFile(fset, path, nil, 0)
+ if err != nil {
+ t.Fatalf("parse %s: %v", path, err)
+ }
+
+ dbAliases, importsDBID := relevantImports(t, path, file)
+ ast.Inspect(file, func(node ast.Node) bool {
+ literal, ok := node.(*ast.CompositeLit)
+ if !ok {
+ return true
+ }
+ selector, ok := literal.Type.(*ast.SelectorExpr)
+ if !ok {
+ return true
+ }
+ pkg, ok := selector.X.(*ast.Ident)
+ if !ok || !dbAliases[pkg.Name] {
+ return true
+ }
+ field, tracked := fields[selector.Sel.Name]
+ if !tracked {
+ return true
+ }
+
+ found[selector.Sel.Name]++
+ if !compositeLiteralSetsField(literal, field) {
+ position := fset.Position(literal.Pos())
+ t.Errorf("%s:%d: %s literal does not set %s; mint it with dbid.NewV7()",
+ path, position.Line, selector.Sel.Name, field)
+ }
+ if !importsDBID {
+ position := fset.Position(literal.Pos())
+ t.Errorf("%s:%d: %s literal is in a file that does not import %s; add the import and call dbid.NewV7()",
+ path, position.Line, selector.Sel.Name, dbidImportPath)
+ }
+ return true
+ })
+ }
+
+ for typ := range fields {
+ if found[typ] == 0 {
+ t.Errorf("no production call site found for %s — was the query removed or renamed?", typ)
+ }
+ }
+}
+
+func relevantImports(t *testing.T, path string, file *ast.File) (map[string]bool, bool) {
+ t.Helper()
+
+ dbAliases := map[string]bool{}
+ importsDBID := false
+ for _, spec := range file.Imports {
+ importPath, err := strconv.Unquote(spec.Path.Value)
+ if err != nil {
+ t.Fatalf("parse import in %s: %v", path, err)
+ }
+ switch importPath {
+ case dbImportPath:
+ name := "db"
+ if spec.Name != nil {
+ name = spec.Name.Name
+ }
+ dbAliases[name] = true
+ case dbidImportPath:
+ importsDBID = true
+ }
+ }
+ return dbAliases, importsDBID
+}
+
+func compositeLiteralSetsField(literal *ast.CompositeLit, field string) bool {
+ for _, element := range literal.Elts {
+ pair, ok := element.(*ast.KeyValueExpr)
+ if !ok {
+ continue
+ }
+ name, ok := pair.Key.(*ast.Ident)
+ if ok && name.Name == field {
+ return true
+ }
+ }
+ return false
+}
+
+// queryBlock returns the text of one named sqlc query, from its `-- name:`
+// comment to the start of the next one.
+func queryBlock(t *testing.T, file, query string) string {
+ t.Helper()
+
+ path := filepath.Join(serverDir(t), "pkg", "db", "queries", file)
+ src, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ text := string(src)
+ marks := queryNameRE.FindAllStringSubmatchIndex(text, -1)
+ for i, m := range marks {
+ if text[m[2]:m[3]] != query {
+ continue
+ }
+ end := len(text)
+ if i+1 < len(marks) {
+ end = marks[i+1][0]
+ }
+ return text[m[0]:end]
+ }
+ t.Fatalf("query %s not found in %s", query, file)
+ return ""
+}
+
+func productionGoFiles(t *testing.T) []string {
+ t.Helper()
+
+ var out []string
+ root := serverDir(t)
+ err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ // generated/ holds the sqlc output, which never constructs its own
+ // params structs, and testdata/ is not compiled.
+ if d.Name() == "generated" || d.Name() == "testdata" || d.Name() == "node_modules" {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, "_test.go") {
+ out = append(out, path)
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(out) == 0 {
+ t.Fatalf("no production Go files found under %s", root)
+ }
+ return out
+}
+
+func serverDir(t *testing.T) string {
+ t.Helper()
+
+ _, self, _, ok := runtime.Caller(0)
+ if !ok {
+ t.Fatal("resolve this test's path")
+ }
+ // .../server/pkg/dbid/writes_test.go -> .../server
+ return filepath.Dir(filepath.Dir(filepath.Dir(self)))
+}
+
+func hasColumn(list, name string) bool {
+ for _, part := range strings.Split(list, ",") {
+ if strings.TrimSpace(part) == name {
+ return true
+ }
+ }
+ return false
+}