From 7f6c4780e2f4fab3893318552557ce82c4f7dc16 Mon Sep 17 00:00:00 2001 From: indifferentketchup Date: Sun, 31 May 2026 00:46:41 +0000 Subject: [PATCH] fix(coder): converge agent_sessions.session_id FK to SET NULL (P1.5-b follow-up) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The P1.5-b re-key block (cb1846c) re-adds session_id_fkey as ON DELETE SET NULL, but the whole block is guarded on chat_id_fkey's absence. A DB already re-keyed to (chat_id, agent) while session_id_fkey was still ON DELETE CASCADE never re-enters that block, so applySchema leaves it at 'c' forever — diverging from the schema's stated intent, from worktree_id (already SET NULL), and from the v2.6.3 changelog's own claim that session_id is informational SET NULL. Add a standalone confdeltype-guarded block (mirroring the session_worktrees defang) that flips session_id_fkey CASCADE -> SET NULL independently of the re-key gate. Idempotent: fires only while the FK is still 'c' — a no-op on a fresh deploy (already 'n' from the re-key block) and on every re-run. The live DB was converged by hand with the identical statements; \d agent_sessions now shows session_id ... ON DELETE SET NULL. Co-Authored-By: Claude Opus 4.8 (1M context) --- apps/coder/src/schema.sql | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/apps/coder/src/schema.sql b/apps/coder/src/schema.sql index ffa5621..adf7c93 100644 --- a/apps/coder/src/schema.sql +++ b/apps/coder/src/schema.sql @@ -205,6 +205,27 @@ DO $$ BEGIN END IF; END $$; +-- P1.5-b follow-up: converge agent_sessions.session_id FK CASCADE → SET NULL. +-- The re-key block above re-adds session_id_fkey as SET NULL, but it is guarded on +-- chat_id_fkey's ABSENCE — so a DB already re-keyed to (chat_id, agent) while +-- session_id_fkey was still ON DELETE CASCADE never re-enters that block and stays +-- 'c'. This standalone guard flips it to SET NULL ('n'), matching worktree_id. +-- Idempotent (mirrors the session_worktrees defang's confdeltype check): only fires +-- while the FK is still CASCADE — a no-op on a fresh deploy (already 'n' from the +-- re-key block) and on every re-run thereafter. +DO $$ BEGIN + IF EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conname = 'agent_sessions_session_id_fkey' + AND confdeltype = 'c' + ) THEN + ALTER TABLE agent_sessions ALTER COLUMN session_id DROP NOT NULL; + ALTER TABLE agent_sessions DROP CONSTRAINT agent_sessions_session_id_fkey; + ALTER TABLE agent_sessions ADD CONSTRAINT agent_sessions_session_id_fkey + FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE SET NULL; + END IF; +END $$; + -- v2.6: attribution for DiffPanel badges (Phase 1 UX reads this). ALTER TABLE pending_changes ADD COLUMN IF NOT EXISTS agent TEXT;