Skip to content

Commit ca94831

Browse files
Keep inherited SQL sessions out of child finalizers
1 parent bbb6c24 commit ca94831

4 files changed

Lines changed: 17 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration.
5050

5151
### Fixed
5252

53+
- Forked PostgreSQL and SQL Server lock backends preserve the parent's active SQL sessions
54+
while opening a separate pool in the child.
5355
- Celery deliveries waiting on an idempotency lease preserve the task retry counter.
5456

5557
- Shared caches batch tag reads and recreate missing version tokens so deleting

‎docs/features/concurrency/leases-and-idempotency.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,12 @@ exposes that behavior for function calls.
7373

7474
`PgAdvisoryLock(engine)` and `SqlAppLock(engine)` accept a SQLAlchemy engine and hold a
7575
dedicated session connection while the lease is held. SQL session locks last for the
76-
session rather than a wall-clock TTL. Capacity must be one. Create engines and SQL
77-
lock backends before a fork (for example at import time in a preloading server). In a
78-
forked child, the backend forgets the parent's connections without closing them, disposes
79-
the inherited engine without closing its shared sockets, and then works normally. A lease
80-
the parent holds stays with the parent: the child's `release` for that token returns
81-
`False`. An engine without `dispose` still raises `RuntimeError` in a child. Use client/database
76+
session rather than a wall-clock TTL. Capacity must be one. Create engines after a fork
77+
when possible. If a preloading server creates the engine before forking, the child's
78+
first lock operation opens a fresh pool. The child retains references to the inherited
79+
pool and connections so driver finalizers cannot interfere with the parent's sessions.
80+
A lease the parent holds stays with the parent. The child's `release` for that token
81+
returns `False`. An engine without `dispose` raises `RuntimeError` in a child. Use client/database
8282
timeouts. Unlock failures invalidate the dedicated connection rather than returning a
8383
potentially locked session to its pool. These adapters need your application's SQLAlchemy
8484
installation and database driver; python-wrap does not install them.

‎src/python_wrap/coordination.py‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,9 @@ class AsyncRedisSemaphore(AsyncRedisLock):
216216
"""`AsyncRedisLock` with capacity supplied by Lease(limit=...)."""
217217

218218

219+
_inherited_sql_resources: list[tuple[Any, dict[str, tuple[str, Any, Any]]]] = []
220+
221+
219222
class _SQLLock:
220223
dialect: str
221224

@@ -234,10 +237,11 @@ def _process(self) -> None:
234237
with self._lock:
235238
if os.getpid() == self._pid:
236239
return
237-
# Connections opened before the fork belong to the parent: forget them
238-
# without closing, and discard pooled sockets the child must not reuse.
239-
self._connections = {}
240+
# Dropping the last reference can finalize a driver connection from the
241+
# child and send protocol traffic on the parent's SQL session.
242+
_inherited_sql_resources.append((getattr(self.engine, "pool", None), self._connections))
240243
dispose(close=False)
244+
self._connections = {}
241245
self._pid = os.getpid()
242246

243247
def _resource(self, key: str) -> Any:

‎tests/test_sql_backends_live.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ def job() -> str:
105105

106106
@pytest.mark.skipif(not hasattr(os, "fork"), reason="POSIX fork only")
107107
def test_sql_lock_backend_rebinds_after_fork(lock_backend):
108+
import gc
108109
import multiprocessing
109110

110111
backend, _ = lock_backend
@@ -113,6 +114,7 @@ def test_sql_lock_backend_rebinds_after_fork(lock_backend):
113114

114115
def use_in_child():
115116
assert not backend.acquire(key, "child", 30)
117+
gc.collect()
116118
assert backend.acquire(key + "-child", "child", 30)
117119
assert backend.release(key + "-child", "child")
118120

0 commit comments

Comments
 (0)