fix(coderd): mark sub agent deletion via boolean instead of delete (#18411)

Deletion of data is uncommon in our database, so the introduction of sub agents
and the deletion of them introduced issues with foreign key assumptions, as can
be seen in coder/internal#685. We could have only addressed the specific case by
allowing cascade deletion of stats as well as handling in the stats collector,
but it's unclear how many more such edge-cases we could run into.

In this change, we mark the rows as deleted via boolean instead, and filter them
out in all relevant queries.

Fixes coder/internal#685
This commit is contained in:
Mathias Fredriksson
2025-06-19 16:32:51 +03:00
committed by GitHub
parent 68f21fa523
commit 511fd09582
13 changed files with 385 additions and 38 deletions
+6 -2
View File
@@ -358,7 +358,8 @@ BEGIN
JOIN workspace_builds ON workspace_builds.job_id = workspace_resources.job_id
WHERE workspace_builds.id = workspace_build_id
AND workspace_agents.name = NEW.name
AND workspace_agents.id != NEW.id;
AND workspace_agents.id != NEW.id
AND workspace_agents.deleted = FALSE; -- Ensure we only count non-deleted agents.
-- If there's already an agent with this name, raise an error
IF agents_with_name > 0 THEN
@@ -1916,6 +1917,7 @@ CREATE TABLE workspace_agents (
display_order integer DEFAULT 0 NOT NULL,
parent_id uuid,
api_key_scope agent_key_scope_enum DEFAULT 'all'::agent_key_scope_enum NOT NULL,
deleted boolean DEFAULT false NOT NULL,
CONSTRAINT max_logs_length CHECK ((logs_length <= 1048576)),
CONSTRAINT subsystems_not_none CHECK ((NOT ('none'::workspace_agent_subsystem = ANY (subsystems))))
);
@@ -1944,6 +1946,8 @@ COMMENT ON COLUMN workspace_agents.display_order IS 'Specifies the order in whic
COMMENT ON COLUMN workspace_agents.api_key_scope IS 'Defines the scope of the API key associated with the agent. ''all'' allows access to everything, ''no_user_data'' restricts it to exclude user data.';
COMMENT ON COLUMN workspace_agents.deleted IS 'Indicates whether or not the agent has been deleted. This is currently only applicable to sub agents.';
CREATE UNLOGGED TABLE workspace_app_audit_sessions (
agent_id uuid NOT NULL,
app_id uuid NOT NULL,
@@ -2216,7 +2220,7 @@ CREATE VIEW workspace_prebuilds AS
FROM (((workspaces w
JOIN workspace_latest_builds wlb ON ((wlb.workspace_id = w.id)))
JOIN workspace_resources wr ON ((wr.job_id = wlb.job_id)))
JOIN workspace_agents wa ON ((wa.resource_id = wr.id)))
JOIN workspace_agents wa ON (((wa.resource_id = wr.id) AND (wa.deleted = false))))
WHERE (w.owner_id = 'c42fdf75-3097-471c-8c33-fb52454d81c0'::uuid)
GROUP BY w.id
), current_presets AS (