Files
coder/coderd/x/chatd/provider_switch_sanitize_internal_test.go
T
Garrett Delfosse c12355d6e5 fix(coderd/x/chatd): carry unanswered user messages through compaction verbatim (#28645)
Fixes
[CODAGT-737](https://linear.app/codercom/issue/CODAGT-737/compaction-can-treat-the-last-user-message-as-an-assistant-message)

## Problem

Auto-compaction can trigger on a turn whose last history message is a
fresh, unanswered **user** message. Two things go wrong:

1. The summary instruction is appended as another user message.
Providers that merge consecutive same-role messages (verified against
fantasy's Anthropic conversion) fuse it with the user's message, and the
summarizer misattributes the user's instruction as assistant intent.
2. After compaction the original user row falls outside the prompt
window, so the instruction survives only through summary fidelity.

## Fix

Carry unanswered trailing user messages through compaction verbatim
instead of summarizing them. All logic lives in `chatd`; `chatloop` is
unchanged apart from prompt wording.

- **Prepare** (`generation_preparer.go`): `pendingUserSegmentStart`
locates the trailing user rows on the persisted rows, before
provider-switch sanitization (which can drop the assistant row
separating them from an already-answered message). Head and tail are
converted separately so the summarizer input excludes the tail exactly.
Falls back to summarizing everything when no usable segment exists.
- **Commit** (`buildCompactionMessages`): replays the tail after the
boundary trio as uncompressed, model-only user rows. The existing prompt
window query includes them; no SQL, UI, or turn-guard changes. Replay
rows carry no usage, so compaction cannot immediately re-fire.
- **Prompt** (`chatloop/compaction.go`): the summary prefix no longer
claims the assistant "was actively working", which is false in this
case. The summarizer prompt is unchanged.
- `ARCHITECTURE.md` compaction section updated.

## Testing

`go test ./coderd/x/chatd/...` green. New:
`TestBuildCompactionMessages_ReplaysPendingUserMessages`,
`TestPendingUserSegmentStart`,
`TestPendingUserSegmentConversionEquivalence`,
`TestPendingUserSegmentDerivedBeforeProviderSwitchSanitization`,
`TestDecisionGeneratesAfterCompactionWithReplayedPendingUser`.

<details>
<summary>Root-cause repro</summary>

Replaying the reported scenario through fantasy's Anthropic provider
against a capture server:

```
=== fantasy prompt (roles as chatd builds them) ===
[2] role=user      "You'll hit compaction now, we'll need to go through some fin..."
[3] role=user      "You are performing a context compaction. Summarize the conve..."

=== wire request to Anthropic ===
[2] role=user, 2 content block(s)
    block[0]: "You'll hit compaction now, we'll need to go through some final checks..."
    block[1]: "You are performing a context compaction. Summarize the conversation so..."
```

</details>

---

🤖 This PR was generated by Coder Agents on behalf of @f0ssel.
2026-09-08 09:31:42 -04:00

291 lines
10 KiB
Go

package chatd
import (
"encoding/json"
"testing"
"github.com/google/uuid"
"github.com/sqlc-dev/pqtype"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/x/chatd/chatprompt"
"github.com/coder/coder/v2/codersdk"
)
func TestStripForeignProviderExecutedToolRows(t *testing.T) {
t.Parallel()
const (
anthropic = "anthropic"
bedrock = "bedrock"
openai = "openai"
)
anthropicCfg := uuid.New()
openAICfg := uuid.New()
unknownCfg := uuid.New()
vllmProviderID := uuid.New()
togetherProviderID := uuid.New()
vllmCfg := uuid.New()
peCall := func(id string) codersdk.ChatMessagePart {
p := codersdk.ChatMessageToolCall(id, "web_search", json.RawMessage(`{"query":"x"}`))
p.ProviderExecuted = true
return p
}
peResult := func(id string) codersdk.ChatMessagePart {
p := codersdk.ChatMessageToolResult(id, "web_search", json.RawMessage(`{"ok":true}`), false, false)
p.ProviderExecuted = true
return p
}
localCall := func(id string) codersdk.ChatMessagePart {
return codersdk.ChatMessageToolCall(id, "read_file", json.RawMessage(`{}`))
}
text := codersdk.ChatMessageText
assistantRow := func(t *testing.T, cfg uuid.UUID, parts ...codersdk.ChatMessagePart) database.ChatMessage {
t.Helper()
content, err := chatprompt.MarshalParts(parts)
require.NoError(t, err)
return database.ChatMessage{
Role: database.ChatMessageRoleAssistant,
ModelConfigID: uuid.NullUUID{UUID: cfg, Valid: cfg != uuid.Nil},
Content: content,
ContentVersion: chatprompt.ContentVersionV1,
}
}
userRow := func(t *testing.T, s string) database.ChatMessage {
t.Helper()
content, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{text(s)})
require.NoError(t, err)
return database.ChatMessage{
Role: database.ChatMessageRoleUser,
Content: content,
ContentVersion: chatprompt.ContentVersionV1,
}
}
origin := func(providerByConfig map[uuid.UUID]string) func(uuid.NullUUID) (string, bool) {
return func(id uuid.NullUUID) (string, bool) {
if !id.Valid {
return "", false
}
provider, ok := providerByConfig[id.UUID]
return provider, ok
}
}
resolver := origin(map[uuid.UUID]string{
anthropicCfg: anthropic,
openAICfg: openai,
vllmCfg: vllmProviderID.String(),
})
partsOf := func(t *testing.T, row database.ChatMessage) []codersdk.ChatMessagePart {
t.Helper()
parts, err := chatprompt.ParseContent(row)
require.NoError(t, err)
return parts
}
t.Run("same provider kept", func(t *testing.T) {
t.Parallel()
rows := []database.ChatMessage{
userRow(t, "hi"),
assistantRow(t, anthropicCfg, peCall("ws"), peResult("ws"), text("done")),
}
got, stats := stripForeignProviderExecutedToolRows(rows, anthropic, resolver)
require.Equal(t, rows, got)
require.Zero(t, stats)
})
t.Run("anthropic to bedrock drops provider blocks", func(t *testing.T) {
t.Parallel()
rows := []database.ChatMessage{
userRow(t, "hi"),
assistantRow(t, anthropicCfg, peCall("ws"), peResult("ws"), text("done")),
}
got, stats := stripForeignProviderExecutedToolRows(rows, bedrock, resolver)
require.Len(t, got, 2)
require.Equal(t, []codersdk.ChatMessagePart{text("done")}, partsOf(t, got[1]))
require.Equal(t, providerSwitchStripStats{RemovedToolCalls: 1, RemovedToolResults: 1}, stats)
})
t.Run("foreign-only row dropped", func(t *testing.T) {
t.Parallel()
rows := []database.ChatMessage{
userRow(t, "hi"),
assistantRow(t, anthropicCfg, peCall("ws")),
userRow(t, "again"),
}
got, stats := stripForeignProviderExecutedToolRows(rows, bedrock, resolver)
require.Len(t, got, 2)
require.Equal(t, database.ChatMessageRoleUser, got[0].Role)
require.Equal(t, database.ChatMessageRoleUser, got[1].Role)
require.Equal(t, providerSwitchStripStats{RemovedToolCalls: 1, DroppedMessages: 1}, stats)
})
t.Run("multi-provider keeps native strips foreign", func(t *testing.T) {
t.Parallel()
rows := []database.ChatMessage{
assistantRow(t, openAICfg, peCall("os"), peResult("os"), text("openai")),
assistantRow(t, anthropicCfg, peCall("as"), peResult("as"), text("anthropic")),
}
got, stats := stripForeignProviderExecutedToolRows(rows, anthropic, resolver)
require.Len(t, got, 2)
require.Equal(t, []codersdk.ChatMessagePart{text("openai")}, partsOf(t, got[0]))
require.Equal(t, rows[1], got[1])
require.Equal(t, providerSwitchStripStats{RemovedToolCalls: 1, RemovedToolResults: 1}, stats)
})
t.Run("non-provider-executed parts untouched", func(t *testing.T) {
t.Parallel()
rows := []database.ChatMessage{
assistantRow(t, anthropicCfg, text("hello"), localCall("local")),
}
got, stats := stripForeignProviderExecutedToolRows(rows, bedrock, resolver)
require.Equal(t, rows, got)
require.Zero(t, stats)
})
t.Run("empty target is a no-op", func(t *testing.T) {
t.Parallel()
rows := []database.ChatMessage{
assistantRow(t, anthropicCfg, peCall("ws"), peResult("ws")),
}
got, stats := stripForeignProviderExecutedToolRows(rows, "", resolver)
require.Equal(t, rows, got)
require.Zero(t, stats)
})
t.Run("unknown origin fails closed", func(t *testing.T) {
t.Parallel()
rows := []database.ChatMessage{
assistantRow(t, unknownCfg, peResult("ws"), text("done")),
}
got, stats := stripForeignProviderExecutedToolRows(rows, bedrock, resolver)
require.Len(t, got, 1)
require.Equal(t, []codersdk.ChatMessagePart{text("done")}, partsOf(t, got[0]))
require.Equal(t, providerSwitchStripStats{RemovedToolResults: 1}, stats)
})
t.Run("unparsable foreign row kept unchanged", func(t *testing.T) {
t.Parallel()
rows := []database.ChatMessage{{
Role: database.ChatMessageRoleAssistant,
ModelConfigID: uuid.NullUUID{UUID: anthropicCfg, Valid: true},
Content: pqtype.NullRawMessage{RawMessage: []byte("{not json"), Valid: true},
ContentVersion: chatprompt.ContentVersionV1,
}}
got, stats := stripForeignProviderExecutedToolRows(rows, bedrock, resolver)
require.Equal(t, rows, got)
require.Zero(t, stats)
})
t.Run("same type different instance drops provider blocks", func(t *testing.T) {
t.Parallel()
rows := []database.ChatMessage{
userRow(t, "hi"),
assistantRow(t, vllmCfg, peCall("ws"), peResult("ws"), text("done")),
}
got, stats := stripForeignProviderExecutedToolRows(rows, togetherProviderID.String(), resolver)
require.Len(t, got, 2)
require.Equal(t, []codersdk.ChatMessagePart{text("done")}, partsOf(t, got[1]))
require.Equal(t, providerSwitchStripStats{RemovedToolCalls: 1, RemovedToolResults: 1}, stats)
})
t.Run("same instance keeps provider blocks", func(t *testing.T) {
t.Parallel()
rows := []database.ChatMessage{
userRow(t, "hi"),
assistantRow(t, vllmCfg, peCall("ws"), peResult("ws"), text("done")),
}
got, stats := stripForeignProviderExecutedToolRows(rows, vllmProviderID.String(), resolver)
require.Equal(t, rows, got)
require.Zero(t, stats)
})
}
func TestModelConfigProviderIdentity(t *testing.T) {
t.Parallel()
providerID := uuid.New()
t.Run("AIProviderID valid returns provider UUID", func(t *testing.T) {
t.Parallel()
cfg := database.ChatModelConfig{
AIProviderID: uuid.NullUUID{UUID: providerID, Valid: true},
}
got := modelConfigProviderIdentity(cfg, "openai-compat")
require.Equal(t, providerID.String(), got)
})
t.Run("AIProviderID invalid falls back to normalized type", func(t *testing.T) {
t.Parallel()
cfg := database.ChatModelConfig{
AIProviderID: uuid.NullUUID{},
}
got := modelConfigProviderIdentity(cfg, "anthropic")
require.Equal(t, "anthropic", got)
})
t.Run("same type different provider IDs are distinguished", func(t *testing.T) {
t.Parallel()
otherProviderID := uuid.New()
cfgA := database.ChatModelConfig{
AIProviderID: uuid.NullUUID{UUID: providerID, Valid: true},
}
cfgB := database.ChatModelConfig{
AIProviderID: uuid.NullUUID{UUID: otherProviderID, Valid: true},
}
require.NotEqual(t,
modelConfigProviderIdentity(cfgA, "openai-compat"),
modelConfigProviderIdentity(cfgB, "openai-compat"),
)
})
}
func TestPendingUserSegmentDerivedBeforeProviderSwitchSanitization(t *testing.T) {
t.Parallel()
foreignCfg := uuid.New()
peCall := codersdk.ChatMessageToolCall("ws", "web_search", json.RawMessage(`{"query":"x"}`))
peCall.ProviderExecuted = true
assistantContent, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{peCall})
require.NoError(t, err)
userContent := func(s string) pqtype.NullRawMessage {
content, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{codersdk.ChatMessageText(s)})
require.NoError(t, err)
return content
}
rows := []database.ChatMessage{
{Role: database.ChatMessageRoleUser, Content: userContent("answered question"), ContentVersion: chatprompt.ContentVersionV1},
{Role: database.ChatMessageRoleAssistant, ModelConfigID: uuid.NullUUID{UUID: foreignCfg, Valid: true}, Content: assistantContent, ContentVersion: chatprompt.ContentVersionV1},
{Role: database.ChatMessageRoleUser, Content: userContent("pending"), ContentVersion: chatprompt.ContentVersionV1},
}
origin := func(id uuid.NullUUID) (string, bool) {
return "openai", id.Valid
}
// Segment first: only the truly unanswered tail is pending, and the
// foreign assistant row counts as preceding assistant context even
// though sanitization is about to drop it.
start := pendingUserSegmentStart(rows)
require.Equal(t, 2, start)
// The sanitizer drops the emptied foreign assistant row from the
// head; the answered user row stays in the head regardless, and the
// segment derived above is unaffected.
head, stats := stripForeignProviderExecutedToolRows(rows[:start], "anthropic", origin)
require.Equal(t, 1, stats.DroppedMessages)
require.Len(t, head, 1)
require.Equal(t, database.ChatMessageRoleUser, head[0].Role)
// Deriving the segment after sanitization would find no assistant
// row at all and therefore no pending segment.
sanitizedAll, _ := stripForeignProviderExecutedToolRows(rows, "anthropic", origin)
require.Equal(t, len(sanitizedAll), pendingUserSegmentStart(sanitizedAll))
}