fix(auditlog): change the audit schema on one replica at a time
Description
Two tests fail intermittently in CI on unrelated pull requests. Both are reproduced and fixed at the cause. The second exposed a product defect: replicas that start together against one PostgreSQL database can deadlock while changing the audit schema.
Replicas starting together deadlock (product)
- Startup DDL in the audit store, and the model and trigram index builds, ran outside the advisory lock that the
written_atindex build takes. The legacy column rename was check-then-act. - With four stores started together on one database, 20 of 20 runs failed before the fix: 215 deadlocks, missing or invalid indexes, and seven startup errors.
- All audit schema changes now run under that one advisory lock, on the session that holds it (
BackgroundIndexBuilder.WithLock,sqlx.NewPostgreSQLConn). The lock is acquired by polling, because a blocking wait would itself deadlock. - New
TestNewSQLStoreStartsReplicasTogetherstarts several stores at once; 70 of 70 runs pass with no deadlock.
A replica that starts while another builds a large index waits for that build. It already blocked on the table lock before, so this is not a new wait.
TestNewSQLStoreReplacesSingleColumnUserPathIndex/postgresql (test)
The test ran CREATE INDEX while the store it had just started was still running CREATE INDEX CONCURRENTLY in the background (deadlock detected, SQLSTATE 40P01). The three legacy-schema tests now wait for the store's index builds first.
TestSharedSessionExpiresWhenIdle (test)
rawMCPStatus returned on the status line while the handler was still in its deferred session touch. The test then advanced the clock, and the touch read the advanced clock and re-extended the session. The helper now reads the body to EOF, which arrives only after the handler returns. Reproduced at 2 to 12 failures per 2,000 runs under load before the fix; 0 in 12,000 after.
Not looked at: the usage store has the same shape (startup DDL plus background index builds) and may need the same lock.