test(im): close the lifecycle test database and keep its name unique (#3433)
* test(im): give each lifecycle test its own sqlite database
newLifecycleTestDB derived its in-memory SQLite DSN from
time.Now().UnixNano() alone. Two tests whose helper calls land in the
same wall-clock tick get the same DSN, and since the database is
cache=shared, the second test's CREATE TABLE collides with the
first's ("table im_channels already exists"). A shared database also
lets one test observe rows created by another.
Every other in-memory test database in this repo names itself from
t.Name() instead (tenant_api_key_test.go, memory/service_test.go,
and others); this helper was the only one still using the wall clock.
Switch to the same convention: t.Name() is unique per test function,
which is all that's needed here since none of the lifecycle tests
call the helper from subtests.
Added TestNewLifecycleTestDBIsolatesConcurrentTests, which runs the
seed and the isolation check as actual parallel subtests rather than
sequentially, closer to the real collision scenario than a plain
sequential pair. Confirmed it fails with the old DSN scheme (fixed
name, forcing the collision) and passes with the fix; ran the full
package 8 times as separate `go test` invocations, matching how the
race is actually triggered, with -race and no failures.
Fixes #3198
Signed-off-by: Ankit Jha <jhaankit373@gmail.com>
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(im): close the lifecycle test database and keep its name unique
Review on #3415: switching the DSN to t.Name() fixed the collision between
tests started in the same tick but broke repeated runs. t.Name() is stable
across -count iterations in one process, and newLifecycleTestDB never closed
the sql.DB, so a shared-cache in-memory database outlived the iteration that
created it and the next CREATE TABLE failed with "table im_channels already
exists".
Reproduced with the reported command:
go test ./internal/im -run '^TestNewLifecycleTestDBIsolatesConcurrentTests$' -count=2
Two changes, both needed:
- t.Cleanup closes the sql.DB immediately after opening, so the database is
released with the test. Registered before the caller's own cleanups, which
therefore still run first and can use the database while stopping a service.
- A process-wide sequence number in the name, so a single test calling the
helper twice gets two databases; those overlap before any cleanup runs, so
closing alone is not sufficient.
Added the repeated-run check that was asked for, plus one asserting the
connection is actually closed. Verified each half is load-bearing: dropping the
cleanup fails TestNewLifecycleTestDBClosesItsConnection, dropping the sequence
fails TestNewLifecycleTestDBIsUsableTwiceInOneProcess. Package is green at
-count=1 and -count=3 under -race.
---------
Signed-off-by: Ankit Jha <jhaankit373@gmail.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
main
parent
68e21b6e74
commit
110134f187
|
|
@ -43,12 +43,32 @@ func (c *lifecycleFactoryCounters) factory() AdapterFactory {
|
|||
}
|
||||
}
|
||||
|
||||
// lifecycleDBSeq makes each database name unique within the process, so a name
|
||||
// can never be reused: t.Name() alone repeats under -count>1, and the wall
|
||||
// clock collides between tests started in the same tick.
|
||||
var lifecycleDBSeq atomic.Int64
|
||||
|
||||
func newLifecycleTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:im-lifecycle-%d?mode=memory&cache=shared", time.Now().UnixNano())), &gorm.Config{})
|
||||
name := fmt.Sprintf("file:im-lifecycle-%s-%d?mode=memory&cache=shared", t.Name(), lifecycleDBSeq.Add(1))
|
||||
db, err := gorm.Open(sqlite.Open(name), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
// A shared-cache in-memory database lives as long as one connection to it
|
||||
// remains open, so without this the schema outlives the test that created
|
||||
// it. Registered before the caller's own cleanups, which therefore run
|
||||
// first and can still use the database while shutting a service down.
|
||||
t.Cleanup(func() {
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
t.Errorf("resolve sql.DB for cleanup: %v", err)
|
||||
return
|
||||
}
|
||||
if err := sqlDB.Close(); err != nil {
|
||||
t.Errorf("close sqlite: %v", err)
|
||||
}
|
||||
})
|
||||
// IMChannel's production schema uses PostgreSQL's uuid_generate_v4()
|
||||
// default, which SQLite cannot parse. Keep an equivalent minimal table for
|
||||
// lifecycle tests; IDs are assigned explicitly below.
|
||||
|
|
@ -74,6 +94,63 @@ func newLifecycleTestDB(t *testing.T) *gorm.DB {
|
|||
return db
|
||||
}
|
||||
|
||||
// Regression test for a shared in-memory database between two lifecycle
|
||||
// tests: run the subtests in parallel, the closest a test can get to the
|
||||
// original wall-clock collision, and confirm the second's table is empty
|
||||
// rather than seeing the first's row or a "table already exists" error.
|
||||
func TestNewLifecycleTestDBIsolatesConcurrentTests(t *testing.T) {
|
||||
t.Run("seeds a channel", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
createLifecycleChannel(t, newLifecycleTestDB(t), "marker", "agent-1")
|
||||
})
|
||||
t.Run("starts from an empty table", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
db := newLifecycleTestDB(t)
|
||||
var count int64
|
||||
if err := db.Table("im_channels").Count(&count).Error; err != nil {
|
||||
t.Fatalf("count im_channels: %v", err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("im_channels has %d rows, want a fresh database isolated from other tests", count)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Repeated -count runs reuse one process, so a database name derived only from
|
||||
// t.Name() is handed out twice. Calling the helper twice here is what a second
|
||||
// -count iteration does, and it caught the regression that closing the
|
||||
// connection and adding a per-call sequence number fixes (review on #3415).
|
||||
func TestNewLifecycleTestDBIsUsableTwiceInOneProcess(t *testing.T) {
|
||||
first := newLifecycleTestDB(t)
|
||||
createLifecycleChannel(t, first, "marker", "agent-1")
|
||||
|
||||
second := newLifecycleTestDB(t)
|
||||
var count int64
|
||||
if err := second.Table("im_channels").Count(&count).Error; err != nil {
|
||||
t.Fatalf("count im_channels on the second database: %v", err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("second database has %d rows, want a fresh one rather than the first's", count)
|
||||
}
|
||||
}
|
||||
|
||||
// The cleanup has to release the connection, or the shared-cache database
|
||||
// outlives the test and the next call to the helper reconnects to it.
|
||||
func TestNewLifecycleTestDBClosesItsConnection(t *testing.T) {
|
||||
var leaked *gorm.DB
|
||||
t.Run("inner", func(t *testing.T) {
|
||||
leaked = newLifecycleTestDB(t)
|
||||
})
|
||||
|
||||
sqlDB, err := leaked.DB()
|
||||
if err != nil {
|
||||
t.Fatalf("resolve sql.DB: %v", err)
|
||||
}
|
||||
if err := sqlDB.Ping(); err == nil {
|
||||
t.Fatal("connection still open after the subtest finished, want it closed by t.Cleanup")
|
||||
}
|
||||
}
|
||||
|
||||
func newLifecycleTestService(db *gorm.DB, redisClient *redis.Client, instanceID string) *Service {
|
||||
return &Service{
|
||||
db: db,
|
||||
|
|
|
|||
Loading…
Reference in New Issue