@@ -188,11 +188,49 @@ INSERT INTO
188
188
SELECT * FROM workspace_agent_log_sources WHERE 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_logs WHERE agent_id IN
194
- (SELECT id FROM workspace_agents WHERE last_connected_at IS NOT NULL
195
- AND last_connected_at < @threshold :: timestamptz );
194
+ WITH
195
+ latest_builds AS (
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_agents AS (
204
+ SELECT
205
+ wa .id , wa .last_connected_at , wb .build_number , wb .workspace_id
206
+ FROM
207
+ workspace_agents AS wa
208
+ JOIN
209
+ workspace_resources AS wr
210
+ ON
211
+ wa .resource_id = wr .id
212
+ JOIN
213
+ workspace_builds AS 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 IS NULL
225
+ AND CASE
226
+ -- If the last time the agent connected was before @threshold
227
+ WHEN wa .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
+ ELSE wa .created_at < @threshold :: timestamptz
231
+ END
232
+ )
233
+ DELETE FROM workspace_agent_logs WHERE agent_id IN (SELECT id FROM old_agents);
196
234
197
235
-- name: GetWorkspaceAgentsInLatestBuildByWorkspaceID :many
198
236
SELECT
0 commit comments