hasql-pool 1.5.1.1 → 1.6.0.0
raw patch · 10 files changed
+592/−68 lines, 10 filesdep ~hasqlPVP ok
version bump matches the API change (PVP)
Dependency ranges changed: hasql
API changes (from Hackage documentation)
- Hasql.Pool: ConnectionUsageError :: ConnectionError -> UsageError
+ Hasql.Pool: ConnectionUsageError :: AcquireError -> UsageError
- Hasql.Pool: SessionUsageError :: SessionError -> UsageError
+ Hasql.Pool: SessionUsageError :: UseError -> UsageError
Files
- CHANGELOG.md +23/−1
- hasql-pool.cabal +27/−3
- src/integration-tests/Specs/Config/InitSessionSpec.hs +5/−2
- src/integration-tests/Specs/ConnectionDiscardsSpec.hs +161/−0
- src/integration-tests/Specs/UseSpec.hs +3/−3
- src/library/Hasql/Pool.hs +52/−29
- src/library/Hasql/Pool/Config/Setting.hs +6/−0
- src/library/Hasql/Pool/ConnectionDiscards.hs +206/−0
- src/library/Hasql/Pool/SessionErrorDestructors.hs +0/−30
- src/unit-tests/Main.hs +109/−0
CHANGELOG.md view
@@ -1,3 +1,26 @@+# v1.6.0.0++## Breaking++- Migrate to `hasql-2.1`. `UsageError`'s `ConnectionUsageError` now wraps `Errors.AcquireError` (was `Errors.ConnectionError`), and `SessionUsageError` now wraps `Errors.UseError` (was `Errors.SessionError`), matching hasql's merge of its connection-fatal error constructors into a single `UseError` type. Code pattern-matching into the wrapped error needs an extra step through `SessionUseError`/`ConnectionUseError` to reach what used to be there directly.++## Fixes++- A session that fails with `MissingTypesSessionError` no longer causes the connection to be discarded. The type lookup behind that error is a live catalog query which leaves no residue on the connection - nothing is negatively cached and the connection state comes back untouched - so a fresh connection would ask the same catalog and get the same answer. Referencing a type that does not exist used to cost a full teardown and reconnect per attempt.++- A session that fails with `UnexpectedColumnTypeStatementError` no longer causes the connection to be discarded. That rule was there for decoders built against an OID the catalog had since reassigned, but that case never reaches this error: the server notices the retired type first and raises `XX000`. What does reach it is the ordinary decoder mismatch - asking for `int4` where the column is `text` - which is a caller-side bug that a fresh connection reproduces identically.++- Connections are now discarded on `26000` (`invalid_sql_statement_name`) and `42P05` (`duplicate_prepared_statement`). Both mean hasql's per-connection statement cache and the server disagree about what is prepared, and since nothing evicts from that cache, the disagreement is permanent - every subsequent execution of the affected statement fails for the rest of the connection's life.++- Connections are now discarded on `25P02` (`in_failed_sql_transaction`), which means the connection is parked inside an aborted transaction where every statement fails until a rollback the pool has no opportunity to issue.++- Connections are now discarded on class `08` (`connection_exception`, including `08P01` `protocol_violation`), on `40003` (`statement_completion_unknown`), and on class `57P` (`admin_shutdown`, `crash_shutdown`, `database_dropped`, the idle-session timeouts, and the rest). Note that `57014` (`query_canceled`) is deliberately excluded - a cancelled query leaves a perfectly healthy connection.++ Codes deliberately left retaining, with the reasoning recorded in `Hasql.Pool.ConnectionDiscards`, include class `53` (`insufficient_resources` - a server-side shortage that a reconnect cannot cure, and where discarding would turn a resource crunch into a reconnect storm), `40001`/`40P01` (the canonical same-connection retry cases), `55P03`/`55006`, `58030`, and `XX001`/`XX002`.++- A session interrupted by an asynchronous exception (a caller-side `timeout`, `race`, or `killThread`) is now discarded instead of returned to the pool. Hasql finishes the connection on that path itself, so re-queuing it as before handed the next caller a spent handle - a plausible root cause of "connection pointer is NULL" reports (#38).++ As a consequence, `initSession` no longer survives such an exception - it now only survives ordinary session errors (a bad query, a constraint violation), since those are the only case that leaves the old connection in play. # v1.5.1.1 ## Fixes@@ -38,7 +61,6 @@ - Connections are handed to waiting requests in arrival order; a request no longer takes a connection while others wait (#58)- # v1.5.0.1 - Allow newer pqi.
hasql-pool.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: hasql-pool-version: 1.5.1.1+version: 1.6.0.0 category: Hasql, Database, PostgreSQL synopsis: Pool of connections for Hasql homepage: https://github.com/nikita-volkov/hasql-pool@@ -80,13 +80,13 @@ Hasql.Pool.Config.Config Hasql.Pool.Config.ReuseOrder Hasql.Pool.Config.Setting+ Hasql.Pool.ConnectionDiscards Hasql.Pool.Prelude- Hasql.Pool.SessionErrorDestructors build-depends: base >=4.11 && <5, bytestring >=0.10 && <0.14,- hasql ^>=2.0,+ hasql ^>=2.1, pqi >=1.0 && <1.2, stm >=2.5 && <3, text >=1.2 && <3,@@ -106,6 +106,7 @@ Specs.Config.AgingTimeoutSpec Specs.Config.IdlenessTimeoutSpec Specs.Config.InitSessionSpec+ Specs.ConnectionDiscardsSpec Specs.Helpers.Sessions.CountConnectionsSpec Specs.Helpers.Sessions.GetSettingSpec Specs.InterruptionSpec@@ -132,3 +133,26 @@ testcontainers-postgresql >=0.2 && <0.3, text-builder >=1 && <1.1, tuple ^>=0.3.0.2,++test-suite unit-tests+ import: base-settings+ type: exitcode-stdio-1.0+ hs-source-dirs:+ src/unit-tests+ src/library++ main-is: Main.hs+ other-modules:+ Hasql.Pool.ConnectionDiscards+ Hasql.Pool.Prelude++ build-depends:+ base >=4.11 && <5,+ bytestring >=0.10 && <0.14,+ hasql ^>=2.1,+ hspec >=2.6 && <3,+ pqi >=1.0 && <1.2,+ stm >=2.5 && <3,+ text >=1.2 && <3,+ time >=1.9 && <2,+ uuid >=1.3 && <2,
src/integration-tests/Specs/Config/InitSessionSpec.hs view
@@ -8,7 +8,7 @@ spec :: SpecWith Scripts.ScopeParams spec = do- it "Persists after exceptions thrown in session" \scopeParams -> do+ it "Does not persist after exceptions thrown in session" \scopeParams -> do Scripts.onAutotaggedPool 1 10 60 60 scopeParams \_ pool -> do varName <- Scripts.generateVarname @@ -22,9 +22,12 @@ liftIO do throwIO (userError "Intentional error for testing") + -- An asynchronous exception out of a session always spends the+ -- connection, so the pool hands out a fresh one here and the+ -- setting from before the exception is gone. res <- use pool do Sessions.getSetting varName- shouldBe res (Right (Just "1"))+ shouldBe res (Right Nothing) it "Persists after bad query" \scopeParams -> do Scripts.onAutotaggedPool 1 10 60 60 scopeParams \_ pool -> do
+ src/integration-tests/Specs/ConnectionDiscardsSpec.hs view
@@ -0,0 +1,161 @@+-- | Reachability and recovery coverage for+-- 'Hasql.Pool.ConnectionDiscards'.+--+-- The verdicts themselves are pure functions of a SQLSTATE and are pinned by+-- the @unit-tests@ suite, which needs no server. What only a live server can+-- establish is the two things asserted here:+--+-- * that the code in question actually reaches the predicate as a+-- 'Errors.SessionUseError', rather than arriving as a+-- 'Errors.ConnectionUseError' the pool discards without consulting the+-- module at all, and+--+-- * that the discard restores service - the residue really was+-- connection-local, and a fresh connection runs the same statement+-- successfully.+--+-- Every test therefore runs against a pool of size 1, so "the next use" is+-- guaranteed to be either the same connection or its replacement.+module Specs.ConnectionDiscardsSpec where++import Data.Text qualified as Text+import Hasql.Decoders qualified as Decoders+import Hasql.Encoders qualified as Encoders+import Hasql.Pool+import Hasql.Session qualified as Session+import Hasql.Statement qualified as Statement+import Helpers.Scripts qualified as Scripts+import Helpers.Sessions qualified as Sessions+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+ -- XX000. The server notices the retired type OID while replanning the+ -- prepared statement and raises @cache lookup failed for type NNNN@, which+ -- repeats on every subsequent execution over that connection.+ it "Discards a connection whose prepared statement references a recreated type" \scopeParams -> do+ typeName <- Text.replace "-" "_" <$> Scripts.generateName "cached_type_"+ onSingleConnectionPool scopeParams \pool -> do+ use pool (Session.script (createTypeSql typeName)) `shouldReturn` Right ()+ use pool (roundtripEnum typeName "ok") `shouldReturn` Right "ok"+ use pool (Session.script (recreateTypeSql typeName)) `shouldReturn` Right ()+ shouldFailWithSessionError (use pool (roundtripEnum typeName "ok"))+ use pool (roundtripEnum typeName "ok") `shouldReturn` Right "ok"++ -- 0A000, @cached plan must not change result type@. The prepared plan for+ -- @select *@ was built against one column; adding a second one invalidates+ -- it permanently for this connection.+ it "Discards a connection whose prepared plan outlived the shape of its result" \scopeParams -> do+ tableName <- Text.replace "-" "_" <$> Scripts.generateName "cached_plan_"+ onSingleConnectionPool scopeParams \pool -> do+ use pool (Session.script ("create table " <> quoteIdentifier tableName <> " (a int8)"))+ `shouldReturn` Right ()+ use pool (selectStar tableName) `shouldReturn` Right ()+ use pool (Session.script ("alter table " <> quoteIdentifier tableName <> " add column b int8"))+ `shouldReturn` Right ()+ shouldFailWithSessionError (use pool (selectStar tableName))+ -- The replacement connection replans against the new shape, so the+ -- one-column decoder now genuinely mismatches. That it fails+ -- \*differently* is the point: the plan-cache residue is gone.+ use pool (selectTwoColumns tableName) `shouldReturn` Right ()++ -- 26000, @prepared statement "..." does not exist@. Hasql's statement+ -- cache still lists the name; the server no longer does, and nothing+ -- evicts the stale entry.+ it "Discards a connection whose statement cache outlived the server's prepared statements" \scopeParams ->+ onSingleConnectionPool scopeParams \pool -> do+ use pool Sessions.selectOne `shouldReturn` Right 1+ use pool (Session.script "deallocate all") `shouldReturn` Right ()+ shouldFailWithSessionError (use pool Sessions.selectOne)+ use pool Sessions.selectOne `shouldReturn` Right 1++ -- 25P02. Note the sequencing: the statement that aborts the transaction+ -- fails with a syntax error, which is correctly *retained* - the residue+ -- only becomes visible on the following use, which is the one that+ -- triggers the discard.+ it "Discards a connection left parked in an aborted transaction" \scopeParams ->+ onSingleConnectionPool scopeParams \pool -> do+ shouldFailWithSessionError (use pool (Session.script "begin" >> Sessions.badQuery))+ shouldFailWithSessionError (use pool Sessions.selectOne)+ use pool Sessions.selectOne `shouldReturn` Right 1++ -- 57P01. Measured, not assumed: terminating the backend surfaces as a+ -- 'Errors.ConnectionUseError' carrying the FATAL text under @pqi-ffi@ and+ -- as a thrown exception under @pqi-native@ - in neither case as a server+ -- error whose SQLSTATE reaches 'ConnectionDiscards.serverError'. The+ -- @57P@ rule is therefore dead for this code, and is kept only because+ -- the rest of the class has not been shown to behave the same way. What+ -- this test asserts is the outcome all those paths share.+ it "Recovers from a backend terminated underneath it" \scopeParams ->+ onSingleConnectionPool scopeParams \pool -> do+ use pool Sessions.selectOne `shouldReturn` Right 1+ _ <- try @SomeException (use pool terminateSelf)+ use pool Sessions.selectOne `shouldReturn` Right 1++onSingleConnectionPool :: Scripts.ScopeParams -> (Pool -> IO ()) -> IO ()+onSingleConnectionPool scopeParams cont =+ Scripts.onAutotaggedPool 1 10 1_800 1_800 scopeParams (const cont)++shouldFailWithSessionError :: (Show a) => IO (Either UsageError a) -> Expectation+shouldFailWithSessionError action = do+ res <- action+ shouldSatisfy res \case+ Left (SessionUsageError _) -> True+ _ -> False++quoteIdentifier :: Text -> Text+quoteIdentifier identifier =+ "\"" <> Text.replace "\"" "\"\"" identifier <> "\""++createTypeSql :: Text -> Text+createTypeSql typeName =+ "create type " <> quoteIdentifier typeName <> " as enum ('sad', 'ok', 'happy')"++recreateTypeSql :: Text -> Text+recreateTypeSql typeName =+ "drop type "+ <> quoteIdentifier typeName+ <> "; create type "+ <> quoteIdentifier typeName+ <> " as enum ('sad', 'ok', 'happy')"++roundtripEnum :: Text -> Text -> Session.Session Text+roundtripEnum typeName value =+ Session.statement value statement+ where+ statement =+ Statement.preparable+ ("select $1 :: " <> quoteIdentifier typeName)+ (Encoders.param (Encoders.nonNullable (Encoders.enum Nothing typeName id)))+ (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing typeName Just))))++selectStar :: Text -> Session.Session ()+selectStar tableName =+ Session.statement () statement+ where+ statement =+ Statement.preparable+ ("select * from " <> quoteIdentifier tableName)+ Encoders.noParams+ (Decoders.rowList (Decoders.column (Decoders.nonNullable Decoders.int8)) $> ())++selectTwoColumns :: Text -> Session.Session ()+selectTwoColumns tableName =+ Session.statement () statement+ where+ statement =+ Statement.preparable+ ("select * from " <> quoteIdentifier tableName)+ Encoders.noParams+ ( Decoders.rowList+ ( (,)+ <$> Decoders.column (Decoders.nonNullable Decoders.int8)+ <*> Decoders.column (Decoders.nonNullable Decoders.int8)+ )+ $> ()+ )++terminateSelf :: Session.Session ()+terminateSelf =+ Session.script "select pg_terminate_backend(pg_backend_pid())"
src/integration-tests/Specs/UseSpec.hs view
@@ -35,7 +35,7 @@ use pool (Sessions.setSetting settingName "present") `shouldReturn` Right () result <- use pool driverError result `shouldSatisfy` \case- Left (SessionUsageError (Errors.DriverSessionError _)) -> True+ Left (SessionUsageError (Errors.ConnectionUseError _)) -> True _ -> False use pool (Sessions.getSetting settingName) `shouldReturn` Right Nothing @@ -56,7 +56,7 @@ Right pid <- use pool backendPid result <- use pool selectTwoRowsAsSingleRow result `shouldSatisfy` \case- Left (SessionUsageError (Errors.StatementSessionError _ _ _ _ _ Errors.UnexpectedRowCountStatementError {})) -> True+ Left (SessionUsageError (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ Errors.UnexpectedRowCountStatementError {}))) -> True _ -> False use pool backendPid `shouldReturn` Right pid @@ -228,7 +228,7 @@ driverError :: Session.Session () driverError = Session.onLibpqConnection \connection ->- pure (Left (Errors.DriverSessionError "synthetic driver error"), connection)+ pure (Left (Errors.ConnectionUseError "synthetic driver error"), connection) -- | Establish two connections, return the first before the second, and give -- their backend PIDs.
src/library/Hasql/Pool.hs view
@@ -10,6 +10,7 @@ ) where +import Data.Text qualified as Text import Data.UUID.V4 qualified as Uuid import Hasql.Connection (Connection) import Hasql.Connection qualified as Connection@@ -17,9 +18,9 @@ import Hasql.Errors qualified as Errors import Hasql.Pool.Config.Config qualified as Config import Hasql.Pool.Config.ReuseOrder (ReuseOrder (..))+import Hasql.Pool.ConnectionDiscards qualified as ConnectionDiscards import Hasql.Pool.Observation import Hasql.Pool.Prelude-import Hasql.Pool.SessionErrorDestructors qualified as ErrorsDestruction import Hasql.Session qualified as Session import Pqi qualified @@ -193,11 +194,10 @@ -- | Use a connection from the pool to run a session and return the connection -- to the pool, when finished. ----- Session failing with a 'Errors.ConnectionSessionError' or leaving the--- connection in the 'Pqi.ConnectionBad' state gets interpreted as a loss of--- connection. In such case the connection does not get returned to the pool--- and a slot gets freed up for a new connection to be established the next--- time one is needed. The error still gets returned from this function.+-- A connection error, a session error that leaves connection-specific+-- state, or a session error on a connection the adapter marks as+-- 'Pqi.ConnectionBad' gets interpreted as a loss of connection. The+-- connection is not returned to the pool and a slot is freed for a new one. -- -- __Warning:__ Due to the mechanism mentioned above you should avoid intercepting this error type from within sessions. --@@ -236,6 +236,11 @@ Given reuseVar Nothing -> onSlot unmask reuseVar Given reuseVar (Just entry) -> onEntry unmask reuseVar entry where+ optionalDetails details =+ if details == ""+ then Nothing+ else Just details+ enqueue :: Word64 -> STM Waiter enqueue now = do waiter <- Waiter (now + poolAcquisitionTimeout) <$> newEmptyTMVar <*> newTVar False@@ -308,10 +313,11 @@ unmask (Connection.acquire poolAdapter settings) >>= \case Left connErr -> do let connErrText = case connErr of- Errors.NetworkingConnectionError details -> Just details- Errors.AuthenticationConnectionError details -> Just details- Errors.CompatibilityConnectionError details -> Just details- Errors.OtherConnectionError details -> if details == "" then Nothing else Just details+ Errors.ConnectionAcquireError details -> optionalDetails details+ Errors.ConnectionPasswordRequiredAcquireError details -> optionalDetails details+ Errors.VersionTooOldAcquireError {} -> Just (Errors.toDetailedText connErr)+ Errors.InitializationConnectionLossAcquireError details -> optionalDetails details+ Errors.InitializationServerErrorAcquireError serverError -> Just (Errors.toDetailedText serverError) unmask $ poolObserver (ConnectionObservation id (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason connErrText))) atomically returnSlot return $ Left $ ConnectionUsageError connErr@@ -320,10 +326,11 @@ Left err -> do Connection.release connection unmask- $ ErrorsDestruction.reset- (\details -> poolObserver (ConnectionObservation id (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason (Just details)))))- (poolObserver (ConnectionObservation id (TerminatedConnectionStatus (InitializationErrorTerminationReason err))))- err+ $ case err of+ Errors.ConnectionUseError details ->+ poolObserver (ConnectionObservation id (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason (optionalDetails details))))+ Errors.SessionUseError sessionErr ->+ poolObserver (ConnectionObservation id (TerminatedConnectionStatus (InitializationErrorTerminationReason sessionErr))) atomically returnSlot return $ Left $ SessionUsageError err Right () -> do@@ -345,28 +352,44 @@ case sessRes of Left exc -> do- returnConn reuseVar entry+ Connection.release (entryConnection entry)+ atomically returnSlot+ unmask+ $ poolObserver+ ( ConnectionObservation+ (entryId entry)+ (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason (Just (Text.pack (displayException exc)))))+ ) throwIO exc- Right (Left err) -> do- discard <-- if ErrorsDestruction.requiresConnectionDiscard err- then return True- else connectionIsLost (entryConnection entry)- if discard- then do+ Right (Left err) ->+ case err of+ Errors.ConnectionUseError details -> do Connection.release (entryConnection entry) atomically returnSlot unmask $ poolObserver ( ConnectionObservation (entryId entry)- (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason (Just (Errors.toMessage err))))+ (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason (optionalDetails details))) ) return $ Left $ SessionUsageError err- else do- returnConn reuseVar entry- unmask $ poolObserver (ConnectionObservation (entryId entry) (ReadyForUseConnectionStatus (SessionFailedConnectionReadyForUseReason err)))- return $ Left $ SessionUsageError err+ Errors.SessionUseError sessionErr -> do+ discard <- (||) (ConnectionDiscards.sessionError sessionErr) <$> connectionIsLost (entryConnection entry)+ if discard+ then do+ Connection.release (entryConnection entry)+ atomically returnSlot+ unmask+ $ poolObserver+ ( ConnectionObservation+ (entryId entry)+ (TerminatedConnectionStatus (NetworkErrorConnectionTerminationReason (Just (Errors.toMessage err))))+ )+ return $ Left $ SessionUsageError err+ else do+ returnConn reuseVar entry+ unmask $ poolObserver (ConnectionObservation (entryId entry) (ReadyForUseConnectionStatus (SessionFailedConnectionReadyForUseReason sessionErr)))+ return $ Left $ SessionUsageError err Right (Right res) -> do returnConn reuseVar entry unmask $ poolObserver (ConnectionObservation (entryId entry) (ReadyForUseConnectionStatus SessionSucceededConnectionReadyForUseReason))@@ -501,9 +524,9 @@ -- | Union over all errors that 'use' can result in. data UsageError = -- | Attempt to establish a connection failed.- ConnectionUsageError Errors.ConnectionError+ ConnectionUsageError Errors.AcquireError | -- | Session execution failed.- SessionUsageError Errors.SessionError+ SessionUsageError Errors.UseError | -- | Timeout acquiring a connection. AcquisitionTimeoutUsageError deriving (Show, Eq)
src/library/Hasql/Pool/Config/Setting.hs view
@@ -95,6 +95,12 @@ -- E.g., you can set the search path for all the sessions executed by the pool by executing the following: -- -- > initSession (Session.sql "SET search_path TO schema1, schema2, public;")+--+-- The state it establishes survives an ordinary session error (a bad query, a+-- constraint violation), since those leave the connection reusable. It does+-- not survive an asynchronous exception escaping the session: any such+-- exception spends the connection, so the next use runs 'initSession' again+-- on a fresh one. initSession :: Session.Session () -> Setting initSession x = Setting (\config -> config {Config.initSession = x})
+ src/library/Hasql/Pool/ConnectionDiscards.hs view
@@ -0,0 +1,206 @@+-- | Classification of 'Errors.SessionError' along the axis the pool cares+-- about: whether the connection it came back on is still fit to reuse.+--+-- Hasql's own verdict - 'Errors.SessionUseError' - only promises the+-- connection is still usable in the sense that 'Hasql.Connection.use' will+-- run another session on it without throwing. It does not promise the+-- statement that just failed can ever succeed on the same connection: a+-- stale catalog cache or a plan built against a type that no longer exists+-- leaves the connection alive but unable to replan that statement. Hasql+-- declined to own this call - see the removal of+-- 'Hasql.Errors.IsError.isTransient' - so the pool keeps making it itself,+-- the same way it always did.+--+-- 'Errors.ConnectionUseError' needs no classification here: it always means+-- the connection is gone, and hasql has already finished it.+--+-- == The standard a rule has to meet+--+-- A rule belongs here only if it can name the /residue/: state left behind+-- on this particular connection that a fresh connection would not have, and+-- that no subsequent session can clear. A rule that cannot name the residue+-- is a rule to delete.+--+-- The two errors are not symmetric. A wrong discard costs one reconnect,+-- paid once. A wrong retain hands back a connection whose client-side+-- caches - 'Hasql.ConnectionState.oidCache' and+-- 'Hasql.ConnectionState.statementCache' - disagree with the server, and+-- since nothing ever evicts from either, that connection fails the same+-- statement for the whole of its remaining lifetime. That asymmetry is the+-- reason a discard is the default cure below, not a reason to discard on+-- suspicion: the bar is still a nameable residue.+module Hasql.Pool.ConnectionDiscards where++import Data.Text qualified as Text+import Hasql.Errors qualified as Errors+import Hasql.Pool.Prelude++sessionError :: Errors.SessionError -> Bool+sessionError = \case+ -- Missing types leave no residue on the connection: the lookup is a live+ -- catalog query, nothing gets negatively cached, and the connection state+ -- comes back untouched. A fresh connection would ask the same catalog and+ -- get the same answer, so discarding buys nothing but a reconnect.+ Errors.MissingTypesSessionError {} -> False+ Errors.ScriptSessionError _ serverErr -> serverError serverErr+ Errors.StatementSessionError _ _ _ _ _ statementErr -> statementError statementErr++statementError :: Errors.StatementError -> Bool+statementError = \case+ Errors.ServerStatementError serverErr -> serverError serverErr+ -- The remaining constructors all describe a disagreement between the+ -- decoder the caller supplied and the result the server actually sent.+ -- The server raised no error, no cache was consulted or written, and the+ -- connection is in exactly the state it was in before the statement ran.+ -- A fresh connection re-runs the statement and fails identically, so a+ -- discard would cost a reconnect and change nothing.+ --+ -- 'UnexpectedColumnTypeStatementError' is worth singling out, because it+ -- used to discard. The reasoning was that a decoder built against an OID+ -- the catalog has since reassigned cannot succeed while the connection+ -- holds the old cache. That case is real, but it does not surface here:+ -- the server notices the dropped type first and raises @XX000@ (see+ -- 'serverError'), which arrives as a 'ServerStatementError'. What reaches+ -- this constructor instead is the ordinary mismatch - a decoder asking+ -- for @int4@ where the column is @text@ - which is a bug in the caller's+ -- code, not residue on the connection.+ --+ -- The match is deliberately exhaustive rather than a wildcard: when hasql+ -- adds a constructor, this module should fail to compile and force a+ -- verdict, instead of silently inheriting @False@.+ Errors.UnexpectedRowCountStatementError {} -> False+ Errors.UnexpectedColumnCountStatementError {} -> False+ Errors.UnexpectedColumnTypeStatementError {} -> False+ Errors.RowStatementError {} -> False+ Errors.UnexpectedResultStatementError {} -> False++-- | Verdict on a server error, keyed on its SQLSTATE.+--+-- The codes below are matched exactly unless a comment says otherwise.+-- Exactness is load-bearing in two places: @XX000@ discards while @XX001@+-- and @XX002@ do not, and @42P05@ discards while the rest of class @42@+-- does not.+serverError :: Errors.ServerError -> Bool+serverError (Errors.ServerError code _ _ _ _)+ -- @internal_error@. The target is @cache lookup failed for type NNNN@,+ -- raised when a prepared statement's plan references a type OID that a+ -- @drop type@ / @create type@ has since retired. Verified against a live+ -- server: every subsequent execution on that connection raises it again,+ -- forever. The residue is the server-side prepared statement bound to a+ -- dead OID, together with hasql's 'statementCache' entry that keeps+ -- pointing at it; both are session-scoped, so a fresh connection replans+ -- cleanly.+ --+ -- The code is broader than that: @XX000@ is also PostgreSQL's catch-all+ -- for internal faults that say nothing about the connection. Those get+ -- discarded too. That is a known over-reach, accepted because the code+ -- alone carries no way to tell the cases apart - the distinguishing+ -- signal is the message text, which the server localises under+ -- @lc_messages@ and which the pool therefore cannot rely on.+ | code == "XX000" = True+ -- @feature_not_supported@. The target is @cached plan must not change+ -- result type@, raised when a schema change alters the columns or+ -- parameter types a prepared statement was planned against. Verified+ -- against a live server: it too repeats on every subsequent execution.+ -- Same residue as @XX000@, same cure.+ --+ -- Same over-reach, too: plenty of statements asking for something+ -- PostgreSQL simply does not do raise @0A000@ on a perfectly healthy+ -- connection, and are discarded for nothing.+ | code == "0A000" = True+ -- @invalid_sql_statement_name@. Hasql's 'statementCache' is a+ -- client-side ledger of what it believes is prepared on this connection.+ -- This code means the ledger and the server disagree - the name hasql+ -- intends to execute is not there - and since nothing ever evicts from+ -- that ledger, the disagreement is permanent. Reproducible by+ -- deallocating a prepared statement and executing it afterwards.+ | code == "26000" = True+ -- @duplicate_prepared_statement@: the same ledger desynced the other way,+ -- with the server holding a name hasql thinks is free. Reachable when+ -- something outside hasql prepared a colliding name, or after a reset+ -- hasql did not observe. Same residue, same permanence.+ | code == "42P05" = True+ -- @in_failed_sql_transaction@. The connection is parked inside an aborted+ -- transaction, and every statement on it fails until a rollback. The pool+ -- does no I/O on the return path, so it cannot issue that rollback, which+ -- leaves a discard as the only cure available.+ | code == "25P02" = True+ -- Class @08@, @connection_exception@ - prefix match. Most of the class+ -- describes a connection that is already gone. @08P01@+ -- (@protocol_violation@) is the one that earns its place on residue+ -- grounds rather than liveness: client and server disagree about where+ -- they are in the wire protocol, and nothing on the connection can+ -- resynchronise them.+ --+ -- Expect most of this class to be unreachable in practice: when the+ -- socket dies hasql reports 'Errors.ConnectionUseError', which the pool+ -- discards without consulting this module at all. @08P01@ is the member+ -- worth keeping regardless, since a protocol desync need not come with a+ -- dead socket.+ | Text.isPrefixOf "08" code = True+ -- @statement_completion_unknown@. The one code in class @40@ that+ -- qualifies: the client does not know whether the statement committed, so+ -- the connection's transactional state is genuinely unknown rather than+ -- merely failed.+ | code == "40003" = True+ -- Class @57P@ - prefix match. @57P01@ (@admin_shutdown@), @57P02@+ -- (@crash_shutdown@), @57P03@ (@cannot_connect_now@), @57P04@+ -- (@database_dropped@), @57P05@ (@idle_session_timeout@), @57P06@+ -- (@idle_in_transaction_session_timeout@). All are FATAL: the server+ -- emits the error and closes the socket, so a connection that saw one is+ -- gone or going.+ --+ -- The prefix is @57P@ rather than @57@ on purpose. @57014@+ -- (@query_canceled@) must not match: a cancelled query leaves a perfectly+ -- healthy connection, and discarding on it would punish every caller-side+ -- timeout with a reconnect.+ --+ -- As with class @08@, some of these only ever arrive as+ -- 'Errors.ConnectionUseError', which the pool discards without consulting+ -- this module. @57P01@ was tested directly: terminating the backend+ -- underneath a session surfaces as a 'Errors.ConnectionUseError' carrying+ -- the FATAL text under @pqi-ffi@, and as a thrown exception under+ -- @pqi-native@ - never as a 'Errors.ServerError' reaching this function.+ -- The rule is kept anyway: it costs nothing, and the remaining codes in+ -- the class have not been shown to behave the same way.+ | Text.isPrefixOf "57P" code = True+ | otherwise = False++-- $rejected+--+-- Codes deliberately /not/ discarded, recorded here so they are not+-- reintroduced on the strength of sounding alarming. Each fails the+-- standard in the module header: the error is real, but the residue is not+-- on this connection.+--+-- * Class @53@, @insufficient_resources@ - @53000@, @53100@ (@disk_full@),+-- @53200@ (@out_of_memory@), @53400@. These describe a shortage on the+-- /server/. The connection that received the error is structurally+-- untouched, and a reconnect does not cure a full disk. Worse, under load+-- the condition fires on many connections at once, so a discard rule+-- turns a resource shortage into a reconnect storm against a server that+-- is already short of resources. @53300@ (@too_many_connections@) is+-- additionally unreachable here: it arrives at acquisition time as an+-- 'Errors.AcquireError' and never reaches this module.+--+-- * @25001@, @active_sql_transaction@. Raised when a command that cannot+-- run inside a transaction block is issued inside one. A caller bug, on a+-- healthy connection, reproduced identically by a fresh one. Listed only+-- so nobody groups it with @25P02@ by prefix.+--+-- * @40001@ (@serialization_failure@) and @40P01@ (@deadlock_detected@).+-- The canonical retry-on-the-same-connection cases. Discarding these+-- would make every serialisation retry pay for a reconnect.+--+-- * @57014@, @query_canceled@. See the @57P@ rule above.+--+-- * @55P03@ (@lock_not_available@) and @55006@ (@object_in_use@). Pure+-- contention between sessions; nothing is left behind on either.+--+-- * @58030@ (@io_error@), @XX001@ (@data_corrupted@), @XX002@+-- (@index_corrupted@). Genuinely alarming, but the damage is on disk. A+-- fresh connection reads the same corrupt page.+--+-- * Class @54@ (@program_limit_exceeded@), class @22@ (data exceptions),+-- and class @42@ other than @42P05@ (syntax and access rule violations).+-- Statement bugs, not connection state.
− src/library/Hasql/Pool/SessionErrorDestructors.hs
@@ -1,30 +0,0 @@-module Hasql.Pool.SessionErrorDestructors where--import Hasql.Errors qualified as Errors-import Hasql.Pool.Prelude--reset :: (Text -> x) -> x -> Errors.SessionError -> x-reset onReset onNoReset = \case- Errors.ConnectionSessionError details -> onReset details- _ -> onNoReset--requiresConnectionDiscard :: Errors.SessionError -> Bool-requiresConnectionDiscard = \case- Errors.ConnectionSessionError {} -> True- Errors.MissingTypesSessionError {} -> True- Errors.ScriptSessionError _ serverError -> isStaleServerError serverError- Errors.StatementSessionError _ _ _ _ _ statementError -> statementRequiresConnectionDiscard statementError- -- Driver errors indicate that Hasql or the server left the connection in an- -- unexpected state. In particular, Hasql closes the libpq connection when- -- cleanup after an interruption fails, so it must not be reused by the pool.- Errors.DriverSessionError {} -> True--statementRequiresConnectionDiscard :: Errors.StatementError -> Bool-statementRequiresConnectionDiscard = \case- Errors.ServerStatementError serverError -> isStaleServerError serverError- Errors.UnexpectedColumnTypeStatementError {} -> True- _ -> False--isStaleServerError :: Errors.ServerError -> Bool-isStaleServerError (Errors.ServerError code _ _ _ _) =- code == "0A000" || code == "XX000"
+ src/unit-tests/Main.hs view
@@ -0,0 +1,109 @@+module Main (main) where++import Data.Foldable (traverse_)+import Data.Text (Text)+import Data.Text qualified as Text+import Hasql.Errors qualified as Errors+import Hasql.Pool.ConnectionDiscards qualified as ConnectionDiscards+import Prelude+import Test.Hspec++main :: IO ()+main = hspec spec++spec :: Spec+spec = do+ describe "serverError" do+ describe "Discards" do+ traverse_+ discards+ [ ("XX000", "internal_error: stale plan against a retired type OID"),+ ("0A000", "feature_not_supported: cached plan must not change result type"),+ ("26000", "invalid_sql_statement_name: statement cache ledger desync"),+ ("42P05", "duplicate_prepared_statement: the same desync inverted"),+ ("25P02", "in_failed_sql_transaction: parked in an aborted transaction"),+ ("40003", "statement_completion_unknown: commit status unknown"),+ ("08000", "connection_exception"),+ ("08001", "sqlclient_unable_to_establish_sqlconnection"),+ ("08003", "connection_does_not_exist"),+ ("08004", "sqlserver_rejected_establishment_of_sqlconnection"),+ ("08006", "connection_failure"),+ ("08007", "transaction_resolution_unknown"),+ ("08P01", "protocol_violation: client and server disagree on wire state"),+ ("57P01", "admin_shutdown"),+ ("57P02", "crash_shutdown"),+ ("57P03", "cannot_connect_now"),+ ("57P04", "database_dropped"),+ ("57P05", "idle_session_timeout"),+ ("57P06", "idle_in_transaction_session_timeout")+ ]++ -- The rejections matter more than the acceptances: they are the rules+ -- most likely to be reintroduced on the strength of sounding alarming.+ describe "Retains" do+ traverse_+ retains+ [ ("53000", "insufficient_resources: a server-side shortage, not residue"),+ ("53100", "disk_full: a reconnect does not empty the disk"),+ ("53200", "out_of_memory: discarding turns a crunch into a reconnect storm"),+ ("53300", "too_many_connections: an acquisition-time error to begin with"),+ ("53400", "configuration_limit_exceeded"),+ ("25001", "active_sql_transaction: a caller bug on a healthy connection"),+ ("40001", "serialization_failure: the canonical same-connection retry"),+ ("40P01", "deadlock_detected: likewise"),+ ("57014", "query_canceled: must not be swept up by the 57P rule"),+ ("55P03", "lock_not_available: contention, not residue"),+ ("55006", "object_in_use: likewise"),+ ("58030", "io_error: the damage is on disk"),+ ("XX001", "data_corrupted: must not be swept up by the XX000 rule"),+ ("XX002", "index_corrupted: likewise"),+ ("54000", "program_limit_exceeded"),+ ("22012", "division_by_zero"),+ ("23505", "unique_violation"),+ ("42601", "syntax_error: must not be swept up by the 42P05 rule"),+ ("42P01", "undefined_table: likewise"),+ ("0A001", "a neighbour of 0A000, which is matched exactly")+ ]++ describe "statementError" do+ it "Retains on an unexpected column type, which is a decoder bug rather than residue" do+ ConnectionDiscards.statementError (Errors.UnexpectedColumnTypeStatementError 0 23 25)+ `shouldBe` False+ it "Retains on an unexpected row count" do+ ConnectionDiscards.statementError (Errors.UnexpectedRowCountStatementError 1 1 2)+ `shouldBe` False+ it "Retains on an unexpected column count" do+ ConnectionDiscards.statementError (Errors.UnexpectedColumnCountStatementError 2 3)+ `shouldBe` False+ it "Retains on an unexpected result" do+ ConnectionDiscards.statementError (Errors.UnexpectedResultStatementError "whatever")+ `shouldBe` False+ it "Defers to the server error it wraps" do+ ConnectionDiscards.statementError (Errors.ServerStatementError (serverErrorWithCode "XX000"))+ `shouldBe` True++ describe "sessionError" do+ it "Retains on missing types, whose lookup leaves the connection untouched" do+ ConnectionDiscards.sessionError (Errors.MissingTypesSessionError mempty)+ `shouldBe` False+ it "Defers to the server error a failed script carries" do+ ConnectionDiscards.sessionError (Errors.ScriptSessionError "select 1" (serverErrorWithCode "26000"))+ `shouldBe` True+ it "Defers to the statement error a failed statement carries" do+ ConnectionDiscards.sessionError+ (Errors.StatementSessionError 1 0 "select 1" [] False (Errors.UnexpectedRowCountStatementError 1 1 0))+ `shouldBe` False++discards :: (Text, String) -> Spec+discards (code, why) =+ it ("Discards on " <> Text.unpack code <> " - " <> why) do+ ConnectionDiscards.serverError (serverErrorWithCode code) `shouldBe` True++retains :: (Text, String) -> Spec+retains (code, why) =+ it ("Retains on " <> Text.unpack code <> " - " <> why) do+ ConnectionDiscards.serverError (serverErrorWithCode code) `shouldBe` False++serverErrorWithCode :: Text -> Errors.ServerError+serverErrorWithCode code =+ Errors.ServerError code "synthetic" Nothing Nothing Nothing