Repository navigation
feat(storage): add SereneDB backend; fix SQL Server conflict-target upserts - #792
Merged
Merged
Conversation
SereneDB speaks the PostgreSQL wire protocol, so the SQL provider drives it unchanged except in two places. Rather than branch shared code, the new provider embeds sql.Provider and overrides only those two: - Migration. SereneDB reports varchar(n) as text, so GORM AutoMigrate re-issues ALTER COLUMN ... TYPE on every boot and SereneDB refuses it on an indexed column — the second startup failed. Replaced with a create-only migrator (CREATE TABLE / ADD COLUMN / CREATE INDEX), the DDL SereneDB actually supports. - Upserts with an explicit conflict target. SereneDB resolves ON CONFLICT (cols) only against an inline UNIQUE constraint, never a CREATE UNIQUE INDEX — which is what GORM emits for `uniqueIndex` and what ALTER TABLE cannot retrofit. AddAuthenticator and AddVerificationRequest now insert bare and resolve the conflict off the 23505 the index still raises, so MFA enrollment and repeat verification requests keep their race guarantees. Its MVCC is optimistic: contended writers abort with 40001 instead of blocking, so both upserts retry rather than surfacing the conflict. Not auto-mapped as an FGA store — it is a search-OLAP engine, not an OpenFGA datastore, and needs an explicit --fga-store. Verified against serenedb/serenedb 26.08.2: full storage suite passes on a fresh database and on a second run against the existing schema. Postgres, SQLite and MongoDB suites unchanged. Claude-Session: https://claude.ai/code/session_01JGxmhT63jvFwuTeujfbC45
AddAuthenticator's conflict fallback depends on the (user_id, method) index raising 23505. Without a direct assertion, a migrator that stopped creating it would make the concurrency test flaky rather than red. Claude-Session: https://claude.ai/code/session_01JGxmhT63jvFwuTeujfbC45
Reviewing the backend against the real binary found the documented ceiling was not theoretical: 20 concurrent update_profile calls for one user produced 17 failures, each leaking `ERROR: Conflict on tuple deletion! (SQLSTATE 40001)` to the API caller. The per-method retry covered only the two overridden upserts; every other write path had none. Moved the retry to a gorm.ConnPool wrapper so every autocommit statement gets it. Two consequences worth stating: - SkipDefaultTransaction is required. GORM otherwise wraps each single Create/Update in a transaction, routing all writes through BeginTx and past the retry — which is why the first attempt at this changed nothing. These schemas carry no GORM associations, so one write is one statement and that wrapper bought nothing here anyway. - Explicit Transaction() blocks are deliberately not retried: replaying one statement inside an aborted transaction is wrong, and GORM offers no hook to replay the whole block. The four cascade-delete call sites still surface 40001 under sustained same-row contention. NewProviderWithMigrate becomes NewProviderWithOptions; both hooks are nil for every other database type, so their path is unchanged. After: 20/20 succeed, 0 conflicts in the server log; at 50 concurrent the app's own rate limiter trips first and still nothing leaks. New test asserts the cascade delete stays atomic under SkipDefaultTransaction. Verified: full suite on SereneDB (946 pass), make test (SQLite), Postgres storage suite, 5x flakiness loop. Claude-Session: https://claude.ai/code/session_01JGxmhT63jvFwuTeujfbC45
# Conflicts: # Makefile # internal/storage/db/sql/provider.go # internal/storage/provider_test.go # scripts/wait-for-test-dbs.sh
SereneDB 26.11 resolves ON CONFLICT (cols) against a CREATE UNIQUE INDEX, so AddAuthenticator and AddVerificationRequest no longer need their own insert-then-update-on-23505 versions; the SQL provider's upserts run unchanged and the existing upsert/concurrent-enrollment tests pin it. Still required on 26.11.2, re-verified: - create-only migrator: varchar(n) is still reported as text and ALTER COLUMN TYPE on an indexed column still fails (42P01) on restart. - 40001 retry pool: 20 concurrent same-row updates fail 17/20 without it. Also adapts the migrator to gorm's ParseIndexes now returning a slice.
…etry Replace GORM-driven migration on SereneDB with hand-written DDL (schema.go) applied by a small versioned runner (migrate.go): - Each version runs in one transaction with the row recording it, so a failed migration leaves neither DDL nor record behind. - SereneDB has no advisory locks; concurrent boots are resolved by idempotent DDL plus the version row, retrying on 40001/23505. - Strings are declared as text, the type SereneDB actually stores, so there is nothing for a migrator to reconcile on restart. Close the remaining write-conflict gap: sql.Options.RetryTransactions replays the four cascade-delete transactions from the start on 40001. Only SereneDB sets it; every other backend keeps a single attempt. Tests: - TestSchemaDDLMatchesModels (no DB, runs in make test): DDL tables, columns, types, defaults, PKs and indexes match the GORM models. Mutation-checked: a dropped column, changed default and missing unique constraint each fail it. - Fresh install, restart no-op, upgrade, failed-version rollback and concurrent boot against a real SereneDB, each in its own database. - Concurrent cascade deletes: 5/5 pass with the retry, 5/5 fail with SQLSTATE 40001 without it.
- Migrations: treat 23505 as a concurrent-boot race only when the version is recorded afterwards; a genuine duplicate (e.g. CREATE UNIQUE INDEX over duplicate data) now fails immediately instead of after ~9.5s of retries. Tolerate the same race when creating the version table. - Retries: pool retry sleep honours ctx; jittered backoff in the pool, the migration runner and the transaction replay. - sql: close the raw pool if gorm.Open fails on the wrapped path. - Parity test: compare NOT NULL; fail loudly on index options the DDL format cannot express; live test checks uni_* constraints. - Makefile: gate SereneDB on a real SELECT 1 (wait-for-sql.sh) instead of a port probe the Docker proxy answers instantly. New test TestMigrateRealUniqueViolationFailsFast (real 23505, 2ms). Contention and concurrent-boot tests: 20/20 each.
gorm.io/driver/sqlserver builds every upsert MERGE from the primary key and ignores clause.OnConflict.Columns, so AddAuthenticator and AddVerificationRequest (keyed on unique indexes) fell through to INSERT and failed with 2601 instead of replacing the row. The SQL Server dialector now swaps in a create callback that builds the MERGE on the conflict columns; every other insert still goes to the driver. MERGE carries WITH (HOLDLOCK) so concurrent upserts of one key cannot both take NOT MATCHED: without it TestAddAuthenticatorConcurrentUpsert failed 1/3 runs with 2601; with it 30/30 across postgres, cockroachdb, mysql, mariadb, sqlite and sqlserver. The two previously known-red SQL Server tests now pass, so sqlserver joins test-all-db (14 backends, 3764 pass, 0 fail).
This was referenced Nov 20, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
SereneDB speaks the PostgreSQL wire protocol, so queries run through the existing SQL provider unchanged.
internal/storage/db/serenedbembedssql.Providerand differs in exactly two places: schema (hand-written versioned DDL instead of GORM AutoMigrate) and write conflicts (40001 retries). No other backend changes behaviour.Also fixes the two known-red SQL Server upserts (see below). Verified against
serenedb/serenedb:26.11.2(pinned asSERENEDB_IMAGEin the Makefile).1. Schema: hand-written, versioned DDL
GORM AutoMigrate cannot run on SereneDB. SereneDB reports
varchar(n)astext, so AutoMigrate sees a type difference on every boot and issues anALTER COLUMN ... TYPE, which SereneDB refuses on an indexed column. First boot works; every restart fails:Re-checked on 26.11.2: still the case.
Instead:
schema.goholds the schema as plain DDL:CREATE TABLE IF NOT EXISTS,CREATE INDEX IF NOT EXISTS, and unique keys as inline constraints named after the GORM indexes they mirror. Strings are declaredtext, the type SereneDB actually stores, so there is nothing to reconcile. ColumnDEFAULTs match the model tags. They matter because GORM leaves zero-valued defaulted fields (is_active,enabled) out of the INSERT.migrate.goapplies versions in order. Each one runs in one transaction together with its row inauthorizer_schema_migrations, so a failed migration leaves neither DDL nor record behind and the next boot retries it. SereneDB DDL is transactional (verified).schema.go: migrations are append-only, and every statement must be re-runnable. AGENTS.md notes that a new model field needs a SereneDB migration.2. Write conflicts (SQLSTATE 40001)
SereneDB's MVCC is optimistic: contended writes to one row abort with 40001 instead of blocking. Without handling, 20 concurrent
UpdateUsercalls on one user fail 17/20 (re-measured on 26.11.2).gorm.ConnPoolwrapper. This requiresSkipDefaultTransaction, otherwise GORM wraps every single write in a transaction and routes it past the pool. These schemas have no GORM associations, so one write is one statement.p.transaction()helper. All four closures only delete throughtx, so a replay is safe. It is gated bysql.Options.RetryTransactions, which only SereneDB sets: every other backend still runs each transaction exactly once.Not needed any more: upsert overrides
Earlier revisions of this PR overrode
AddAuthenticator/AddVerificationRequest, because SereneDB before 26.11 resolvedON CONFLICT (cols)only against inline constraints, never aCREATE UNIQUE INDEX. 26.11 fixed that, so the overrides are gone and the stock SQL upserts run unchanged. The existing upsert and 8-way concurrent-enrollment tests still cover them.Changes to the shared SQL provider
All opt-in; the zero
Options{}path thatsql.NewProvideruses is unchanged:NewProviderWithOptions(cfg, deps, Options{Migrate, WrapPool, SkipDefaultTransaction, RetryTransactions}).Providertype alias,DB()accessor andModels()list, for embedding.p.transaction(ctx, fn), which withRetryTransactionsoff is exactlyp.db.WithContext(ctx).Transaction(fn).Not auto-mapped as an FGA store: SereneDB is a search-OLAP engine, not an OpenFGA datastore, so it needs an explicit
--fga-store. A test guards this, alongside the cockroachdb case.Tests
Static, runs in
make test(no Docker):TestSchemaDDLMatchesModelsparses the DDL and compares it with GORM's parse of every model: tables, columns, types, defaults, primary keys, and index names, columns and uniqueness, in both directions. Mutation-checked: removing a column, changing a default, or dropping a unique constraint each fail it with a pointed message.TestSchemaDDLParityDetectsDriftandTestValidateMigrationscover the parser and the version-list rules.Against SereneDB (
TEST_DBS=serenedb), each migration test in its own fresh database:TestMigrateFreshDatabase: all versions recorded; every model table, column and index present in the live catalog;is_activedefaults to true.TestMigrateRestartIsNoop: the path that used to fail. Three restarts, data kept, no re-recorded versions.TestMigrateAppliesNewVersion: upgrade path, with rows preserved.TestMigrateFailedVersionRollsBack: a migration failing at statement 2 leaves statement 1 rolled back and the version unrecorded; the fixed migration then applies.TestMigrateConcurrentBoot: 4 instances on an empty database all come up, and the version is recorded once.TestCascadeDeleteSurvivesContention: 8 concurrent cascade deletes × 5 rounds. 5/5 pass with the transaction retry, 5/5 fail withConflict on tuple deletion! (SQLSTATE 40001)without it.Verification
make test-all-db: all 14 backends (Postgres, SereneDB, CockroachDB, MySQL, MariaDB, SQL Server, SQLite, libSQL, MongoDB, ArangoDB, ScyllaDB, Cassandra, DynamoDB, Couchbase)make test(SQLite)go vet ./...,make lint-goSQL Server upsert fix (also in this PR)
gorm.io/driver/sqlserver(latest, v1.6.4) builds every upsertMERGEfrom the primary key and ignoresclause.OnConflict.Columns. SoAddAuthenticatorandAddVerificationRequest, keyed on(user_id, method)and(email, identifier), fell through to INSERT and failed with2601instead of replacing the row. These were the two known-red SQL Server tests; both fail identically onmain.sqlServerCreate) that builds theMERGEon the conflict columns. Every other insert, including primary-keyDoNothingupserts, still goes to the driver unchanged.MERGEcarriesWITH (HOLDLOCK). Without it, two concurrent upserts of one key both takeNOT MATCHEDand the loser fails on the unique index. The newTestAddAuthenticatorConcurrentUpsertfailed 1/3 runs without the hint and passes 30/30 with it, across Postgres, CockroachDB, MySQL, MariaDB, SQLite and SQL Server.make test-all-db. AGENTS.md is updated.Review fixes (after an independent review pass)
CREATE UNIQUE INDEXover duplicate data) now fails immediately instead of after about 9.5s of retries (TestMigrateRealUniqueViolationFailsFast: real 23505, reported in 2ms). The same race is tolerated when creating the version table.ctx. Jittered backoff in the pool, the migration runner and the transaction replay (contention and concurrent-boot tests: 20/20 each).NOT NULL(mutation-checked), and fails loudly on index options the DDL format cannot express. The live test checks theuni_*constraints too.make test-serenedb/test-all-dbgate SereneDB on a realSELECT 1(wait-for-sql.sh serenedb) instead of a port probe that the Docker proxy answers instantly.sql: close the raw pool ifgorm.Openfails on the wrapped path.QueryContextreturns rows. 200 contendedUPDATE … RETURNINGstatements: 200 ok, no row errors, no lost updates.make test-serenedbis added;test-all-db,test-docker-upandtest-cleanupinclude it.Separately, and pre-existing on every backend: the service layer returns raw storage errors, so driver text can reach the GraphQL
message. Worth its own issue; not touched here.