fix: rollback transaction on panic in RunInTx#703
Open
masashi-toda-ene wants to merge 1 commit into
Open
Conversation
If the function passed to RunInTx panics, the transaction was never rolled back, leaving row-level locks held until the connection is GC'd or the server's lock-wait timeout fires — which can cause deadlocks under concurrent load. Add a deferred recover() that rolls back the transaction and re-panics. If both the original panic value and the rollback itself are errors, they are joined via errors.Join so the caller can inspect both. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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.
Problem
RunInTxcurrently does not handle panics inside the provided function.If
fnpanics, the transaction is never rolled back, leaving row-levellocks held until the connection is GC'd or the server's
innodb_lock_wait_timeoutfires — which can cause deadlocks underconcurrent load.
Fix
Add a deferred
recover()that rolls back the transaction and re-panics,matching the behaviour of other Go ORMs (GORM, go-pg, gobuffalo/pop).
error: join both errors viaerrors.Join(consistent with the existing error-path style) and re-panicerror(e.g. a string): rollback error is intentionally discarded — changing the panic value type would break callers whorecover()and type-assert the valueTests
Three new tests added to
stdlib_test.gousing a minimal mockdriver.Connector:TestRunInTxPanicPropagatesTestRunInTxPanicErrorJoinsRollbackErrerrors.Iswhen rollback also failsTestRunInTxPanicNonErrorPreservesValueReferences