From 9cfe27063df10de27459115bc7bc0730cfb8a718 Mon Sep 17 00:00:00 2001
From: Michael Suchacz <203725896+ibetitsmike@users.noreply.github.com>
Date: Wed, 7 Oct 2026 13:42:42 +0200
Subject: [PATCH] test(coderd): reduce chat test fixture and timer waits
(#29523)
Reduce repeated database/server fixtures and fixed timer waits in chat
tests without changing production code or assertions.
`TestTransitionMatrix_AllCombinations` shares one database and seeded
dependencies across 272 leaves, with a unique chat and recording
publisher per leaf. `TestPostChatFile` shares one authenticated client
across 20 upload leaves. `TestResolveFallbackModelConfigID` shares one
database with independently seeded model configurations. The
requires-action test closes its server after the expected state
persists; the stopped-workspace test advances a trapped Quartz
validation timer; two tool-filtering tests no longer start unused
workspace agents.
| Test | Before | After |
|---|---|---|
| `chatstate/TestTransitionMatrix_AllCombinations` (272 leaves) | 94.06s
| 16.86s |
| `coderd/TestPostChatFile` (20 leaves) | 31.23s | 0.95s |
| `chatd/TestRequiresActionChatPersistsWaitingStatusLabel` | 11.21s |
1.25s |
| `chatd/TestSubagentChatExcludesWorkspaceProvisioningTools` | 7.90s |
2.84s |
| `chatd/TestPlanModeSubagentChatExcludesAskUserQuestion` | 8.25s |
3.00s |
| `chatd/TestStoppedWorkspaceWithPersistedAgentBindingDoesNotBlockChat`
| 6.91s | 1.91s |
| `chatd/TestResolveFallbackModelConfigID` (12 leaves) | 7.58s | 0.34s |
Independent review measurements on September 18, 2026: median summed
leaf time from two runs per side in A/B/B/A order, comparing base
`0ea777a341` with head `e378f9e936`. Every run used
`-tags=testsmallbatch -count=1 -v -p 1 -parallel 8`, PostgreSQL 17, and
the same test selection per package. Other agents shared the host, so
absolute times varied. The speedups reproduced, but not the original
ratios: the matrix improved 5.58x and uploads 32.87x. Summed leaf time
excludes shared parent fixture setup and cleanup; it is not package wall
time. Median package elapsed was 19.26s to 9.76s for the full
`chatstate` package, 4.47s to 1.28s for `coderd` with only
`TestPostChatFile`, and 11.43s to 3.36s for the five targeted `chatd`
tests. Compilation time is excluded.
Investigation notes
- Transition matrix: the shared user, organization, membership,
provider, and model are not mutated by any leaf. Each leaf seeds its own
chat, messages, and queue, and copies the fixture with a new recording
publisher (`transitions_matrix_test.go:617,728,762`).
`ChatMachine.Update` still opens real transactions on the shared
database store; no outer transaction masks rollback assertions
(`chatstate/machine.go:161`, `transitions_helpers_test.go:891`). Parent
cleanup runs after every leaf.
- Requires-action: the old idle hook reached its 10s timeout because the
runner remains active while awaiting dynamic-tool results
(`testhooks.go:14`, `worker.go:114`). The test now waits for the
persisted status and label, closes and drains the server, and retains
the no-web-push assertion (`chatd_test.go:3072`).
- Stale binding: the test injects a new Quartz mock, traps the 5s
validation timer, waits for `MustRelease` to finish timer registration
and for the dial to start, then advances the clock
(`chatd_test.go:4907`). The one-dial, model-call, and
unavailable-workspace tool-result assertions remain intact.
- Tool filtering: both tests create templates but no workspace, and
their mocked model only invokes `spawn_agent` before returning text. The
removed workspace agents could not authenticate and were never used by
the tested flow; their shutdown added about 5s
(`chatd_test.go:229,384`).
- Fallback models: configurations and providers are independently
inserted. Most leaves use unique organizations; the two
default-organization cases insert distinct models, and only one inserts
a default. No leaf mutates another leaf's model or provider
(`chatd_internal_test.go:3512`).
Validation: all changed tests passed with `-count=5` and `-race
-count=2`; the full `chatstate` package passed both checks (2,350 and
940 test executions, including parents). All 272 matrix, 20 upload, and
12 fallback leaves remain present. `gofmt -l`, `git diff --check`, and
`golangci-lint run` on the three changed packages were clean. The full
`coderd` package was not run. No correctness changes were needed during
review. `ARCHITECTURE.md` was read; this test-only PR does not affect
the documented architecture, so no TODO or architecture edit is needed.
Paste me as plain text.
@@ -12633,8 +12606,6 @@ This arrived as octet-stream. t.Run("MissingOrganization", func(t *testing.T) { t.Parallel() ctx := testutil.Context(t, testutil.WaitLong) - client := newChatClient(t) - coderdtest.CreateFirstUser(t, client.Client) data := append([]byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}, make([]byte, 64)...) res, err := client.Request(ctx, http.MethodPost, "/api/v2/chats/files", bytes.NewReader(data), func(r *http.Request) { @@ -12651,8 +12622,6 @@ This arrived as octet-stream. t.Run("InvalidOrganization", func(t *testing.T) { t.Parallel() ctx := testutil.Context(t, testutil.WaitLong) - client := newChatClient(t) - coderdtest.CreateFirstUser(t, client.Client) data := append([]byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}, make([]byte, 64)...) res, err := client.Request(ctx, http.MethodPost, "/api/v2/chats/files?organization=not-a-uuid", bytes.NewReader(data), func(r *http.Request) { @@ -12668,8 +12637,6 @@ This arrived as octet-stream. t.Run("WrongOrganization", func(t *testing.T) { t.Parallel() ctx := testutil.Context(t, testutil.WaitLong) - client := newChatClient(t) - coderdtest.CreateFirstUser(t, client.Client) data := append([]byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}, make([]byte, 64)...) _, err := client.UploadChatFile(ctx, uuid.New(), "image/png", "test.png", bytes.NewReader(data)) @@ -12685,9 +12652,6 @@ This arrived as octet-stream. t.Run("Unauthenticated", func(t *testing.T) { t.Parallel() ctx := testutil.Context(t, testutil.WaitLong) - client := newChatClient(t) - firstUser := coderdtest.CreateFirstUser(t, client.Client) - unauthed := codersdk.NewExperimentalClient(codersdk.New(client.URL)) data := append([]byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}, make([]byte, 64)...) _, err := unauthed.UploadChatFile(ctx, firstUser.OrganizationID, "image/png", "test.png", bytes.NewReader(data)) @@ -12698,8 +12662,6 @@ This arrived as octet-stream. t.Parallel() ctx := testutil.Context(t, testutil.WaitLong) - client := newChatClient(t) - firstUser := coderdtest.CreateFirstUser(t, client.Client) memberClientRaw, _ := coderdtest.CreateAnotherUser(t, client.Client, firstUser.OrganizationID) memberClient := codersdk.NewExperimentalClient(memberClientRaw) diff --git a/coderd/x/chatd/chatd_internal_test.go b/coderd/x/chatd/chatd_internal_test.go index e116032d623..da906978072 100644 --- a/coderd/x/chatd/chatd_internal_test.go +++ b/coderd/x/chatd/chatd_internal_test.go @@ -3597,6 +3597,8 @@ func TestResolveModelConfigOrganizationScope(t *testing.T) { func TestResolveFallbackModelConfigID(t *testing.T) { t.Parallel() + db, ps := dbtestutil.NewDB(t) + newProvider := func(t *testing.T, db database.Store, enabled bool) database.AIProvider { return dbgen.AIProvider(t, db, database.AIProvider{}, func(p *database.InsertAIProviderParams) { p.Enabled = enabled @@ -3618,7 +3620,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { t.Run("EnabledLastModel", func(t *testing.T) { t.Parallel() - db, _ := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) orgID := newModelConfigOrg(t, db) @@ -3632,7 +3633,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { t.Run("ProviderDisabledLastModelFallsBackToDefault", func(t *testing.T) { t.Parallel() - db, _ := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) orgID := newModelConfigOrg(t, db) @@ -3648,7 +3648,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { t.Run("NilLastModelUsesDefault", func(t *testing.T) { t.Parallel() - db, _ := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) orgID := newModelConfigOrg(t, db) @@ -3662,7 +3661,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { t.Run("NonDefaultOrgWithoutLocalDefaultRejected", func(t *testing.T) { t.Parallel() - db, _ := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) otherOrgID := newModelConfigOrg(t, db) @@ -3677,7 +3675,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { t.Run("DisabledLocalDefaultRejected", func(t *testing.T) { t.Parallel() - db, _ := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) orgID := newModelConfigOrg(t, db) @@ -3702,7 +3699,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { t.Run("DisabledLocalDefaultProviderRejected", func(t *testing.T) { t.Parallel() - db, _ := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) orgID := newModelConfigOrg(t, db) @@ -3715,7 +3711,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { t.Run("ProviderDisabledDefaultRejected", func(t *testing.T) { t.Parallel() - db, _ := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) orgID := newModelConfigOrg(t, db) @@ -3729,7 +3724,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { t.Run("ExplicitEnabledModel", func(t *testing.T) { t.Parallel() - db, _ := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) orgID := newModelConfigOrg(t, db) @@ -3743,7 +3737,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { t.Run("ExplicitDefaultOrgModelRejected", func(t *testing.T) { t.Parallel() - db, _ := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) chatOrgID := newModelConfigOrg(t, db) @@ -3763,7 +3756,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { t.Run("ExplicitUnrelatedOrgModelRejected", func(t *testing.T) { t.Parallel() - db, _ := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) chatOrgID := newModelConfigOrg(t, db) @@ -3784,7 +3776,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { // preflight must still be rejected inside the daemon. t.Run("ExplicitProviderDisabledRejected", func(t *testing.T) { t.Parallel() - db, _ := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) orgID := newModelConfigOrg(t, db) @@ -3799,7 +3790,6 @@ func TestResolveFallbackModelConfigID(t *testing.T) { // inserting the chat and its initial messages. t.Run("CreateChatProviderDisabledRejected", func(t *testing.T) { t.Parallel() - db, ps := dbtestutil.NewDB(t) ctx := testutil.Context(t, testutil.WaitShort) owner := dbgen.User(t, db, database.User{}) diff --git a/coderd/x/chatd/chatd_test.go b/coderd/x/chatd/chatd_test.go index 3989fbab500..0be3fe20483 100644 --- a/coderd/x/chatd/chatd_test.go +++ b/coderd/x/chatd/chatd_test.go @@ -260,8 +260,6 @@ func TestSubagentChatExcludesWorkspaceProvisioningTools(t *testing.T) { coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID) - _ = agenttest.New(t, client.URL, agentToken) - // Track tools sent in LLM requests. The first call is for the // root chat which spawns a subagent; the second call is for the // subagent itself. @@ -417,8 +415,6 @@ func TestPlanModeSubagentChatExcludesAskUserQuestion(t *testing.T) { coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID) - _ = agenttest.New(t, client.URL, agentToken) - // Start an external MCP server whose tools should remain available to the // root plan-mode chat but stay hidden from plan-mode subagents. mcpSrv := newTestMCPServer("plan-root-mcp") @@ -3241,7 +3237,8 @@ func TestRequiresActionChatPersistsWaitingStatusLabel(t *testing.T) { got.LastTurnSummary.Valid && got.LastTurnSummary.String == "Waiting for user input" }, testutil.IntervalFast) - chatd.WaitUntilIdleForTest(server) + // A requires_action runner stays active until tool results arrive. + require.NoError(t, server.Close()) require.Equal(t, database.ChatStatusRequiresAction, fromDB.Status, "expected requires_action, got %s (last_error=%q)", @@ -5299,18 +5296,29 @@ func TestStoppedWorkspaceWithPersistedAgentBindingDoesNotBlockChat(t *testing.T) BuildNumber: 2, }).Do() + clock := quartz.NewMock(t).WithLogger(quartz.NoOpLogger) + validationTrap := clock.Trap().NewTimer("chatd", "dial-validation-delay") + defer validationTrap.Close() + dialStarted := make(chan struct{}) var dialCalls atomic.Int32 factory := chattest.NewMockAIBridgeTransport(t, openAIURL) _ = newActiveTestServer(t, db, ps, func(cfg *chatd.Config) { + cfg.Clock = clock cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(factory) cfg.AgentConn = func(ctx context.Context, agentID uuid.UUID) (workspacesdk.AgentConn, func(), error) { dialCalls.Add(1) require.Equal(t, dbAgent.ID, agentID) + close(dialStarted) <-ctx.Done() return nil, nil, ctx.Err() } }) + validationTimer := validationTrap.MustWait(ctx) + validationTimer.MustRelease(ctx) + testutil.TryReceive(ctx, t, dialStarted) + advanceMockClockBy(ctx, t, clock, validationTimer.Duration) + var chatResult database.Chat require.Eventually(t, func() bool { got, getErr := db.GetChatByID(ctx, chat.ID) diff --git a/coderd/x/chatd/chatstate/transitions_matrix_test.go b/coderd/x/chatd/chatstate/transitions_matrix_test.go index dfa939f94d4..d6e0766b62d 100644 --- a/coderd/x/chatd/chatstate/transitions_matrix_test.go +++ b/coderd/x/chatd/chatstate/transitions_matrix_test.go @@ -533,10 +533,9 @@ func remainingBodiesExcluding(bodies []string, exclude int) []string { // runPositiveCase seeds the chat, runs the transition, and asserts the // post-state plus case-specific effects. -func runPositiveCase(t *testing.T, spec transitionCaseSpec) { +func runPositiveCase(t *testing.T, f *testFixture, spec transitionCaseSpec) { t.Helper() require.NotNil(t, spec.apply, "case %s missing apply", spec.subtestName()) - f := newTestFixture(t) ctx := testutil.Context(t, testutil.WaitShort) seeder := spec.seed @@ -571,9 +570,8 @@ func runPositiveCase(t *testing.T, spec transitionCaseSpec) { // runDisallowedCase seeds the chat, runs the transition with default // inputs, and asserts that the chatstate package surfaces the right // sentinel error and rolled the snapshot bump back. -func runDisallowedCase(t *testing.T, tr chatstate.Transition, from chatstate.ExecutionState) { +func runDisallowedCase(t *testing.T, f *testFixture, tr chatstate.Transition, from chatstate.ExecutionState) { t.Helper() - f := newTestFixture(t) ctx := testutil.Context(t, testutil.WaitShort) seeded := seedState(t, f, from) if seeded.exists { @@ -628,6 +626,8 @@ func runDisallowedCase(t *testing.T, tr chatstate.Transition, from chatstate.Exe func TestTransitionMatrix_AllCombinations(t *testing.T) { t.Parallel() + // Each case owns its chat and publisher; dependencies are read-only. + fixture := newTestFixture(t) cases := matrixCases() // Detect duplicate full keys and duplicate subtest names. The @@ -737,7 +737,9 @@ func TestTransitionMatrix_AllCombinations(t *testing.T) { actualPositive[tc.key()] = struct{}{} mu.Unlock() } - runPositiveCase(t, tc) + f := *fixture + f.Pub = newRecordingPubsub() + runPositiveCase(t, &f, tc) }) } }) @@ -769,7 +771,9 @@ func TestTransitionMatrix_AllCombinations(t *testing.T) { mu.Lock() actualDisallowed[disallowedCaseKey{transition: tr, from: from}] = struct{}{} mu.Unlock() - runDisallowedCase(t, tr, from) + f := *fixture + f.Pub = newRecordingPubsub() + runDisallowedCase(t, &f, tr, from) }) } })