Chat messages could only be linked to AI Gateway records per chat, so nothing recorded which model response produced a given message. fantasy surfaces the response ID the model endpoint returns on the stream's finish part: the Anthropic Messages ID as the part ID, and the OpenAI Responses ID in provider metadata. chatd now stores that ID in the existing `chat_messages.provider_response_id` column for assistant steps and the compaction summary row. No migration and no aibridge changes. What the stored value is depends on the route: | Route | Stored value | Joins to | |---|---|---| | Anthropic Messages API through the AI Gateway (Anthropic and Bedrock Claude) | The gateway's interception ID. The gateway replaces the message ID because injected MCP tool loops can fold several upstream messages into one response. | `aibridge_interceptions.id` | | OpenAI Responses API through the AI Gateway | The upstream `resp_` ID, passed through unchanged | `provider_response_id` on `aibridge_token_usages`, `aibridge_user_prompts`, and `aibridge_tool_usages` | | Direct to the provider | The provider's own ID (`msg_`, `resp_`) | Nothing in the gateway tables | To resolve messages to interceptions, then read usage by `interception_id`: ```sql SELECT cm.id AS chat_message_id, i.id AS interception_id FROM chat_messages cm JOIN aibridge_interceptions i ON i.id::text = cm.provider_response_id UNION SELECT cm.id, tu.interception_id FROM chat_messages cm JOIN aibridge_token_usages tu ON tu.provider_response_id = cm.provider_response_id; ``` Not covered, and left NULL: - Partial rows saved on interrupt, because fantasy only reports the ID in the finish part. - Chat Completions providers (OpenAI-compatible, OpenRouter, Vercel), because fantasy does not surface the chunk ID there. - User, tool, and system rows, and all existing messages. <details> <summary>Delivery record</summary> - `96a896c` replaced the earlier interception-link design (`59fa58f`, `7f93c18`, `9d04ccd`) in place: the aibridge hook, the `aibridge_interception_id` column and migration, the message part buffer tracking, and the `ARCHITECTURE.md` section are all removed. The net diff against the base touches only `coderd/database` and `coderd/x/chatd`. - Local validation on `96a896c`: pre-commit hook green (gen, fmt, lint, build); `go test ./coderd/x/chatd/... ./coderd/database/` green. Red-green: removing the finish-part capture fails both new end-to-end tests (`TestActiveServer_PersistsAnthropicMessageID`, `TestOpenAIResponsesPersistsProviderResponseID`). CI on `96a896c`: green. - Remote UAT round 2 on `96a896c` ([chat](https://dogfood.cdr.dev/agents/75353a23-cd9e-4c81-a99f-472c78f3ba32)): **FAIL** against this description's earlier claim that every stored ID joins the gateway usage rows directly. Anthropic rows routed through the gateway stored the interception ID, so 0 of 18 joined usage rows directly, while every checked Anthropic row equaled `aibridge_interceptions.id`. Both OpenAI Responses rows joined directly. Interrupted partial rows, Chat Completions rows, and user and tool rows were NULL, with no empty strings or duplicate IDs. Multi-step turns, manual compaction, edit and regenerate, a provider switch, and a retried 429 behaved as expected. One unattributed anomaly: a single duplicate user row after interrupt and continue, which did not reproduce and is outside this diff. - `2e889ba` corrects the doc comment on `PersistedStep.ProviderResponseID` and this description to match; behavior is unchanged. Pre-commit hook and CI green. - Remote UAT round 3 on `2e889ba` against the corrected contract ([same chat](https://dogfood.cdr.dev/agents/75353a23-cd9e-4c81-a99f-472c78f3ba32)): **PASS**. The query above resolved all 40 stamped rows to exactly one interception from the same chat, with none unresolved. Reading usage by interception recovered every usage row for 38 of them; the last two resolved but their usage rows were not counted. Fresh Anthropic and Responses calls, a seven-step tool turn, manual compaction, an Anthropic to Responses to Anthropic switch in one chat, and a UI reload behaved as described, and the NULL cases held. Three interrupt and continue attempts did not reproduce the round-2 duplicate, so it stays unattributed. Not tested: gateway-injected MCP tool loops (unreachable from chatd, whose delegated requests skip the gateway's MCP proxy), direct Anthropic `msg_` IDs, Bedrock, and threshold-triggered compaction. Both rounds had a verified isolation proof and a clean dogfood audit. - Codex rounds 1 to 3 reviewed the old design. Codex round 4 on `2e889ba` ([request](https://github.com/coder/coder/pull/29763#issuecomment-5796193371), 13:58Z): no major issues ([result](https://github.com/coder/coder/pull/29763#issuecomment-5796267231), reviewed commit `2e889ba05c`). No unresolved review threads. Review passes so far: 4 of 6. - Final head `2e889ba` is the exact commit remote UAT round 3 and Codex round 4 covered; required checks green. </details> > Xum updated this PR on behalf of @ibetitsmike.
424 lines
12 KiB
Go
424 lines
12 KiB
Go
package chatd_test
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/dbtestutil"
|
|
dbpubsub "github.com/coder/coder/v2/coderd/database/pubsub"
|
|
"github.com/coder/coder/v2/coderd/x/chatd"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chattest"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/testutil"
|
|
)
|
|
|
|
func TestOpenAIResponsesNoStaleWebSearchReplay(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
const (
|
|
reasoningID = "rs_no_stale_reasoning"
|
|
webSearchID = "ws_no_stale_search"
|
|
)
|
|
var recorder responsesRequestRecorder
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
|
|
requestNumber := recorder.record(req)
|
|
switch requestNumber {
|
|
case 1:
|
|
resp := chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("search result summary")...,
|
|
)
|
|
resp.ResponseID = "resp_no_stale_first"
|
|
resp.Reasoning = &chattest.OpenAIReasoningItem{
|
|
ID: reasoningID,
|
|
Summary: "checked provider-side search state",
|
|
EncryptedContent: "encrypted-no-stale",
|
|
}
|
|
resp.WebSearch = &chattest.OpenAIWebSearchCall{
|
|
ID: webSearchID,
|
|
Query: "coder changelog",
|
|
}
|
|
return resp
|
|
default:
|
|
resp := chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("follow-up answer")...,
|
|
)
|
|
resp.ResponseID = "resp_no_stale_second"
|
|
return resp
|
|
}
|
|
})
|
|
|
|
user, org, _ := seedChatDependenciesWithProvider(t, db, "openai", openAIURL)
|
|
model := insertOpenAIResponsesModelConfig(t, db, user.ID, false, true)
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newOpenAIResponsesTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: uniqueResponsesTitle(t, "no-stale"),
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("search for the latest Coder docs"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatProcessed(ctx, t, db, chat.ID, server)
|
|
requireResponsesChatWaiting(ctx, t, db, chat.ID)
|
|
require.Len(t, recorder.all(), 1)
|
|
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: model.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("summarize the result without searching again"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatProcessed(ctx, t, db, chat.ID, server)
|
|
requireResponsesChatWaiting(ctx, t, db, chat.ID)
|
|
|
|
requests := recorder.all()
|
|
require.Len(t, requests, 2)
|
|
followup := requests[1]
|
|
require.NotNil(t, followup.Store)
|
|
require.False(t, *followup.Store)
|
|
require.NotEmpty(t, followup.Prompt)
|
|
requireNoResponsesProviderItemReplay(t, followup.Prompt, reasoningID, webSearchID)
|
|
require.NotContains(t, promptItemTypes(followup.Prompt), "web_search_call")
|
|
}
|
|
|
|
func TestOpenAIResponsesPersistsProviderResponseID(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
resp := chattest.OpenAIStreamingResponse(chattest.OpenAITextChunks("answer")...)
|
|
resp.ResponseID = "resp_persisted"
|
|
return resp
|
|
})
|
|
|
|
user, org, _ := seedChatDependenciesWithProvider(t, db, "openai", openAIURL)
|
|
model := insertOpenAIResponsesModelConfig(t, db, user.ID, false, false)
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newOpenAIResponsesTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: uniqueResponsesTitle(t, "response-id"),
|
|
ModelConfigID: model.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("hello"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatProcessed(ctx, t, db, chat.ID, server)
|
|
requireResponsesChatWaiting(ctx, t, db, chat.ID)
|
|
|
|
messages, err := db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{ChatID: chat.ID})
|
|
require.NoError(t, err)
|
|
responseIDs := make(map[database.ChatMessageRole]sql.NullString)
|
|
for _, message := range messages {
|
|
responseIDs[message.Role] = message.ProviderResponseID
|
|
}
|
|
require.Equal(t, sql.NullString{String: "resp_persisted", Valid: true}, responseIDs[database.ChatMessageRoleAssistant])
|
|
require.False(t, responseIDs[database.ChatMessageRoleUser].Valid)
|
|
}
|
|
|
|
func TestOpenAIResponsesFullReplayPairsReasoningAndWebSearch(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db, ps := dbtestutil.NewDB(t)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
|
|
const (
|
|
reasoningID = "rs_full_replay_reasoning"
|
|
webSearchID = "ws_full_replay_search"
|
|
)
|
|
var recorder responsesRequestRecorder
|
|
openAIURL := chattest.NewOpenAI(t, func(req *chattest.OpenAIRequest) chattest.OpenAIResponse {
|
|
if !req.Stream {
|
|
return chattest.OpenAINonStreamingResponse("title")
|
|
}
|
|
requestNumber := recorder.record(req)
|
|
switch requestNumber {
|
|
case 1:
|
|
resp := chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("search result summary")...,
|
|
)
|
|
resp.ResponseID = "resp_full_replay_first"
|
|
resp.Reasoning = &chattest.OpenAIReasoningItem{
|
|
ID: reasoningID,
|
|
Summary: "checked provider-side search state",
|
|
EncryptedContent: "encrypted-full-replay",
|
|
}
|
|
resp.WebSearch = &chattest.OpenAIWebSearchCall{
|
|
ID: webSearchID,
|
|
Query: "coder changelog",
|
|
}
|
|
return resp
|
|
default:
|
|
resp := chattest.OpenAIStreamingResponse(
|
|
chattest.OpenAITextChunks("follow-up answer")...,
|
|
)
|
|
resp.ResponseID = "resp_full_replay_second"
|
|
return resp
|
|
}
|
|
})
|
|
|
|
user, org, _ := seedChatDependenciesWithProvider(t, db, "openai", openAIURL)
|
|
firstModel := insertOpenAIResponsesModelConfig(t, db, user.ID, true, true)
|
|
secondModel := insertOpenAIResponsesModelConfig(t, db, user.ID, true, true)
|
|
factory := chattest.NewMockAIBridgeTransport(t, openAIURL)
|
|
server := newOpenAIResponsesTestServer(t, db, ps, func(cfg *chatd.Config) {
|
|
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory)
|
|
})
|
|
|
|
chat, err := server.CreateChat(ctx, chatd.CreateOptions{
|
|
OrganizationID: org.ID,
|
|
OwnerID: user.ID,
|
|
Title: uniqueResponsesTitle(t, "full-replay"),
|
|
ModelConfigID: firstModel.ID,
|
|
InitialUserContent: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("search for the latest Coder docs"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatProcessed(ctx, t, db, chat.ID, server)
|
|
requireResponsesChatWaiting(ctx, t, db, chat.ID)
|
|
require.Len(t, recorder.all(), 1)
|
|
|
|
_, err = server.SendMessage(ctx, chatd.SendMessageOptions{
|
|
ChatID: chat.ID,
|
|
CreatedBy: user.ID,
|
|
ModelConfigID: secondModel.ID,
|
|
Content: []codersdk.ChatMessagePart{
|
|
codersdk.ChatMessageText("summarize the result without searching again"),
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
waitForChatProcessed(ctx, t, db, chat.ID, server)
|
|
requireResponsesChatWaiting(ctx, t, db, chat.ID)
|
|
|
|
requests := recorder.all()
|
|
require.Len(t, requests, 2)
|
|
followup := requests[1]
|
|
require.NotNil(t, followup.Store)
|
|
require.True(t, *followup.Store)
|
|
require.NotEmpty(t, followup.Prompt)
|
|
requirePromptItemReferenceOrder(t, followup.Prompt, reasoningID, webSearchID)
|
|
}
|
|
|
|
type recordedResponsesRequest struct {
|
|
Prompt []interface{}
|
|
Store *bool
|
|
}
|
|
|
|
type responsesRequestRecorder struct {
|
|
mu sync.Mutex
|
|
requests []recordedResponsesRequest
|
|
}
|
|
|
|
func (r *responsesRequestRecorder) record(req *chattest.OpenAIRequest) int {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
|
|
var store *bool
|
|
if req.Store != nil {
|
|
value := *req.Store
|
|
store = &value
|
|
}
|
|
r.requests = append(r.requests, recordedResponsesRequest{
|
|
Prompt: append([]interface{}(nil), req.Prompt...),
|
|
Store: store,
|
|
})
|
|
return len(r.requests)
|
|
}
|
|
|
|
func (r *responsesRequestRecorder) all() []recordedResponsesRequest {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
return append([]recordedResponsesRequest(nil), r.requests...)
|
|
}
|
|
|
|
func newOpenAIResponsesTestServer(
|
|
t *testing.T,
|
|
db database.Store,
|
|
ps dbpubsub.Pubsub,
|
|
overrides ...func(*chatd.Config),
|
|
) *chatd.Server {
|
|
t.Helper()
|
|
allOverrides := append([]func(*chatd.Config){func(cfg *chatd.Config) {
|
|
// Let CreateChat and SendMessage publish their pending status
|
|
// before wake-driven processing starts. The responses tests are
|
|
// not exercising periodic polling, and PostgreSQL can otherwise
|
|
// deliver that stale pending notification after processChat
|
|
// subscribes to control events.
|
|
cfg.PendingChatAcquireInterval = testutil.WaitLong
|
|
}}, overrides...)
|
|
return newActiveTestServer(t, db, ps, allOverrides...)
|
|
}
|
|
|
|
func insertOpenAIResponsesModelConfig(
|
|
t *testing.T,
|
|
db database.Store,
|
|
userID uuid.UUID,
|
|
store bool,
|
|
webSearchEnabled bool,
|
|
) database.ChatModelConfig {
|
|
t.Helper()
|
|
return insertChatModelConfigWithCallConfig(
|
|
t,
|
|
db,
|
|
userID,
|
|
"openai",
|
|
"gpt-4o",
|
|
codersdk.ChatModelCallConfig{
|
|
ProviderOptions: &codersdk.ChatModelProviderOptions{
|
|
OpenAI: &codersdk.ChatModelOpenAIProviderOptions{
|
|
Store: &store,
|
|
WebSearchEnabled: &webSearchEnabled,
|
|
},
|
|
},
|
|
},
|
|
)
|
|
}
|
|
|
|
func requireResponsesChatWaiting(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
db database.Store,
|
|
chatID uuid.UUID,
|
|
) {
|
|
t.Helper()
|
|
chat, err := db.GetChatByID(ctx, chatID)
|
|
require.NoError(t, err)
|
|
if chat.Status == database.ChatStatusError {
|
|
require.FailNowf(t, "chat failed", "last_error=%q", chatLastErrorMessage(chat.LastError))
|
|
}
|
|
require.Equal(t, database.ChatStatusWaiting, chat.Status)
|
|
}
|
|
|
|
func uniqueResponsesTitle(t *testing.T, prefix string) string {
|
|
t.Helper()
|
|
return fmt.Sprintf("%s-%s-%d", prefix, t.Name(), time.Now().UnixNano())
|
|
}
|
|
|
|
func promptItemTypes(prompt []interface{}) []string {
|
|
types := make([]string, 0, len(prompt))
|
|
for _, item := range prompt {
|
|
itemMap, ok := item.(map[string]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
if itemType := chattest.StringResponseField(itemMap, "type"); itemType != "" {
|
|
types = append(types, itemType)
|
|
}
|
|
}
|
|
return types
|
|
}
|
|
|
|
func requireNoResponsesProviderItemReplay(
|
|
t *testing.T,
|
|
prompt []interface{},
|
|
staleIDs ...string,
|
|
) {
|
|
t.Helper()
|
|
stale := make(map[string]struct{}, len(staleIDs))
|
|
for _, id := range staleIDs {
|
|
stale[id] = struct{}{}
|
|
}
|
|
for _, item := range prompt {
|
|
assertNoResponsesProviderItemReplay(t, item, stale)
|
|
}
|
|
}
|
|
|
|
func assertNoResponsesProviderItemReplay(
|
|
t *testing.T,
|
|
value interface{},
|
|
staleIDs map[string]struct{},
|
|
) {
|
|
t.Helper()
|
|
switch typed := value.(type) {
|
|
case map[string]interface{}:
|
|
for key, raw := range typed {
|
|
if text, ok := raw.(string); ok {
|
|
if key == "type" && text == "web_search_call" {
|
|
require.FailNow(t, "prompt replayed web_search_call provider item")
|
|
}
|
|
if key == "id" || key == "call_id" || key == "item_id" {
|
|
if _, isStale := staleIDs[text]; isStale {
|
|
require.FailNowf(t, "prompt replayed stale provider item ID",
|
|
"field %q contained stale provider ID %q", key, text)
|
|
}
|
|
if strings.HasPrefix(text, "ws_") || strings.HasPrefix(text, "rs_") {
|
|
require.FailNowf(t, "prompt replayed provider item ID",
|
|
"field %q contained provider-managed ID %q", key, text)
|
|
}
|
|
}
|
|
}
|
|
assertNoResponsesProviderItemReplay(t, raw, staleIDs)
|
|
}
|
|
case []interface{}:
|
|
for _, item := range typed {
|
|
assertNoResponsesProviderItemReplay(t, item, staleIDs)
|
|
}
|
|
}
|
|
}
|
|
|
|
func requirePromptItemReferenceOrder(
|
|
t *testing.T,
|
|
prompt []interface{},
|
|
firstID string,
|
|
secondID string,
|
|
) {
|
|
t.Helper()
|
|
firstIndex := -1
|
|
secondIndex := -1
|
|
for index, item := range prompt {
|
|
itemMap, ok := item.(map[string]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
itemID := chattest.StringResponseField(itemMap, "id")
|
|
if itemID == "" {
|
|
itemID = chattest.StringResponseField(itemMap, "item_id")
|
|
}
|
|
switch itemID {
|
|
case firstID:
|
|
firstIndex = index
|
|
case secondID:
|
|
secondIndex = index
|
|
}
|
|
}
|
|
require.NotEqual(t, -1, firstIndex, "missing first item reference")
|
|
require.NotEqual(t, -1, secondIndex, "missing second item reference")
|
|
require.Less(t, firstIndex, secondIndex)
|
|
}
|