Skip to content

Make schema installation idempotent - #433

Open
SajawalSajjad786 wants to merge 1 commit into
hangfire-postgres:masterfrom
SajawalSajjad786:fix/idempotent-schema-install
Open

SajawalSajjad786 wants to merge 1 commit into
hangfire-postgres:masterfrom
SajawalSajjad786:fix/idempotent-schema-install

Conversation

@SajawalSajjad786

@SajawalSajjad786 SajawalSajjad786 commented Dec 1, 2026 •

Copy link
Copy Markdown

Fixes #425.

Problem

PostgreSqlObjectsInstaller.Install walks Install.v3.sql → Install.v23.sql, skipping any script whose version is already recorded in the schema table. Two things make that fragile:

1. The migration scripts are not replayable. If the recorded version ever lags behind the objects that are actually present, the installer re-runs a script whose bare DDL collides with what is already there. Install.v4.sql is the one in the report:

42701: column "updatecount" of relation "lock" already exists

It fails on lock rather than counter precisely because v8 later drops counter.updatecount, so the first ALTER TABLE of v4 succeeds and the second one collides.

2. The version bump could silently record nothing. The trailing statement was

UPDATE "schema" SET "version" = @Version WHERE "version" = @PreviousVersion

where @PreviousVersion came from a counter in the installer loop, not from the database. When the stored version was out of sync, that matched zero rows — the script's DDL was committed while the version stayed put, so every subsequent startup ran the very same script again. With EnableResilientStartup (1.21) each failed attempt now also costs the full backoff chain (~31 s at the defaults) before repeating, so a restart sits in that loop instead of completing startup.

Changes

PostgreSqlObjectsInstaller: record the new version unconditionally, replacing the conditional UPDATE with

DELETE FROM "<schema>"."schema" WHERE "version" < @Version;
INSERT INTO "<schema>"."schema"("version") VALUES (@Version) ON CONFLICT DO NOTHING;

A script only ever executes when no version greater than or equal to its own is recorded — both VersionAlreadyApplied and the version-already-applied guard inside every script enforce that — so recording it unconditionally always moves the schema forward. It also collapses a stale multi-row schema table back to a single row. previousVersion is no longer needed and has been removed.

Scripts made replayable:

Script Change
v3 ON CONFLICT DO NOTHING on the seed version row
v4 ADD COLUMN IF NOT EXISTS (×10)
v7 ADD COLUMN IF NOT EXISTS acquired
v8 DROP COLUMN IF EXISTS updatecount
v15 CREATE INDEX IF NOT EXISTS (×4)
v18 CREATE TABLE IF NOT EXISTS aggregatedcounter
v20 WHERE "invocationdata"::text = '' instead of = ''

The v20 change surfaced only after the others: once those columns are jsonb, the pre-conversion UPDATE ... WHERE "invocationdata" = '' raises 22P02: invalid input syntax for type json. The cast is a no-op while the column is still text and cannot match anything once it is jsonb.

The ALTER COLUMN ... TYPE scripts (v5, v9–v12, v19) are left untouched — they are naturally idempotent, and the new tests confirm a replay converges on the same column types.

Tests

Four new facts in PostgreSqlInstallerFacts:

  • InstallingSchemaTwiceKeepsVersionAndShouldNotThrowAnException
  • InstallingSchemaWithStaleVersionRowShouldNotThrowAnExceptionAndShouldUpdateVersion
  • InstallingSchemaWithoutVersionRowShouldNotThrowAnExceptionAndShouldUpdateVersion
  • InstallingSchemaWithStaleVersionRowShouldProduceTheSameObjectsAsAFreshInstall — walks the recorded version back to every value from 3 to 22 and asserts the installer recovers to 23 each time and that the resulting columns and indexes are identical to a fresh install, so a replay cannot leave a subtly different schema behind.

Three of them fail on master with the exact reported error. Full suite: 259/259 on PostgreSQL 16, and the installer facts also pass on PostgreSQL 10, confirming the new syntax stays within the floor the scripts already assume (CREATE INDEX IF NOT EXISTS and DROP INDEX IF EXISTS were in use before this change).

Not covered

The genuinely concurrent case — two processes installing simultaneously — still raises a serialization or collision error on the loser and relies on EnableResilientStartup to retry. With the version bump fixed, that retry now skips the completed migrations cleanly instead of re-running them.

Install re-ran migration scripts against objects that already existed
whenever the recorded schema version lagged behind the schema that is
actually present, failing with 42701 (column "updatecount" of relation
"lock" already exists). The trailing version update matched the loop's
expected previous version, so it silently recorded nothing when the
stored version was out of sync - the script's DDL was committed without
advancing the version, leaving every subsequent startup to run the very
same script again.

- Record the new version unconditionally. A script only runs when no
  version greater than or equal to its own is recorded, so this always
  moves the schema forward, and it collapses a stale multi-row schema
  table back to a single row.
- Make v3, v4, v7, v8, v15 and v18 replayable via IF (NOT) EXISTS.
- Cast to text in v20's pre-conversion updates so they stay valid once
  the columns have become jsonb, where comparing to '' raises 22P02.

Adds installer tests that reproduce the reported failure and assert that
a replay from every recorded version converges on the same columns and
indexes as a fresh install. Verified against PostgreSQL 16 and 10.

Fixes hangfire-postgres#425

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@SajawalSajjad786

SajawalSajjad786 commented Dec 1, 2026 •

Copy link
Copy Markdown
Author

The verification build hasn't started on this PR — no checks have been queued at all. Could a maintainer approve the workflow run when you get a chance, so the suite runs here as well as locally?

Unrelated, but worth noting while you're in that file: ci.yml filters on test/**, while the test project actually lives in tests/**, so a test-only change wouldn't trigger the build. This PR touches src/** so it matches either way.

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.

Hangfire PostgreSQL: “column updatecount of relation lock already exists” during schema installation

1 participant