fix(im): isolate user and thread session mappings (#5067)

This commit is contained in:
jacentsao authored and GitHub committed 2026-11-16 11:48:24 +08:00
1 parent 9d2ffd63bd
commit a124732dbf
9 files changed
+385 -4

No files matched your search

@@ -0,0 +1,127 @@
package database
import (
"bytes"
"database/sql"
"os"
"path/filepath"
"testing"
sqlitemigrate "github.com/golang-migrate/migrate/v4/database/sqlite3"
"github.com/stretchr/testify/require"
)
func TestSQLiteMigrationsSeparateIMSessionModes(t *testing.T) {
root := sqliteRepoRoot(t)
for _, upgrade := range []bool{false, true} {
name := "fresh"
if upgrade {
name = "upgrade"
}
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "im.db")
opts := MigrationOptions{SQLiteDBPath: path}
if upgrade {
chdirAndRestore(t, copySQLiteMigrationsThrough(t, root, 52))
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
}
db := openSQLiteDB(t, path)
if upgrade {
insertIMMapping(t, db, "legacy", "alice", "", "agent-1", false)
}
chdirAndRestore(t, root)
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
if upgrade {
var id string
row := db.QueryRow("SELECT session_id FROM im_channel_sessions WHERE id = 'legacy'")
require.NoError(t, row.Scan(&id))
require.Equal(t, "session-legacy", id, "upgrade must preserve existing mappings")
} else {
insertIMMapping(t, db, "legacy", "alice", "", "agent-1", false)
}
assertIMMappingConstraints(t, db)
})
}
}
// The fixture exercises the partial indexes independently of the session
// resolver. These fields have no foreign keys other than session_id on the
// real schema, so seed the backing session before inserting each mapping.
func insertIMMapping(t *testing.T, db *sql.DB, id, user, thread, agent string, deleted bool) {
t.Helper()
_, err := db.Exec("INSERT INTO sessions (id, tenant_id) VALUES (?, 1)", "session-"+id)
require.NoError(t, err)
var deletedAt any
if deleted {
deletedAt = "2026-01-01 00:00:00"
}
_, err = db.Exec(`INSERT INTO im_channel_sessions
(id, platform, user_id, chat_id, session_id, tenant_id, agent_id, thread_id, deleted_at)
VALUES (?, 'feishu', ?, 'group', ?, 1, ?, ?, ?)`, id, user, "session-"+id, agent, thread, deletedAt)
require.NoError(t, err)
}
func assertIMMappingConstraints(t *testing.T, db *sql.DB) {
t.Helper()
insertIMMapping(t, db, "topic-1", "alice", "thread-1", "agent-1", false)
insertIMMapping(t, db, "topic-2", "alice", "thread-2", "agent-1", false)
insertIMMapping(t, db, "agent-user", "alice", "", "agent-2", false)
insertIMMapping(t, db, "agent-thread", "alice", "thread-1", "agent-2", false)
insertIMMapping(t, db, "deleted-user", "alice", "", "agent-1", true)
insertIMMapping(t, db, "deleted-thread", "alice", "thread-1", "agent-1", true)
// Duplicates within one mode are still rejected, including a different
// creator trying to insert another mapping for an existing shared thread.
for _, tc := range []struct{ user, thread string }{{"alice", ""}, {"bob", "thread-1"}} {
_, err := db.Exec(`INSERT INTO im_channel_sessions
(id, platform, user_id, chat_id, session_id, tenant_id, agent_id, thread_id)
VALUES ('duplicate', 'feishu', ?, 'group', 'session-legacy', 1, 'agent-1', ?)`, tc.user, tc.thread)
require.ErrorContains(t, err, "UNIQUE constraint failed")
}
}
func TestSQLiteIMSessionModeRollbackPreservesData(t *testing.T) {
root := sqliteRepoRoot(t)
for _, conflicting := range []bool{false, true} {
name := "compatible"
if conflicting {
name = "multiple threads"
}
t.Run(name, func(t *testing.T) {
chdirAndRestore(t, root)
path := filepath.Join(t.TempDir(), "rollback.db")
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: path}))
db := openSQLiteDB(t, path)
insertIMMapping(t, db, "legacy", "alice", "", "agent-1", false)
if conflicting {
insertIMMapping(t, db, "thread", "alice", "topic", "agent-1", false)
}
down, err := os.ReadFile(filepath.Join(root, "migrations/sqlite/000053_im_session_mode_indexes.down.sql"))
require.NoError(t, err)
driver, err := sqlitemigrate.WithInstance(db, &sqlitemigrate.Config{})
require.NoError(t, err)
err = driver.Run(bytes.NewReader(down))
if conflicting {
require.ErrorContains(t, err, "UNIQUE constraint failed")
// A failed down must leave the new indexes and all rows intact.
insertIMMapping(t, db, "another-thread", "alice", "other-topic", "agent-1", false)
var live int
row := db.QueryRow("SELECT count(*) FROM im_channel_sessions WHERE deleted_at IS NULL")
require.NoError(t, row.Scan(&live))
require.Equal(t, 3, live)
} else {
require.NoError(t, err)
assertIMMappingConstraintsAfterReupgrade(t, db, root)
}
})
}
}
func assertIMMappingConstraintsAfterReupgrade(t *testing.T, db *sql.DB, root string) {
t.Helper()
up, err := os.ReadFile(filepath.Join(root, "migrations/sqlite/000053_im_session_mode_indexes.up.sql"))
require.NoError(t, err)
driver, err := sqlitemigrate.WithInstance(db, &sqlitemigrate.Config{})
require.NoError(t, err)
require.NoError(t, driver.Run(bytes.NewReader(up)))
assertIMMappingConstraints(t, db)
}
@@ -0,0 +1,83 @@
package database
import (
"database/sql"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestPostgresIMSessionModeIndexes(t *testing.T) {
dsn := os.Getenv("WEKNORA_MIGRATION_TEST_POSTGRES_DSN")
if dsn == "" {
t.Skip("set WEKNORA_MIGRATION_TEST_POSTGRES_DSN to run PostgreSQL migration tests")
}
db, err := sql.Open("postgres", dsn)
require.NoError(t, err)
t.Cleanup(func() { _ = db.Close() })
tx, err := db.Begin()
require.NoError(t, err)
t.Cleanup(func() { _ = tx.Rollback() })
// Temporary tables shadow any real tables. Roll back the whole fixture so
// this test neither needs ParadeDB nor changes existing application data.
_, err = tx.Exec(`CREATE TEMP TABLE im_channel_sessions (
id TEXT PRIMARY KEY, platform TEXT NOT NULL, user_id TEXT NOT NULL,
chat_id TEXT NOT NULL, tenant_id BIGINT NOT NULL, agent_id TEXT DEFAULT '',
thread_id TEXT NOT NULL DEFAULT '', deleted_at TIMESTAMPTZ
)`)
require.NoError(t, err)
root := sqliteRepoRoot(t)
run := func(file string) error {
script, err := os.ReadFile(filepath.Join(root, "migrations", "versioned", file))
require.NoError(t, err)
_, err = tx.Exec(string(script))
return err
}
// Seed both old indexes before executing migration 38, so DROP INDEX
// resolves to the temp schema even on a database with application tables.
_, err = tx.Exec(`CREATE INDEX idx_channel_lookup ON im_channel_sessions (user_id);
CREATE INDEX idx_channel_thread_lookup ON im_channel_sessions (thread_id)`)
require.NoError(t, err)
require.NoError(t, run("000038_im_session_agent_id.up.sql"))
_, err = tx.Exec(`INSERT INTO im_channel_sessions VALUES
('legacy', 'feishu', 'alice', 'group', 1, 'agent-1', '', NULL)`)
require.NoError(t, err)
require.NoError(t, run("000137_im_session_mode_indexes.up.sql"))
_, err = tx.Exec(`INSERT INTO im_channel_sessions VALUES
('topic-1', 'feishu', 'alice', 'group', 1, 'agent-1', 'thread-1', NULL),
('topic-2', 'feishu', 'alice', 'group', 1, 'agent-1', 'thread-2', NULL),
('agent-user', 'feishu', 'alice', 'group', 1, 'agent-2', '', NULL),
('agent-thread', 'feishu', 'alice', 'group', 1, 'agent-2', 'thread-1', NULL),
('deleted-user', 'feishu', 'alice', 'group', 1, 'agent-1', '', now()),
('deleted-thread', 'feishu', 'alice', 'group', 1, 'agent-1', 'thread-1', now())`)
require.NoError(t, err)
for _, tc := range []struct{ user, thread, index string }{
{"alice", "", "idx_channel_lookup"},
{"bob", "thread-1", "idx_channel_thread_lookup"},
} {
_, err = tx.Exec("SAVEPOINT duplicate_mapping")
require.NoError(t, err)
_, err = tx.Exec(`INSERT INTO im_channel_sessions VALUES
('duplicate', 'feishu', $1, 'group', 1, 'agent-1', $2, NULL)`, tc.user, tc.thread)
require.ErrorContains(t, err, tc.index)
_, err = tx.Exec("ROLLBACK TO SAVEPOINT duplicate_mapping")
require.NoError(t, err)
}
_, err = tx.Exec("SAVEPOINT incompatible_down")
require.NoError(t, err)
require.ErrorContains(t, run("000137_im_session_mode_indexes.down.sql"), "idx_channel_lookup")
_, err = tx.Exec("ROLLBACK TO SAVEPOINT incompatible_down")
require.NoError(t, err)
var count int
require.NoError(t, tx.QueryRow("SELECT count(*) FROM im_channel_sessions").Scan(&count))
require.Equal(t, 7, count, "failed rollback must preserve every mapping")
// With compatible data, down and up both work and preserve the old row.
_, err = tx.Exec("DELETE FROM im_channel_sessions WHERE id != 'legacy'")
require.NoError(t, err)
require.NoError(t, run("000137_im_session_mode_indexes.down.sql"))
require.NoError(t, run("000137_im_session_mode_indexes.up.sql"))
require.NoError(t, tx.QueryRow("SELECT count(*) FROM im_channel_sessions WHERE id = 'legacy'").Scan(&count))
require.Equal(t, 1, count)
}
@@ -89,7 +89,7 @@ var versionedSQLiteColumns = map[string][]string{
}, // 000028
}
const expectedSQLiteMigrationVersion = 52
const expectedSQLiteMigrationVersion = 53
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
+7 -3
View File
@@ -2317,7 +2317,7 @@ func imInitialSessionTitle(msg *IncomingMessage, identityTitle func(*IncomingMes
}
// resolveUserSession finds or creates a ChannelSession keyed by (platform, user_id, chat_id, tenant_id, agent_id).
// This is the original session resolution strategy.
// Only mappings with an empty thread_id belong to user mode.
//
// Invariant: a cache miss creates a brand-new session — we never attach a second
// mapping to an existing session. The session-list source filter (repository
@@ -2325,7 +2325,9 @@ func imInitialSessionTitle(msg *IncomingMessage, identityTitle func(*IncomingMes
// re-maps an existing session, that JOIN needs a one-row-per-session guard.
func (s *Service) resolveUserSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string) (*ChannelSession, error) {
var cs ChannelSession
result := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND agent_id = ? AND deleted_at IS NULL",
result := s.db.Where(
"platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? "+
"AND agent_id = ? AND thread_id = '' AND deleted_at IS NULL",
string(msg.Platform), msg.UserID, msg.ChatID, tenantID, agentID).
First(&cs)
@@ -2369,7 +2371,9 @@ func (s *Service) resolveUserSession(ctx context.Context, msg *IncomingMessage,
logger.Warnf(ctx, "[IM] Failed to clean up orphaned session %s: %v", createdSession.ID, delErr)
}
var existing ChannelSession
if findErr := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND agent_id = ? AND deleted_at IS NULL",
if findErr := s.db.Where(
"platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? "+
"AND agent_id = ? AND thread_id = '' AND deleted_at IS NULL",
string(msg.Platform), msg.UserID, msg.ChatID, tenantID, agentID).
First(&existing).Error; findErr != nil {
return nil, fmt.Errorf("create channel session: %w (lookup fallback: %v)", err, findErr)
+129
View File
@@ -0,0 +1,129 @@
package im
import (
"context"
"path/filepath"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/golang-migrate/migrate/v4"
sqlitemigrate "github.com/golang-migrate/migrate/v4/database/sqlite3"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type resolutionSessionService struct {
interfaces.SessionService
db *gorm.DB
afterCreate func()
}
func (s *resolutionSessionService) CreateSession(ctx context.Context, session *types.Session) (*types.Session, error) {
if err := s.db.WithContext(ctx).Create(session).Error; err != nil {
return nil, err
}
if hook := s.afterCreate; hook != nil {
s.afterCreate = nil
hook()
}
return session, nil
}
// Use the shipped migrations: AutoMigrate does not install the partial unique
// indexes that determine whether these resolutions succeed in production.
func newResolutionService(t *testing.T) *Service {
t.Helper()
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "sessions.db")), &gorm.Config{})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
driver, err := sqlitemigrate.WithInstance(sqlDB, &sqlitemigrate.Config{})
require.NoError(t, err)
root, err := filepath.Abs(filepath.Join("..", "..", "migrations", "sqlite"))
require.NoError(t, err)
m, err := migrate.NewWithDatabaseInstance("file://"+root, "sqlite3", driver)
require.NoError(t, err)
t.Cleanup(func() { _, _ = m.Close() })
require.NoError(t, m.Up())
return &Service{db: db, sessionService: &resolutionSessionService{db: db}}
}
func resolveTestMessage(t *testing.T, s *Service, user, thread, agent, mode string) *ChannelSession {
t.Helper()
cs, err := s.resolveSession(context.Background(), &IncomingMessage{
Platform: PlatformFeishu, UserID: user, ChatID: "group", ThreadID: thread, Content: "hello",
}, 1, agent, "channel", mode)
require.NoError(t, err)
return cs
}
func TestSessionResolutionSeparatesThreadsForTheSameUser(t *testing.T) {
s := newResolutionService(t)
first := resolveTestMessage(t, s, "alice", "topic-1", "agent", "thread")
second := resolveTestMessage(t, s, "alice", "topic-2", "agent", "thread")
require.NotEqual(t, first.SessionID, second.SessionID)
require.Equal(t, first.SessionID, resolveTestMessage(t, s, "alice", "topic-1", "agent", "thread").SessionID)
require.Equal(t, first.SessionID, resolveTestMessage(t, s, "bob", "topic-1", "agent", "thread").SessionID)
}
func TestSessionResolutionKeepsModesSeparate(t *testing.T) {
for _, firstMode := range []string{"user", "thread"} {
t.Run(firstMode+" first", func(t *testing.T) {
s := newResolutionService(t)
resolveTestMessage(t, s, "alice", "topic", "agent", firstMode)
user := resolveTestMessage(t, s, "alice", "topic", "agent", "user")
thread := resolveTestMessage(t, s, "alice", "topic", "agent", "thread")
require.Empty(t, user.ThreadID)
require.NotEqual(t, user.SessionID, thread.SessionID)
require.Equal(t, user.SessionID, resolveTestMessage(
t, s, "alice", "other-topic", "agent", "user").SessionID)
require.Equal(t, thread.SessionID, resolveTestMessage(t, s, "alice", "topic", "agent", "thread").SessionID)
// Platforms without a thread ID retain user-mode continuity.
require.Equal(t, user.SessionID, resolveTestMessage(t, s, "alice", "", "agent", "thread").SessionID)
})
}
}
func TestSessionResolutionIsolatesAgents(t *testing.T) {
for _, mode := range []string{"user", "thread"} {
t.Run(mode, func(t *testing.T) {
s := newResolutionService(t)
first := resolveTestMessage(t, s, "alice", "topic", "agent-1", mode)
second := resolveTestMessage(t, s, "alice", "topic", "agent-2", mode)
require.NotEqual(t, first.SessionID, second.SessionID)
})
}
}
func TestSessionResolutionRecoversConcurrentCreation(t *testing.T) {
for _, mode := range []string{"user", "thread"} {
t.Run(mode, func(t *testing.T) {
s := newResolutionService(t)
wantLive := int64(1)
if mode == "user" {
thread := resolveTestMessage(t, s, "alice", "old-topic", "agent", "thread")
// GORM's First orders by primary key. Make the thread the first
// candidate so an unscoped fallback cannot pass by chance.
require.NoError(t, s.db.Model(&ChannelSession{}).Where("id = ?", thread.ID).
Update("id", "000-thread").Error)
wantLive++
}
var winner *ChannelSession
// Force another request to win between the first request's miss and
// mapping insert, without depending on goroutine/SQLite lock timing.
s.sessionService.(*resolutionSessionService).afterCreate = func() {
winner = resolveTestMessage(t, s, "alice", "topic", "agent", mode)
}
got := resolveTestMessage(t, s, "alice", "topic", "agent", mode)
require.Equal(t, winner.ID, got.ID)
var liveSessions, liveMappings int64
require.NoError(t, s.db.Model(&types.Session{}).Count(&liveSessions).Error)
require.NoError(t, s.db.Model(&ChannelSession{}).Count(&liveMappings).Error)
require.Equal(t, wantLive, liveSessions, "losing creation must clean up its session")
require.Equal(t, wantLive, liveMappings)
})
}
}
@@ -0,0 +1,12 @@
-- The old constraints cannot represent some valid per-thread/per-agent data.
-- Fail atomically rather than discard mappings if such conflicts exist.
-- golang-migrate's SQLite driver wraps this migration in a transaction.
DROP INDEX IF EXISTS idx_channel_lookup;
CREATE UNIQUE INDEX idx_channel_lookup
ON im_channel_sessions (platform, user_id, chat_id, tenant_id)
WHERE deleted_at IS NULL;
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)
WHERE deleted_at IS NULL AND thread_id != '';
@@ -0,0 +1,11 @@
-- Match PostgreSQL's per-agent session isolation and keep user-mode uniqueness
-- separate from thread-mode uniqueness. Existing mappings remain untouched.
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 AND thread_id = '';
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 != '';
@@ -0,0 +1,7 @@
-- Restoring the old constraint can fail after multiple threads have been
-- created by one user. Fail rather than delete or hide conversation mappings;
-- those conflicts must be resolved explicitly before retrying the rollback.
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;
@@ -0,0 +1,8 @@
-- User and thread mappings have different identities. Applying the user
-- constraint to thread rows prevents the same user from opening a second
-- thread, and prevents user-mode and thread-mode mappings from coexisting.
-- This narrows the constraint without changing any existing mappings.
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 AND thread_id = '';