c578fdbad6
Three bugs fixed: 1. Session cross-contamination (#1066): resolveUserSession and resolveThreadSession looked up ChannelSession by (platform, user_id, chat_id, tenant_id) without agent_id. When the same user talked to two bots bound to different agents under the same tenant, they shared a session — mixing knowledge base context. Add agent_id to all four WHERE clauses and update the DB unique indexes to match. 2. Swapped parameters in resolveThreadSession: the SQL expected (chat_id, thread_id) but Go args passed (threadID, msg.ChatID). 3. Orphaned ChannelSession crash (#1046): deleting a session from the WeKnora UI soft-deletes it (GORM), but the ChannelSession row survives because soft-delete doesn't trigger SQL ON DELETE CASCADE. Subsequent IM messages hit "record not found" on GetSession and the bot becomes permanently unresponsive. Now detect this case, recycle the stale mapping, and transparently create a fresh session.
20 lines
980 B
SQL
20 lines
980 B
SQL
-- Migration: 000038_im_session_agent_id
|
|
-- Description: Add agent_id to IM channel session unique indexes to isolate sessions per agent.
|
|
-- Fixes: GitHub #1066 (cross-agent session contamination)
|
|
DO $$ BEGIN RAISE NOTICE '[Migration 000038] Adding agent_id to IM channel session indexes'; END $$;
|
|
|
|
-- 1. User-mode lookup: include agent_id so the same user talking to
|
|
-- different agents gets separate sessions.
|
|
DROP INDEX IF EXISTS idx_channel_lookup;
|
|
CREATE UNIQUE INDEX idx_channel_lookup
|
|
ON im_channel_sessions (platform, user_id, chat_id, tenant_id, agent_id)
|
|
WHERE deleted_at IS NULL;
|
|
|
|
-- 2. Thread-mode lookup: same fix for thread-based sessions.
|
|
DROP INDEX IF EXISTS idx_channel_thread_lookup;
|
|
CREATE UNIQUE INDEX idx_channel_thread_lookup
|
|
ON im_channel_sessions (platform, chat_id, thread_id, tenant_id, agent_id)
|
|
WHERE deleted_at IS NULL AND thread_id != '';
|
|
|
|
DO $$ BEGIN RAISE NOTICE '[Migration 000038] IM session agent_id indexes updated'; END $$;
|