feat: replace InsertChatMessage with batch InsertChatMessages#23220
Merged
Conversation
6fb88ce to
05bc921
Compare
5f07b45 to
0042628
Compare
0042628 to
fdb99c1
Compare
Replace the singular InsertChatMessage query with InsertChatMessages that uses PostgreSQL's unnest() for batch inserts. This reduces the number of round-trips to the database when inserting multiple messages in a single transaction (e.g., chat creation with system+user messages, persisting assistant+tool messages, and context compression summaries). The new query: - Uses unnest() arrays for all parameters following the existing codebase pattern (e.g., InsertWorkspaceAgentStats). - Preserves the IS DISTINCT FROM optimization in the CTE that updates chats.last_model_config_id. - Uses NULLIF for UUID columns to properly handle NULL foreign keys. - Uses NULLIF(..., 0) for nullable numeric columns (tokens, cost, runtime_ms) to preserve NULL semantics used by cost reporting. - Uses text[] for content with a ::jsonb cast so pq.Array serializes correctly. - Returns all inserted rows. A chatMessage struct and appendChatMessage helper simplify building the batch params at each call site with named fields.
fdb99c1 to
df8ad47
Compare
johnstcn
approved these changes
Mar 18, 2026
Member
johnstcn
left a comment
There was a problem hiding this comment.
Coulple of non-blocking comments.
Comment on lines
4064
to
+4085
| for i := 0; i < 2; i++ { | ||
| message, err := db.InsertChatMessage(dbauthz.AsSystemRestricted(ctx), database.InsertChatMessageParams{ | ||
| ChatID: chat.ID, | ||
| ModelConfigID: uuid.NullUUID{UUID: modelConfig.ID, Valid: true}, | ||
| Role: "assistant", | ||
| Visibility: database.ChatMessageVisibilityBoth, | ||
| InputTokens: sql.NullInt64{Int64: 100, Valid: true}, | ||
| OutputTokens: sql.NullInt64{Int64: 50, Valid: true}, | ||
| TotalCostMicros: sql.NullInt64{Int64: 500, Valid: true}, | ||
| }) | ||
| require.NoError(t, err) | ||
| results, err := db.InsertChatMessages(dbauthz.AsSystemRestricted(ctx), database.InsertChatMessagesParams{ | ||
| ChatID: chat.ID, | ||
| CreatedBy: []uuid.UUID{uuid.Nil}, | ||
| ModelConfigID: []uuid.UUID{modelConfig.ID}, | ||
| Role: []database.ChatMessageRole{"assistant"}, | ||
| Content: []string{"null"}, | ||
| ContentVersion: []int16{0}, | ||
| Visibility: []database.ChatMessageVisibility{database.ChatMessageVisibilityBoth}, | ||
| InputTokens: []int64{100}, | ||
| OutputTokens: []int64{50}, | ||
| TotalTokens: []int64{0}, | ||
| ReasoningTokens: []int64{0}, | ||
| CacheCreationTokens: []int64{0}, | ||
| CacheReadTokens: []int64{0}, | ||
| ContextLimit: []int64{0}, | ||
| Compressed: []bool{false}, | ||
| TotalCostMicros: []int64{500}, | ||
| RuntimeMs: []int64{0}, | ||
| }) | ||
| require.NoError(t, err) | ||
| message := results[0] |
Member
There was a problem hiding this comment.
Should actually exercise the batch logic here instead of looping
| RawMessage: json.RawMessage(fmt.Sprintf("%q", content)), | ||
| Valid: true, | ||
| }, | ||
| _, err := store.InsertChatMessages(ctx, database.InsertChatMessagesParams{ |
Member
There was a problem hiding this comment.
should test with multiple messages
Comment on lines
+233
to
+234
| unnest(@role::chat_message_role[]), | ||
| unnest(@content::text[])::jsonb, |
| // represent NULL — the SQL uses NULLIF to convert zero UUIDs to NULL. | ||
| // For nullable int64 fields, use 0 to represent NULL — the SQL uses | ||
| // NULLIF to convert zeros to NULL. | ||
| type chatMessage struct { |
Member
There was a problem hiding this comment.
nit: builder pattern would be nice here for nullable/optional fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Replaces the singular
InsertChatMessagequery withInsertChatMessagesthat uses PostgreSQL'sunnest()for batch inserts. This reduces the number of database round-trips when inserting multiple messages in a single transaction.Changes
InsertChatMessages :manyquery usingunnest()arrays following the existing codebase pattern (e.g.,InsertWorkspaceAgentStats). Preserves the CTE that updateschats.last_model_config_idusing the last non-null model config from the batch. UsesNULLIFfor UUID columns to handle NULL foreign keys.querier.go,dbauthz.go,dbmetrics/querymetrics.go,dbmock/dbmock.go, andqueries.sql.goto use the new batch signature ([]ChatMessagereturn type, array params).appendChatMessagefunction simplifies building batch params at each call site.Builds on top of #23213.