`taskTestFixture` in `tasks_test.go` repeated `workerTestFixture` field for field, with the same seed rows, and carried its own copies of five chat setup helpers, `publishChatUpdate` and two message builders. This PR deletes the fixture and the copies and moves the 39 task, hook and turn-trace tests that built it onto `workerTestFixture` and the shared helpers. It also drops the fixture's API key row and the `apiKeyID` parameter of `userTextMessage`, which nothing read. **Why it is safe** The copies differed from the shared helpers in two ways, and both are kept: - **Clearing the recorder.** The copies cleared the recording pubsub after setup, and `interruptChat` cleared it before interrupting, so assertions on published events see only what the code under test published. `workerTestFixture.pubsub` is now that recorder (from the layer below), and the shared helpers clear it at the same points. No worker test reads the fixture recorder's events, so the extra clears do not change them. - **The deadline argument.** The task copy of `forceExecutionState` took an explicit requires-action deadline. `forceExecutionStateWithDeadline` takes it as a pointer (nil keeps the current one) for `setRequiresActionDeadline` and the one call that cleared an expired deadline. The other three callers passed an empty deadline for chats that never had one, so they call `forceExecutionState`. The rest of the move keeps the old behavior: - `startRealTaskWorker` now starts from `testOptions`, which holds the same values. It unsets the recording task starter so the worker builds its real one, as before. - No chatd code reads the fixture's API key. The synthetic gateway key is looked up by its own token name. After the change, `rg 'taskTestFixture|taskUserTextMessage|taskAssistantToolCallMessage|f\.apiKey' coderd/ enterprise/` finds nothing. **Review focus** The `clear()` placement in `helpers_test.go`. Setup helpers clear when they finish, and `interruptChat` clears before it runs. **Validation** Same commands as the layer below: the 142 top-level tests in the ten files listed there, run from `go test -c ./coderd/x/chatd/` binaries (plain and `-race`) with `-test.count=1 -test.parallel 4`. | Head | Plain | `-race` | |---|---|---| | `main` (`e289c6fe011`) | 142 passed | 142 passed, no data races | | this PR | 142 passed | 142 passed, no data races | The pre-commit hook passed. **Stack** The stack folds the task test fixture into the shared worker test fixture. 1. #30923 reuse `recordingPubsub` in the task test fixture 2. #30924 fold `taskTestFixture` into `workerTestFixture` (this PR) > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description.
158 lines
5.0 KiB
Go
158 lines
5.0 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"cdr.dev/slog/v3/sloggers/slogtest"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/x/agenthooks/dispatch"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chathooks"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatprompt"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatstate"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/testutil"
|
|
)
|
|
|
|
func TestSessionStartTrackerRetriesIncompleteDispatch(t *testing.T) {
|
|
t.Parallel()
|
|
tracker := &sessionStartTracker{}
|
|
claimed, complete, err := tracker.claim(t.Context())
|
|
require.NoError(t, err)
|
|
require.True(t, claimed)
|
|
|
|
canceled, cancel := context.WithCancel(t.Context())
|
|
cancel()
|
|
_, _, err = tracker.claim(canceled)
|
|
require.ErrorIs(t, err, context.Canceled)
|
|
complete(false)
|
|
|
|
claimed, complete, err = tracker.claim(t.Context())
|
|
require.NoError(t, err)
|
|
require.True(t, claimed)
|
|
complete(true)
|
|
claimed, _, err = tracker.claim(t.Context())
|
|
require.NoError(t, err)
|
|
require.False(t, claimed)
|
|
}
|
|
|
|
func TestSessionStartDispatchFailureFinishesGeneration(t *testing.T) {
|
|
t.Parallel()
|
|
f := newWorkerTestFixture(t)
|
|
chat := f.createRunningChat(t)
|
|
workerID := uuid.New()
|
|
runnerID := uuid.New()
|
|
chat = acquireChat(t, f, chat.ID, workerID, runnerID)
|
|
consumer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
}))
|
|
t.Cleanup(consumer.Close)
|
|
dispatcher := dispatch.New(
|
|
slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}),
|
|
consumer.Client(),
|
|
consumer.URL,
|
|
false,
|
|
"test-hook-secret-32-bytes-minimum!!",
|
|
time.Second,
|
|
"test-deployment",
|
|
"test-version",
|
|
prometheus.NewRegistry(),
|
|
)
|
|
starter := newTestTaskStarter(t, f, newTaskSideEffectRecorder())
|
|
starter.server.hooks = chathooks.NewTrigger(dispatcher)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
debugTurn := newRunnerDebugTurn(starter.opts.Logger)
|
|
defer debugTurn.Finalize(ctx)
|
|
err := starter.StartGeneration(ctx, chatWorkerTaskStartInput{
|
|
ChatID: chat.ID,
|
|
WorkerID: workerID,
|
|
RunnerID: runnerID,
|
|
HistoryVersion: chat.HistoryVersion,
|
|
GenerationAttempt: chat.GenerationAttempt,
|
|
Status: database.ChatStatusRunning,
|
|
DebugTurn: debugTurn,
|
|
SessionStart: &sessionStartTracker{},
|
|
})
|
|
require.NoError(t, err)
|
|
updated, err := f.db.GetChatByID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, database.ChatStatusError, updated.Status)
|
|
var chatErr codersdk.ChatError
|
|
require.NoError(t, json.Unmarshal(updated.LastError.RawMessage, &chatErr))
|
|
require.Equal(t, codersdk.ChatErrorKindHookDispatchFailed, chatErr.Kind)
|
|
require.Contains(t, chatErr.Message, "hook dispatch failed: session_start: http_error (dispatch ")
|
|
require.False(t, chatErr.Retryable)
|
|
}
|
|
|
|
func TestApplySessionStartResponse(t *testing.T) {
|
|
t.Parallel()
|
|
f := newWorkerTestFixture(t)
|
|
chat := f.createRunningChat(t)
|
|
workerID := uuid.New()
|
|
runnerID := uuid.New()
|
|
chat = acquireChat(t, f, chat.ID, workerID, runnerID)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
input := chatWorkerTaskStartInput{
|
|
ChatID: chat.ID,
|
|
WorkerID: workerID,
|
|
RunnerID: runnerID,
|
|
HistoryVersion: chat.HistoryVersion,
|
|
Status: database.ChatStatusRunning,
|
|
}
|
|
_, err := applySessionStartResponse(
|
|
ctx,
|
|
chatstate.NewChatMachine(f.db, f.pubsub, chat.ID),
|
|
input,
|
|
chat,
|
|
&chathooks.Result{
|
|
ModelContext: "model context",
|
|
UserMessage: "user notice",
|
|
},
|
|
)
|
|
require.NoError(t, err)
|
|
|
|
promptRows, err := f.db.GetChatMessagesForPromptByChatID(ctx, chat.ID)
|
|
require.NoError(t, err)
|
|
require.Equal(t, "model context", hookMessageTextInternal(t, promptRows[len(promptRows)-1]))
|
|
require.Equal(t, database.ChatMessageVisibilityModel, promptRows[len(promptRows)-1].Visibility)
|
|
allRows, err := f.db.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{ChatID: chat.ID})
|
|
require.NoError(t, err)
|
|
userNotice := allRows[len(allRows)-1]
|
|
require.Equal(t, database.ChatMessageRoleSystem, userNotice.Role)
|
|
require.Equal(t, database.ChatMessageVisibilityUser, userNotice.Visibility)
|
|
require.Equal(t, "user notice", hookMessageTextInternal(t, userNotice))
|
|
}
|
|
|
|
func TestApplySessionStartResponseNoOp(t *testing.T) {
|
|
t.Parallel()
|
|
f := newWorkerTestFixture(t)
|
|
chat := f.createRunningChat(t)
|
|
f.pubsub.clear()
|
|
result, err := applySessionStartResponse(
|
|
testutil.Context(t, testutil.WaitLong),
|
|
chatstate.NewChatMachine(f.db, f.pubsub, chat.ID),
|
|
chatWorkerTaskStartInput{},
|
|
chat,
|
|
nil,
|
|
)
|
|
require.NoError(t, err)
|
|
require.Equal(t, chat.SnapshotVersion, result.Chat.SnapshotVersion)
|
|
require.Empty(t, f.pubsub.published())
|
|
}
|
|
|
|
func hookMessageTextInternal(t *testing.T, message database.ChatMessage) string {
|
|
t.Helper()
|
|
parts, err := chatprompt.ParseContent(message)
|
|
require.NoError(t, err)
|
|
require.Len(t, parts, 1)
|
|
return parts[0].Text
|
|
}
|