Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(db): never restore a tenant token in a context that did not make it (CHOO-2623)

Wojciech Wojtyniakb5e2555765e7
diff --git a/core/switch_core/db/session_scope.py b/core/switch_core/db/session_scope.py
index 36a048172..a60ca40d2 100644
--- a/core/switch_core/db/session_scope.py
+++ b/core/switch_core/db/session_scope.py
@@ -56,7 +56,7 @@ from contextlib import asynccontextmanager
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
-from switch_core.tenant_context import bind_tenant_id, no_tenant, unbind_tenant_id
+from switch_core.tenant_context import no_tenant, tenant_scope
@asynccontextmanager
@@ -65,16 +65,13 @@ async def tenant_session(
) -> AsyncIterator[AsyncSession]:
"""Open a session bound to `tenant_id` for the life of the `async with` block.
- Binds before the session is constructed and unbinds in a `finally`, so a
+ Binds before the session is constructed and unbinds on the way out, so a
long-lived caller (a bridge's own task, say) cannot leak this tenant into
whatever it does next even if the block raises.
"""
- token = bind_tenant_id(tenant_id)
- try:
+ with tenant_scope(tenant_id):
async with session_factory() as session:
yield session
- finally:
- unbind_tenant_id(token)
@asynccontextmanager
diff --git a/core/switch_core/tenant_context.py b/core/switch_core/tenant_context.py
index c347d26bc..5f0415dbe 100644
--- a/core/switch_core/tenant_context.py
+++ b/core/switch_core/tenant_context.py
@@ -62,13 +62,34 @@ def clear_tenant_id() -> Token[str | None]:
@contextmanager
-def tenant_scope(tenant_id: str) -> Iterator[None]:
- """Bind `tenant_id` for the duration of the block."""
- token = bind_tenant_id(tenant_id)
+def _held(token: Token[str | None]) -> Iterator[None]:
+ """Hold `token` for the block and restore what it replaced on the way out.
+
+ Not restored when the block is unwound by `GeneratorExit`. That is a frame
+ being *finalised* rather than resumed — a coroutine dropped while
+ suspended and later closed by the garbage collector — and the collector
+ runs it in whatever context it happens to be in, not the one the token
+ belongs to. `Token.reset` refuses to cross contexts, correctly: restoring
+ there would write this scope's tenant into an unrelated one. There is also
+ nothing left to restore, since the context the token belongs to is
+ unreachable, which is why the frame is being finalised at all.
+ """
+ finalising = False
try:
yield
+ except GeneratorExit:
+ finalising = True
+ raise
finally:
- unbind_tenant_id(token)
+ if not finalising:
+ unbind_tenant_id(token)
+
+
+@contextmanager
+def tenant_scope(tenant_id: str) -> Iterator[None]:
+ """Bind `tenant_id` for the duration of the block."""
+ with _held(bind_tenant_id(tenant_id)):
+ yield
@contextmanager
@@ -88,8 +109,5 @@ def no_tenant() -> Iterator[None]:
has to bind the tenant of the row it is acting on — and one that forgets
reads nothing rather than reading the wrong tenant.
"""
- token = clear_tenant_id()
- try:
+ with _held(clear_tenant_id()):
yield
- finally:
- unbind_tenant_id(token)
diff --git a/core/tests/switch_core/test_tenant_context.py b/core/tests/switch_core/test_tenant_context.py
index 4394d2569..eb9b5c5b1 100644
--- a/core/tests/switch_core/test_tenant_context.py
+++ b/core/tests/switch_core/test_tenant_context.py
@@ -4,6 +4,9 @@ that reads or writes it for a real request."""
from __future__ import annotations
import asyncio
+import contextvars
+from collections.abc import Coroutine, Generator
+from typing import Any
from switch_core.tenant_context import (
bind_tenant_id,
@@ -15,6 +18,14 @@ from switch_core.tenant_context import (
)
+class _Suspend:
+ """An await that suspends once, so a coroutine can be left mid-scope with
+ no event loop in sight."""
+
+ def __await__(self) -> Generator[None, None, None]:
+ yield
+
+
class TestBindAndUnbind:
def test_nothing_bound_reads_as_none(self) -> None:
assert current_tenant_id() is None
@@ -113,3 +124,37 @@ class TestNoTenant:
assert current_tenant_id() is None
unbind_tenant_id(token)
assert current_tenant_id() == "tenant-a"
+
+
+class TestFinalisationInAnotherContext:
+ """A dropped coroutine is closed by the garbage collector, and the
+ collector runs the frame's `finally` in whatever context it is in rather
+ than the task's. A scope that reset its token there would either raise
+ (`Token.reset` refuses to cross contexts) or, worse, write its tenant into
+ a context that never asked for one."""
+
+ @staticmethod
+ def _drive_then_finalise_elsewhere(coro: Coroutine[Any, Any, None]) -> None:
+ """Enter the scope inside its own context, then close from this one."""
+ contextvars.copy_context().run(coro.send, None)
+ coro.close()
+
+ def test_no_tenant_survives_being_closed_from_another_context(self) -> None:
+ async def body() -> None:
+ with no_tenant():
+ await _Suspend()
+
+ with tenant_scope("caller"):
+ self._drive_then_finalise_elsewhere(body())
+ assert current_tenant_id() == "caller"
+
+ def test_tenant_scope_survives_being_closed_from_another_context(self) -> None:
+ async def body() -> None:
+ with tenant_scope("the-task-s-tenant"):
+ await _Suspend()
+
+ self._drive_then_finalise_elsewhere(body())
+ assert current_tenant_id() is None, (
+ "finalising a dropped coroutine leaked its tenant into the "
+ "collector's context"
+ )