vzhn commented on PR #564:
URL: https://github.com/apache/commons-dbcp/pull/564#issuecomment-7202668810

   Thanks, Gary, and thanks for the credit. Agreed: the check belongs in 
`DelegatingConnection.close()`, with the existing `closed` flag, and I missed 
`PoolingDriver`.
   
   I re-ran my original reproducer on master at 3b6a4c4 (after #565 and #566): 
a pool of size 1, two threads closing the same handle while a third waits for a 
connection, 2,000 rounds. The waiter's connection was returned to the pool 
under it in 0 rounds, against 280 on fceee73. `TestPoolingDataSource` and 
`TestPoolingDriver` pass.
   
   While checking that, I found a different bug. GitHub issues are disabled 
here and I don't have an ASF JIRA account, so I'm reporting it in this comment.
   
   ## A connection that dies while idle lets BasicDataSource exceed maxTotal, 
permanently
   
   ### Summary
   
   With default settings (`testOnBorrow = true`), every pooled connection whose 
physical connection dies while it is idle in the pool permanently raises the 
effective `maxTotal` by one. A database restart, a firewall, or a server-side 
idle timeout is enough. After a restart that drops N idle connections, the pool 
can open N connections more than `maxTotal`. No concurrency is involved: the 
reproducer below is single-threaded and fails every time.
   
   **Versions:** commons-dbcp2 2.14.0 with commons-pool2 2.13.1. Also master at 
3b6a4c4 (after #565 and #566). JDK 21, Linux, H2 2.2.224.
   
   ### Reproducer
   
   The database allows one connection, so `maxTotal = 1`. Alice returns her 
connection, the database restarts at night, and the next day Bob gets a 
connection while Alice holds the only one.
   
   ```java
   import java.sql.*;
   import java.time.Duration;
   import org.apache.commons.dbcp2.BasicDataSource;
   
   public class AliceAndBob {
       static final String DB = "jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1";
   
       public static void main(String[] args) throws Exception {
           try (BasicDataSource pool = new BasicDataSource();
                Connection dba = DriverManager.getConnection(DB, "sa", "")) {   
// not from the pool
               pool.setUrl(DB);
               pool.setUsername("sa");
               pool.setMaxTotal(1);
               pool.setMaxWait(Duration.ofSeconds(1));
   
               int session;
               try (Connection alice = pool.getConnection()) {                  
 // day 1: Alice works, goes home
                   session = sessionOf(alice);
               }
               try (Statement st = dba.createStatement()) {                     
 // night: the database drops the idle session
                   st.execute("CALL ABORT_SESSION(" + session + ")");
               }
               Connection alice = pool.getConnection();                         
 // day 2: Alice gets a (new) connection
               sessionOf(alice);
               try {
                   Connection bob = pool.getConnection();                       
 // must time out: Alice holds the only one
                   sessionOf(bob);
                   System.out.println("BUG: Bob got a connection too. 
Connections in use: "
                           + pool.getNumActive() + ", maxTotal: " + 
pool.getMaxTotal());
                   bob.close();
               } catch (SQLException expected) {
                   System.out.println("OK: Bob waited and timed out");
               }
               alice.close();
           }
       }
   
       static int sessionOf(Connection c) throws SQLException {
           try (Statement st = c.createStatement(); ResultSet rs = 
st.executeQuery("SELECT SESSION_ID()")) {
               rs.next();
               return rs.getInt(1);
           }
       }
   }
   ```
   
   Output on 2.14.0 and on master:
   
   ```
   BUG: Bob got a connection too. Connections in use: 2, maxTotal: 1
   ```
   
   The overshoot accumulates. In a loop of "return, drop the idle session, 
borrow as many as possible", the pool hands out 2, 3, then 4 connections at 
once after 1, 2, then 3 dropped sessions.
   
   ### Cause
   
   The pooled object is destroyed twice, and `createCount` is decremented twice:
   
   1. `GenericObjectPool.borrowObject()` takes the idle `PoolableConnection`, 
activates it, and calls `factory.validateObject(p)`.
   2. `PoolableConnectionFactory.validateConnection()` calls `conn.isClosed()`.
   3. `PoolableConnection.isClosed()` sees the underlying connection closed and 
calls `close()` ("Something has gone wrong ... Return it now."). `close()` sees 
the underlying connection closed and calls `pool.invalidateObject(this)`. That 
runs `destroy()` (`createCount--`) and then `addObject()`, which creates a new 
idle connection (`createCount++`).
   4. Validation fails, so `borrowObject()` calls `destroy(p)` on the same 
object. `GenericObjectPool.destroy()` doesn't check whether `p` was already 
destroyed: it removes nothing, but still runs `createCount--`.
   
   `createCount` is now one lower than the number of objects that exist, so 
`create()` allows one connection past `maxTotal`. `getNumActive()` reports the 
real number (2), which is how the output above shows it.
   
   ### TLA+ model
   
   A small model of the steps above: borrow with `testOnBorrow`, return, 
`invalidateObject` with `addObject`, the second `destroy`, and the database 
dropping a connection. TLC finds the same scenario as the reproducer.
   
   <details>
   <summary>DeadIdle.tla</summary>
   
   ```tla
   ------------------------------ MODULE DeadIdle ------------------------------
   \* BasicDataSource over GenericObjectPool with testOnBorrow = true (the 
default).
   \* objs is allObjects; createCount is GenericObjectPool.createCount.
   EXTENDS Integers, FiniteSets
   
   CONSTANTS Clients, MaxTotal, MaxIds
   
   VARIABLES objs, createCount, nextId, pc, cur
   vars == <<objs, createCount, nextId, pc, cur>>
   
   Init == /\ objs = [i \in {} |-> {}]
           /\ createCount = 0
           /\ nextId = 1
           /\ pc = [c \in Clients |-> "free"]
           /\ cur = [c \in Clients |-> 0]
   
   Without(o) == [i \in DOMAIN objs \ {o} |-> objs[i]]
   With(f, o, r) == [i \in DOMAIN f \cup {o} |-> IF i = o THEN r ELSE f[i]]
   Idle == {o \in DOMAIN objs : objs[o].state = "IDLE"}
   
   \* GenericObjectPool.invalidateObject(o): destroy(o), then addObject().
   Invalidate(o) ==
       IF createCount - 1 < MaxTotal /\ nextId <= MaxIds
       THEN /\ objs' = With(Without(o), nextId, [state |-> "IDLE", alive |-> 
TRUE])
            /\ nextId' = nextId + 1
            /\ UNCHANGED createCount              \* -1 for destroy, +1 for 
addObject
       ELSE /\ objs' = Without(o)
            /\ createCount' = createCount - 1
            /\ UNCHANGED nextId
   
   \* The database drops a connection (restart, firewall, idle timeout).
   Kill(o) == /\ o \in DOMAIN objs /\ objs[o].alive
              /\ objs' = [objs EXCEPT ![o].alive = FALSE]
              /\ UNCHANGED <<createCount, nextId, pc, cur>>
   
   \* borrowObject(): take an idle object, then validate it.
   BorrowIdle(c) == /\ pc[c] = "free"
                    /\ \E o \in Idle : /\ objs' = [objs EXCEPT ![o].state = 
"ALLOC"]
                                       /\ cur' = [cur EXCEPT ![c] = o]
                    /\ pc' = [pc EXCEPT ![c] = "validate"]
                    /\ UNCHANGED <<createCount, nextId>>
   
   \* borrowObject(): no idle object, create one if createCount < maxTotal.
   BorrowNew(c) == /\ pc[c] = "free" /\ Idle = {}
                   /\ createCount < MaxTotal /\ nextId <= MaxIds
                   /\ objs' = With(objs, nextId, [state |-> "ALLOC", alive |-> 
TRUE])
                   /\ createCount' = createCount + 1
                   /\ nextId' = nextId + 1
                   /\ cur' = [cur EXCEPT ![c] = nextId]
                   /\ pc' = [pc EXCEPT ![c] = "hold"]
   
   ValidateOk(c) == /\ pc[c] = "validate" /\ objs[cur[c]].alive
                    /\ pc' = [pc EXCEPT ![c] = "hold"]
                    /\ UNCHANGED <<objs, createCount, nextId, cur>>
   
   \* validateConnection() -> PoolableConnection.isClosed() -> close() -> 
invalidateObject(this)
   ValidateDead(c) == /\ pc[c] = "validate" /\ ~objs[cur[c]].alive
                      /\ Invalidate(cur[c])
                      /\ pc' = [pc EXCEPT ![c] = "failed"]
                      /\ UNCHANGED cur
   
   \* validateObject() returned false: borrowObject() calls destroy(p) on the 
same object;
   \* destroy() decrements createCount although p is already gone.
   DestroyAgain(c) == /\ pc[c] = "failed"
                      /\ objs' = Without(cur[c])
                      /\ createCount' = createCount - 1
                      /\ pc' = [pc EXCEPT ![c] = "free"]
                      /\ cur' = [cur EXCEPT ![c] = 0]
                      /\ UNCHANGED nextId
   
   \* Connection.close(): returnObject(), or invalidateObject() if the 
connection is dead.
   Close(c) == /\ pc[c] = "hold"
               /\ IF objs[cur[c]].alive
                    THEN /\ objs' = [objs EXCEPT ![cur[c]].state = "IDLE"]
                         /\ UNCHANGED <<createCount, nextId>>
                    ELSE Invalidate(cur[c])
               /\ pc' = [pc EXCEPT ![c] = "free"]
               /\ cur' = [cur EXCEPT ![c] = 0]
   
   Next == \/ \E o \in 1..MaxIds : Kill(o)
           \/ \E c \in Clients : \/ BorrowIdle(c) \/ BorrowNew(c) \/ 
ValidateOk(c)
                                 \/ ValidateDead(c) \/ DestroyAgain(c) \/ 
Close(c)
   
   Spec == Init /\ [][Next]_vars
   
   \* The pool never hands out more than maxTotal connections at once.
   AtMostMaxTotal == Cardinality({c \in Clients : pc[c] = "hold"}) <= MaxTotal
   =============================================================================
   ```
   
   </details>
   
   ```
   CONSTANTS Clients = {alice, bob}  MaxTotal = 1  MaxIds = 4
   SPECIFICATION Spec
   INVARIANT AtMostMaxTotal
   ```
   
   `tlc -deadlock DeadIdle.tla` (`-deadlock` because the bounded supply of 
connection ids always ends in a deadlock):
   
   ```
   Error: Invariant AtMostMaxTotal is violated.
   ```
   
   | # | action | pool after the step | createCount |
   |---|---|---|---|
   | 1 | initial | empty | 0 |
   | 2 | Alice borrows: connection 1 is created | 1 in use (Alice) | 1 |
   | 3 | Alice closes | 1 idle | 1 |
   | 4 | the database drops connection 1 | 1 idle, dead | 1 |
   | 5 | Alice borrows connection 1 | 1 in use, being validated | 1 |
   | 6 | validation: `isClosed()` → `close()` → `invalidateObject()`: 1 
destroyed, 2 added | 2 idle | 1 |
   | 7 | validation failed: `destroy()` on 1 again | 2 idle | **0** |
   | 8–9 | Alice borrows connection 2, validation passes | 2 in use (Alice) | 0 
|
   | 10 | Bob borrows: `createCount` 0 < 1, so connection 3 is created | 2 
(Alice) and 3 (Bob) in use | 1 |
   
   Related but different: 
[DBCP-193](https://issues.apache.org/jira/browse/DBCP-193) (negative NumActive 
with Oracle's `isClosed()`), 
[DBCP-398](https://issues.apache.org/jira/browse/DBCP-398) (hang when the 
underlying connection is closed), 
[POOL-231](https://issues.apache.org/jira/browse/POOL-231) (concurrent 
invalidate counters).
   
   ---
   
   *AI disclosure ([ASF Generative Tooling 
Guidance](https://www.apache.org/legal/generative-tooling.html)): found while 
checking #565. Claude Code (Claude Opus 5.5) wrote the reproducer, the 
analysis, the TLA+ model and this text, and ran the checks above.*
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to