@@ -188,11 +188,49 @@ INSERT INTO
188
188
SELECT * FROM workspace_agent_log_sourcesWHERE workspace_agent_id= ANY(@ids :: uuid [ ]);
189
189
190
190
-- If an agent hasn't connected in the last 7 days, we purge it's logs.
191
+ -- Exception: if the logs are related to the latest build, we keep those around.
191
192
-- Logs can take up a lot of space, so it's important we clean up frequently.
192
193
-- name: DeleteOldWorkspaceAgentLogs :exec
193
- DELETE FROM workspace_agent_logsWHERE agent_idIN
194
- (SELECT idFROM workspace_agentsWHERE last_connected_atIS NOT NULL
195
- AND last_connected_at< @threshold ::timestamptz );
194
+ WITH
195
+ latest_buildsAS (
196
+ SELECT
197
+ workspace_id,max (build_number)AS max_build_number
198
+ FROM
199
+ workspace_builds
200
+ GROUP BY
201
+ workspace_id
202
+ ),
203
+ old_agentsAS (
204
+ SELECT
205
+ wa .id ,wa .last_connected_at ,wb .build_number ,wb .workspace_id
206
+ FROM
207
+ workspace_agentsAS wa
208
+ JOIN
209
+ workspace_resourcesAS wr
210
+ ON
211
+ wa .resource_id = wr .id
212
+ JOIN
213
+ workspace_buildsAS wb
214
+ ON
215
+ wb .job_id = wr .job_id
216
+ LEFT JOIN
217
+ latest_builds
218
+ ON
219
+ latest_builds .workspace_id = wb .workspace_id
220
+ AND
221
+ latest_builds .max_build_number = wb .build_number
222
+ WHERE
223
+ -- Filter out the latest builds for each workspace.
224
+ latest_builds .workspace_id ISNULL
225
+ AND CASE
226
+ -- If the last time the agent connected was before @threshold
227
+ WHENwa .last_connected_at IS NOT NULL THEN
228
+ wa .last_connected_at < @threshold ::timestamptz
229
+ -- The agent never connected, and was created before @threshold
230
+ ELSEwa .created_at < @threshold ::timestamptz
231
+ END
232
+ )
233
+ DELETE FROM workspace_agent_logsWHERE agent_idIN (SELECT idFROM old_agents);
196
234
197
235
-- name: GetWorkspaceAgentsInLatestBuildByWorkspaceID :many
198
236
SELECT