Skip to content

Commit f751f81

Browse files
fix(coderd): fix flake in TestAPI/ModifyAutostopWithRunningWorkspace (#18932)
Fixes coder/internal#521 This happened due to a race condition present in how `AwaitWorkspaceBuildJobCompleted` works. `AwaitWorkspaceBuildJobCompleted` works by waiting until `/api/v2/workspacesbuilds/{workspacebuild}/` returns a workspace build with `.Job.CompletedAt != nil`. The issue here is that _sometimes_ the returned `codersdk.WorkspaceBuild` can contain a build from _before_ a provisioner job completed, but contain the provisioner job from _after_ it completed. Let me demonstrate: Here we query the database for `database.WorkspaceBuild`. https://github.com/coder/coder/blob/a3f64f74f794c733126ad21cd1feb0801caf67c4/coderd/coderd.go#L1409-L1415 Inside of the `workspaceBuild` route handler, we call `workspaceBuildsData` https://github.com/coder/coder/blob/a3f64f74f794c733126ad21cd1feb0801caf67c4/coderd/workspacebuilds.go#L54 This then calls `GetProvisionerJobsByIDsWithQueuePosition` https://github.com/coder/coder/blob/a3f64f74f794c733126ad21cd1feb0801caf67c4/coderd/workspacebuilds.go#L852-L856 As these two calls happen _outside of a transaction_, the state of the world can change underneath. This can result in an in-progress workspace build having a completed provisioner job attached to it.
1 parent 0d3b770 commit f751f81

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

coderd/workspaces_test.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2875,13 +2875,18 @@ func TestWorkspaceUpdateTTL(t *testing.T) {
28752875
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
28762876
defer cancel()
28772877

2878-
err := client.UpdateWorkspaceTTL(ctx, workspace.ID, codersdk.UpdateWorkspaceTTLRequest{
2879-
TTLMillis: testCase.toTTL,
2880-
})
2878+
// Re-fetch the workspace build. This is required because
2879+
// `AwaitWorkspaceBuildJobCompleted` can return stale data.
2880+
build, err := client.WorkspaceBuild(ctx, build.ID)
28812881
require.NoError(t, err)
28822882

28832883
deadlineBefore := build.Deadline
28842884

2885+
err = client.UpdateWorkspaceTTL(ctx, workspace.ID, codersdk.UpdateWorkspaceTTLRequest{
2886+
TTLMillis: testCase.toTTL,
2887+
})
2888+
require.NoError(t, err)
2889+
28852890
build, err = client.WorkspaceBuild(ctx, build.ID)
28862891
require.NoError(t, err)
28872892

0 commit comments

Comments
 (0)