Skip to content

feat(storage): add SereneDB backend; fix SQL Server conflict-target upserts - #792

Merged
lakhansamani merged 8 commits into
mainfrom
feat/serenedb
Nov 19, 2026
Merged

lakhansamani merged 8 commits into
mainfrom
feat/serenedb

Conversation

@lakhansamani

@lakhansamani lakhansamani commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

SereneDB speaks the PostgreSQL wire protocol, so queries run through the existing SQL provider unchanged. internal/storage/db/serenedb embeds sql.Provider and 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 as SERENEDB_IMAGE in the Makefile).

1. Schema: hand-written, versioned DDL

GORM AutoMigrate cannot run on SereneDB. SereneDB reports varchar(n) as text, so AutoMigrate sees a type difference on every boot and issues an ALTER COLUMN ... TYPE, which SereneDB refuses on an indexed column. First boot works; every restart fails:

ERROR: Cannot change the type of this column: an index depends on it! (SQLSTATE 42P01)

Re-checked on 26.11.2: still the case.

Instead:

  • schema.go holds 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 declared text, the type SereneDB actually stores, so there is nothing to reconcile. Column DEFAULTs match the model tags. They matter because GORM leaves zero-valued defaulted fields (is_active, enabled) out of the INSERT.
  • migrate.go applies versions in order. Each one runs in one transaction together with its row in authorizer_schema_migrations, so a failed migration leaves neither DDL nor record behind and the next boot retries it. SereneDB DDL is transactional (verified).
  • Concurrent boot: SereneDB has no advisory locks. Instances racing on an empty database get a catalog write-conflict (40001) or a duplicate version row (23505). The loser waits, re-reads the version table and retries; the DDL is idempotent, so this is safe.
  • Rules for future changes are at the top of 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 UpdateUser calls on one user fail 17/20 (re-measured on 26.11.2).

  • Autocommit statements are retried by a gorm.ConnPool wrapper. This requires SkipDefaultTransaction, 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.
  • Explicit transactions (the four cascade deletes: user, client, organization, webhook) cannot be retried statement-by-statement once aborted, so they are now replayed whole via a new p.transaction() helper. All four closures only delete through tx, so a replay is safe. It is gated by sql.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 resolved ON CONFLICT (cols) only against inline constraints, never a CREATE 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 that sql.NewProvider uses is unchanged:

  • NewProviderWithOptions(cfg, deps, Options{Migrate, WrapPool, SkipDefaultTransaction, RetryTransactions}).
  • Provider type alias, DB() accessor and Models() list, for embedding.
  • The four cascade deletes call p.transaction(ctx, fn), which with RetryTransactions off is exactly p.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):

  • TestSchemaDDLMatchesModels parses 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.
  • TestSchemaDDLParityDetectsDrift and TestValidateMigrations cover 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_active defaults 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 with Conflict on tuple deletion! (SQLSTATE 40001) without it.

Verification

Result
make test-all-db: all 14 backends (Postgres, SereneDB, CockroachDB, MySQL, MariaDB, SQL Server, SQLite, libSQL, MongoDB, ArangoDB, ScyllaDB, Cassandra, DynamoDB, Couchbase) 3764 pass, 0 fail
make test (SQLite) pass
go vet ./..., make lint-go clean

SQL Server upsert fix (also in this PR)

gorm.io/driver/sqlserver (latest, v1.6.4) builds every upsert MERGE from the primary key and ignores clause.OnConflict.Columns. So AddAuthenticator and AddVerificationRequest, keyed on (user_id, method) and (email, identifier), fell through to INSERT and failed with 2601 instead of replacing the row. These were the two known-red SQL Server tests; both fail identically on main.

  • The SQL Server dialector now swaps in a create callback (sqlServerCreate) that builds the MERGE on the conflict columns. Every other insert, including primary-key DoNothing upserts, still goes to the driver unchanged.
  • The MERGE carries WITH (HOLDLOCK). Without it, two concurrent upserts of one key both take NOT MATCHED and the loser fails on the unique index. The new TestAddAuthenticatorConcurrentUpsert failed 1/3 runs without the hint and passes 30/30 with it, across Postgres, CockroachDB, MySQL, MariaDB, SQLite and SQL Server.
  • SQL Server is no longer known-red, so it joins make test-all-db. AGENTS.md is updated.

Review fixes (after an independent review pass)

  • Migrations: a 23505 counts as a concurrent-boot race only if the version is recorded afterwards. A genuine duplicate (e.g. CREATE UNIQUE INDEX over 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.
  • Retries: the pool retry honours ctx. Jittered backoff in the pool, the migration runner and the transaction replay (contention and concurrent-boot tests: 20/20 each).
  • Parity test now also compares NOT NULL (mutation-checked), and fails loudly on index options the DDL format cannot express. The live test checks the uni_* constraints too.
  • make test-serenedb / test-all-db gate SereneDB on a real SELECT 1 (wait-for-sql.sh serenedb) instead of a port probe that the Docker proxy answers instantly.
  • sql: close the raw pool if gorm.Open fails on the wrapped path.
  • Checked, no change needed: a 40001 cannot escape the retry after QueryContext returns rows. 200 contended UPDATE … RETURNING statements: 200 ok, no row errors, no lost updates.

make test-serenedb is added; test-all-db, test-docker-up and test-cleanup include 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.

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).
@lakhansamani lakhansamani changed the title feat(storage): add SereneDB backend feat(storage): add SereneDB backend; fix SQL Server conflict-target upserts Nov 19, 2026
@lakhansamani
lakhansamani merged commit cef4e90 into main Nov 19, 2026
6 checks passed
@lakhansamani
lakhansamani deleted the feat/serenedb branch November 19, 2026 13:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant