LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-4253 [FIX] Cache the request's organization instead of querying it on every org-scoped queryset (#2330)
Rahul Johnyc86a1a70dc72
diff --git a/backend/account_v2/custom_auth_middleware.py b/backend/account_v2/custom_auth_middleware.pyindex b69174fdd..ce5a5627a 100644--- a/backend/account_v2/custom_auth_middleware.py+++ b/backend/account_v2/custom_auth_middleware.py@@ -6,6 +6,7 @@ from django.conf import settingsfrom django.http import HttpRequest, HttpResponse, JsonResponsefrom utils.constants import Accountfrom utils.local_context import StateStore+from utils.user_context import UserContextfrom utils.user_session import UserSessionUtilsfrom account_v2.authentication_plugin_registry import AuthenticationPluginRegistry@@ -194,7 +195,9 @@ class CustomAuthMiddleware:# Skip CSRF for Bearer-authenticated requestsrequest.csrf_processing_done = TrueStateStore.set(Common.LOG_EVENTS_ID, str(key.id))- StateStore.set(Account.ORGANIZATION_ID, key.organization.organization_id)+ # Sets the id, then caches the row loaded with the key: saves the+ # request's first org lookup.+ UserContext.set_organization(key.organization)try:return self.get_response(request)diff --git a/backend/backend/celery_service.py b/backend/backend/celery_service.pyindex 9e4f69717..1da4f0b05 100644--- a/backend/backend/celery_service.py+++ b/backend/backend/celery_service.py@@ -6,6 +6,7 @@ import osfrom pprint import pformatfrom celery import Celery+from celery.signals import task_postrunfrom backend.settings.base import LOGGING@@ -28,3 +29,17 @@ app.config_from_object("backend.celery_config.CeleryConfig")app.autodiscover_tasks()logger.debug(f"Celery Configuration:\n {pformat(app.conf.table(with_defaults=True))}")+++@task_postrun.connect+def _drop_cached_organization(**kwargs: object) -> None:+ """Backstop for tasks that set the organization id and never clear it.++ Setting the id already drops the cached organization, so this only keeps a+ pool worker (a prefork child process, or a thread under the threads pool)+ from carrying it into a task that relies on a leftover id.+ """+ # Lazy: account_v2.models needs the app registry, ready once tasks run.+ from utils.user_context import UserContext++ UserContext.clear_organization_cache()diff --git a/backend/conftest.py b/backend/conftest.pyindex bbf191042..159393cc3 100644--- a/backend/conftest.py+++ b/backend/conftest.py@@ -16,6 +16,7 @@ testenv); this file only takes effect in local/IDE runs.from pathlib import Path+import pytestfrom dotenv import load_dotenv# `-s` is set in pyproject so prints surface — log when test.env is absent@@ -24,6 +25,25 @@ if not load_dotenv(Path(__file__).parent / "test.env", override=False):print("[conftest] backend/test.env not found; using ambient environment", flush=True)[email protected](autouse=True)+def _drop_cached_organization():+ """Keep the per-request organization cache from crossing tests.++ Tests share a thread, and many leave the organization id set. Production+ drops the cache when the next request sets the id, or at request end; a+ test that relies on a leftover id would instead be served an organization+ another test created and rolled back.+ """+ yield+ # Django-free on purpose: ``utils.user_context`` (which registers the cache+ # as a derived key) needs the app registry, and ``utils.constants`` needs+ # configured settings; a run of the Django-free test files has neither, and+ # then has nothing registered to drop either.+ from utils.local_context import StateStore++ StateStore.drop_derived()++def pytest_collection_modifyitems(items):"""Auto-mark every DB-bound test as ``integration`` so the rig's unit tier(``-m 'not integration'``) skips it while the integration tier (live@@ -32,7 +52,6 @@ def pytest_collection_modifyitems(items):backend test needs a database. Kept central so tests declare their DB needby how they're written, not by a hand-maintained marker on each file."""- import pytestfrom django.test import TestCase, TransactionTestCasefor item in items:diff --git a/backend/middleware/internal_api_auth.py b/backend/middleware/internal_api_auth.pyindex a34b62a47..204ae8554 100644--- a/backend/middleware/internal_api_auth.py+++ b/backend/middleware/internal_api_auth.py@@ -170,6 +170,7 @@ class InternalAPIAuthMiddleware(MiddlewareMixin):# Enhanced organization context validationfrom utils.organization_utils import resolve_organization+ from utils.user_context import UserContexttry:organization = resolve_organization(org_id, raise_on_not_found=False)@@ -183,8 +184,9 @@ class InternalAPIAuthMiddleware(MiddlewareMixin):"name": organization.display_name,"validated": True,}- # Store the organization_id string field in StateStore for UserContext compatibility- StateStore.set(Account.ORGANIZATION_ID, organization.organization_id)+ # Store the organization_id string field in StateStore for UserContext compatibility,+ # then cache the row already loaded above: saves the request's first org lookup.+ UserContext.set_organization(organization)logger.debug(f"Organization context validated and set: {organization.display_name} (org_id: {organization.organization_id}, pk: {organization.id})"diff --git a/backend/tenant_account_v2/test_capabilities.py b/backend/tenant_account_v2/test_capabilities.pyindex 40e906aa4..47a09d6c9 100644--- a/backend/tenant_account_v2/test_capabilities.py+++ b/backend/tenant_account_v2/test_capabilities.py@@ -35,6 +35,7 @@ from platform_api.models import ApiKeyPermission, PlatformApiKeyfrom platform_api.views import PlatformApiKeyViewSetfrom platform_audit.tests.base import AuditTestBase, make_userfrom rest_framework.exceptions import PermissionDenied+from utils.user_context import UserContextfrom workflow_manager.workflow_v2.models.workflow import Workflowfrom workflow_manager.workflow_v2.views import WorkflowViewSet@@ -136,6 +137,10 @@ class CapabilityTestBase(AuditTestBase):spec = next(s for s in SPECS if s.key == key)Organization.objects.filter(pk=self.org.pk).update(**{spec.field: restricted})self.org.refresh_from_db()+ # Stands in for an admin's change made in another request. The cached+ # organization is dropped at every request end (request_finished), so+ # no real request is served a row cached before the change.+ UserContext.clear_organization_cache()def capabilities(self, user) -> dict[str, dict]:response = self.call(organization_capabilities, "get", user=user)@@ -266,6 +271,19 @@ class CapabilitiesApiTests(CapabilityTestBase):{"restrict_llm_adapter_creation": True, "restrict_connector_creation": True},)+ def test_a_change_is_seen_by_later_reads_in_the_same_request(self) -> None:+ """Both views write through their own locked row. The organization the+ request cached when the view looked it up must not keep the old values.+ """+ self.call(+ organization_settings, "patch", data={"restrict_llm_adapter_creation": True}+ )+ self.assertTrue(UserContext.get_organization().restrict_llm_adapter_creation)+ self.call(+ organization_capabilities, "patch", data={"create_connectors": "admins_only"}+ )+ self.assertTrue(UserContext.get_organization().restrict_connector_creation)+def test_each_change_is_audited_once(self) -> None:self.call(organization_capabilities,diff --git a/backend/tenant_account_v2/views.py b/backend/tenant_account_v2/views.pyindex d7806ccbb..6e9f1c61e 100644--- a/backend/tenant_account_v2/views.py+++ b/backend/tenant_account_v2/views.py@@ -254,6 +254,10 @@ def _save_restrictions(setattr(locked, field, value)locked.modified_by = request.userlocked.save(update_fields=[*values, "modified_by", "modified_at"])+ # The request's cached organization is another instance and still holds+ # the old values; cache the written row so later reads in this request+ # see them.+ UserContext.cache_organization(locked)return locked, beforediff --git a/backend/utils/constants.py b/backend/utils/constants.pyindex 222828f80..d7be2a794 100644--- a/backend/utils/constants.py+++ b/backend/utils/constants.py@@ -14,6 +14,8 @@ class Account:CREATED_BY = "created_by"MODIFIED_BY = "modified_by"ORGANIZATION_ID = "organization_id"+ # (organization_id, Organization) resolved for the current request or task.+ ORGANIZATION_CACHE = "organization_cache"class Common:diff --git a/backend/utils/local_context.py b/backend/utils/local_context.pyindex 0d11c0f6a..343f4de3e 100644--- a/backend/utils/local_context.py+++ b/backend/utils/local_context.py@@ -17,6 +17,12 @@ class StateStore:mode = os.environ.get("CONCURRENCY_MODE", ConcurrencyMode.THREAD)# Thread-safe storage.thread_local = threading.local()+ # Keys holding a value cached from another key, keyed by that source key.+ # Setting or clearing the source drops them, so a cached value is never+ # served once the value it was built from has changed. That alone does not+ # bound it to a request or task: a path that sets the source and never+ # clears it needs a boundary hook (see utils.user_context).+ _derived_keys: dict[str, set[str]] = {}@classmethoddef _get_thread_local(cls, key: str) -> Any:@@ -30,6 +36,25 @@ class StateStore:def _del_thread_local(cls, key: str) -> None:delattr(cls.thread_local, key)+ @classmethod+ def register_derived_key(cls, source_key: str, derived_key: str) -> None:+ """Drop ``derived_key`` whenever ``source_key`` is set or cleared."""+ cls._derived_keys.setdefault(source_key, set()).add(derived_key)++ @classmethod+ def _drop_derived(cls, key: str) -> None:+ for derived_key in cls._derived_keys.get(key, ()):+ if hasattr(cls.thread_local, derived_key):+ delattr(cls.thread_local, derived_key)++ @classmethod+ def drop_derived(cls) -> None:+ """Drop every registered derived value on this thread, leaving the+ source keys as they are. A no-op where nothing has registered one.+ """+ for key in cls._derived_keys:+ cls._drop_derived(key)+@classmethoddef get(cls, key: str) -> Any:if cls.mode == ConcurrencyMode.THREAD:@@ -40,6 +65,7 @@ class StateStore:@classmethoddef set(cls, key: str, val: Any) -> None:if cls.mode == ConcurrencyMode.THREAD:+ cls._drop_derived(key)return cls._set_thread_local(key, val)else:raise RuntimeError(Exceptions.UNKNOWN_MODE)@@ -47,6 +73,8 @@ class StateStore:@classmethoddef clear(cls, key: str) -> None:if cls.mode == ConcurrencyMode.THREAD:+ # Before the delete, which raises when the key was never set.+ cls._drop_derived(key)return cls._del_thread_local(key)else:raise RuntimeError(Exceptions.UNKNOWN_MODE)diff --git a/backend/utils/tests/test_organization_cache.py b/backend/utils/tests/test_organization_cache.pynew file mode 100644index 000000000..c6448ef09--- /dev/null+++ b/backend/utils/tests/test_organization_cache.py@@ -0,0 +1,82 @@+"""Org-scoped querysets reuse the cached organization (UN-4253).++``DefaultOrganizationManagerMixin`` asks ``UserContext.get_organization()``+for the organization on every queryset. Without the per-request cache each of+those cost an extra ``SELECT ... FROM organization``, about one in six of the+statements the database ran under load. These pin the saving and that it+does not weaken the tenant boundary or serve stale settings.+"""++import secrets++import pytest+from account_v2.models import Organization+from django.db import connection+from django.test import TestCase+from django.test.utils import CaptureQueriesContext+from workflow_manager.workflow_v2.models.workflow import Workflow++from utils.constants import Account+from utils.local_context import StateStore+from utils.user_context import UserContext+++def _organization_lookups(queries) -> int:+ return sum(1 for q in queries if 'FROM "organization"' in q["sql"])+++class OrganizationCacheTest(TestCase):+ def setUp(self) -> None:+ self.org_a = self._org("a")+ self.org_b = self._org("b")+ self.wf_a = Workflow._base_manager.create(+ workflow_name=f"wf-a-{secrets.token_hex(3)}", organization=self.org_a+ )+ self.wf_b = Workflow._base_manager.create(+ workflow_name=f"wf-b-{secrets.token_hex(3)}", organization=self.org_b+ )++ def tearDown(self) -> None:+ for key in (Account.ORGANIZATION_ID, Account.ORGANIZATION_CACHE):+ if hasattr(StateStore.thread_local, key):+ delattr(StateStore.thread_local, key)++ def _org(self, tag: str) -> Organization:+ slug = f"org-{tag}-{secrets.token_hex(3)}"+ return Organization.objects.create(+ name=slug, display_name=slug, organization_id=slug+ )++ def test_org_resolved_once_across_querysets(self):+ StateStore.set(Account.ORGANIZATION_ID, self.org_a.organization_id)+ with CaptureQueriesContext(connection) as ctx:+ for _ in range(5):+ assert list(Workflow.objects.all()) == [self.wf_a]+ assert _organization_lookups(ctx.captured_queries) == 1++ def test_switching_org_scopes_to_the_new_org(self):+ StateStore.set(Account.ORGANIZATION_ID, self.org_a.organization_id)+ assert list(Workflow.objects.all()) == [self.wf_a]+ StateStore.set(Account.ORGANIZATION_ID, self.org_b.organization_id)+ assert list(Workflow.objects.all()) == [self.wf_b]++ def test_next_request_sees_changed_settings(self):+ """An admin toggling a controlled-mode flag must take effect on the+ next request, even on a thread that served the org before.+ """+ StateStore.set(Account.ORGANIZATION_ID, self.org_a.organization_id)+ assert UserContext.get_organization().restrict_connector_creation is False+ Organization.objects.filter(pk=self.org_a.pk).update(+ restrict_connector_creation=True+ )+ # A new request on the same thread starts by setting the id.+ StateStore.set(Account.ORGANIZATION_ID, self.org_a.organization_id)+ assert UserContext.get_organization().restrict_connector_creation is True++ def test_seeded_org_needs_no_lookup(self):+ StateStore.set(Account.ORGANIZATION_ID, self.org_a.organization_id)+ UserContext.cache_organization(self.org_a)+ with CaptureQueriesContext(connection) as ctx:+ assert list(Workflow.objects.all()) == [self.wf_a]+ assert _organization_lookups(ctx.captured_queries) == 0diff --git a/backend/utils/tests/test_organization_cache_middleware.py b/backend/utils/tests/test_organization_cache_middleware.pynew file mode 100644index 000000000..16ce3bfb1--- /dev/null+++ b/backend/utils/tests/test_organization_cache_middleware.py@@ -0,0 +1,148 @@+"""The organization cache's seeding sites and request boundary, through a real+middleware chain (UN-4253).++``UserContext.set_organization`` seeds the cache only after the id is set, and a+seed that is lost reports nothing: the request simply pays the organization+lookup again. Only a request through the real chain, counting ``organization``+SELECTs, pins that the Bearer and internal-API paths seed. The last test pins+the request boundary: a whitelisted path that sets the id inside the view (as+the API-deployment helpers do) must not leave the cached row on the thread once+the response is closed.+"""++import secrets+import uuid++from account_v2.models import Organization, User+from django.conf import settings+from django.db import connection+from django.test import override_settings+from django.test.utils import CaptureQueriesContext+from django.urls import path+from platform_api.models import PlatformApiKey+from rest_framework.authentication import SessionAuthentication+from rest_framework.decorators import (+ api_view,+ authentication_classes,+ permission_classes,+)+from rest_framework.response import Response+from rest_framework.test import APITestCase+from workflow_manager.workflow_v2.models.workflow import Workflow++from utils.constants import Account+from utils.local_context import StateStore+from utils.user_context import UserContext++ORG = "org-cache"+INTERNAL_KEY = "internal-test-key"+++@api_view(["GET"])+@authentication_classes([SessionAuthentication])+@permission_classes([])+def _scoped_view(request):+ """Evaluates an org-scoped default manager, which resolves the organization+ through ``UserContext.get_organization``.+ """+ return Response({"workflows": Workflow.objects.count()})+++@api_view(["GET"])+@authentication_classes([SessionAuthentication])+@permission_classes([])+def _whitelisted_view(request):+ """What the API-deployment helpers do on a whitelisted path: set the id+ inside the view and never clear it.+ """+ UserContext.set_organization_identifier(ORG)+ UserContext.get_organization()+ return Response({"cached": StateStore.get(Account.ORGANIZATION_CACHE) is not None})+++# OrganizationMiddleware strips the org segment before routing, so the Bearer+# view is registered on the stripped path while requests use the full one. The+# other two paths carry no org segment: ``/internal/`` is the internal API+# prefix, ``/health`` is in WHITELISTED_PATHS.+urlpatterns = [+ path("api/v1/unstract/scoped/", _scoped_view),+ path("internal/scoped/", _scoped_view),+ path("health/cache-probe/", _whitelisted_view),+]+BEARER_URL = f"/api/v1/unstract/{ORG}/scoped/"+INTERNAL_URL = "/internal/scoped/"+WHITELISTED_URL = "/health/cache-probe/"++# Trimmed from the production chain, preserving its relative order.+_MIDDLEWARE = [+ "middleware.request_id.CustomRequestIDMiddleware",+ settings.TENANT_MIDDLEWARE,+ "middleware.internal_api_auth.InternalAPIAuthMiddleware",+ "django.contrib.sessions.middleware.SessionMiddleware",+ "django.middleware.csrf.CsrfViewMiddleware",+ "django.contrib.auth.middleware.AuthenticationMiddleware",+ settings.CUSTOM_AUTH_MIDDLEWARE,+]+++def _organization_lookups(queries) -> int:+ return sum(1 for q in queries if 'FROM "organization"' in q["sql"])+++@override_settings(+ ROOT_URLCONF=__name__, MIDDLEWARE=_MIDDLEWARE, INTERNAL_SERVICE_API_KEY=INTERNAL_KEY+)+class OrganizationCacheMiddlewareTest(APITestCase):+ def setUp(self) -> None:+ self.org = Organization.objects.create(+ name=ORG, display_name="Org Cache", organization_id=ORG+ )+ service_account = User.objects.create_user(+ username="[email protected]",+ email="[email protected]",+ password=secrets.token_urlsafe(),+ )+ self.key = PlatformApiKey.objects.create(+ name=f"key-{uuid.uuid4().hex[:8]}",+ description="test key",+ organization=self.org,+ api_user=service_account,+ )++ def tearDown(self) -> None:+ for key in (Account.ORGANIZATION_ID, Account.ORGANIZATION_CACHE):+ if hasattr(StateStore.thread_local, key):+ delattr(StateStore.thread_local, key)++ def test_bearer_path_seeds_the_cache_from_the_key(self):+ """The key's ``select_related("organization")`` is a JOIN, not a+ ``FROM "organization"`` statement, so a seeded request runs none.+ """+ with CaptureQueriesContext(connection) as ctx:+ resp = self.client.get(+ BEARER_URL, HTTP_AUTHORIZATION=f"Bearer {self.key.key}"+ )+ assert resp.status_code == 200, resp.content+ assert _organization_lookups(ctx.captured_queries) == 0++ def test_internal_api_path_seeds_the_cache_from_the_resolved_org(self):+ """The middleware's own ``resolve_organization`` is the one lookup; the+ view's org-scoped queryset must not add a second.+ """+ with CaptureQueriesContext(connection) as ctx:+ resp = self.client.get(+ INTERNAL_URL,+ HTTP_AUTHORIZATION=f"Bearer {INTERNAL_KEY}",+ HTTP_X_ORGANIZATION_ID=ORG,+ )+ assert resp.status_code == 200, resp.content+ assert _organization_lookups(ctx.captured_queries) == 1++ def test_whitelisted_path_does_not_leave_the_cache_on_the_thread(self):+ """No middleware sets or clears the id here, so only the request+ boundary (``request_finished``) can drop the row the view cached.+ """+ resp = self.client.get(WHITELISTED_URL)+ assert resp.status_code == 200, resp.content+ assert resp.json() == {"cached": True}+ assert StateStore.get(Account.ORGANIZATION_CACHE) is Nonediff --git a/backend/utils/tests/test_user_context.py b/backend/utils/tests/test_user_context.pyindex 09d2c82d0..cbf001a98 100644--- a/backend/utils/tests/test_user_context.py+++ b/backend/utils/tests/test_user_context.py@@ -1,13 +1,22 @@"""Regression tests for UserContext.get_organization.Pins the no-org short-circuit: the lookup must return None without touching the-DB, so it stays evaluable on a DB-less/unmigrated setup.+DB, so it stays evaluable on a DB-less/unmigrated setup. Also pins the+per-request organization cache (UN-4253)."""from __future__ import annotationsfrom unittest.mock import patch+import pytest+from account_v2.models import Organization+from celery.signals import task_postrun+from django.core.signals import request_finished+from django.db.utils import ProgrammingError++from utils.constants import Account+from utils.local_context import StateStorefrom utils.user_context import UserContext@@ -39,3 +48,185 @@ class TestGetOrganizationNoContext:):assert UserContext.get_organization() is sentinelmock_get.assert_called_once_with(organization_id="org-123")+++# --- Per-request organization cache (UN-4253) --------------------------------+#+# These run against the real StateStore: what is under test is how the cache+# reacts to the organization id being set and cleared, which a patched+# StateStore would hide.++_LOOKUP = "utils.user_context.Organization.objects.get"+++def _reset_state() -> None:+ for key in (Account.ORGANIZATION_ID, Account.ORGANIZATION_CACHE):+ if hasattr(StateStore.thread_local, key):+ delattr(StateStore.thread_local, key)++[email protected](autouse=True)+def clean_state_store():+ _reset_state()+ yield+ _reset_state()+++class _Org:+ """Stands in for an Organization row; only identity and pk are read."""++ def __init__(self, organization_id: str, pk: int | None = 1):+ self.organization_id = organization_id+ self.pk = pk+++def _lookup_returning(*orgs: _Org):+ by_id = {org.organization_id: org for org in orgs}+ return patch(_LOOKUP, side_effect=lambda organization_id: by_id[organization_id])+++class TestOrganizationCache:+ def test_repeat_calls_reuse_the_cached_organization(self):+ org = _Org("org-a")+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ with _lookup_returning(org) as lookup:+ for _ in range(5):+ assert UserContext.get_organization() is org+ lookup.assert_called_once_with(organization_id="org-a")++ def test_switching_org_never_returns_the_previous_one(self):+ """Tenant boundary: a cached org is only valid for the id it was built for."""+ org_a, org_b = _Org("org-a", pk=1), _Org("org-b", pk=2)+ with _lookup_returning(org_a, org_b):+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ assert UserContext.get_organization() is org_a+ StateStore.set(Account.ORGANIZATION_ID, "org-b")+ assert UserContext.get_organization() is org_b++ def test_cache_entry_for_another_id_is_ignored(self):+ """Even if an entry survived an id change, it must not be served."""+ org_a, org_b = _Org("org-a", pk=1), _Org("org-b", pk=2)+ StateStore.set(Account.ORGANIZATION_ID, "org-b")+ StateStore.set(Account.ORGANIZATION_CACHE, ("org-a", org_a))+ with _lookup_returning(org_b) as lookup:+ assert UserContext.get_organization() is org_b+ lookup.assert_called_once_with(organization_id="org-b")++ def test_setting_the_same_id_again_resolves_afresh(self):+ """Each request starts by setting the id, so settings changed by an+ admin between requests (e.g. restrict_connector_creation) are seen.+ """+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ with _lookup_returning(_Org("org-a")) as lookup:+ UserContext.get_organization()+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ UserContext.get_organization()+ assert lookup.call_count == 2++ def test_clearing_the_id_drops_the_cache(self):+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ with _lookup_returning(_Org("org-a")):+ UserContext.get_organization()+ StateStore.clear(Account.ORGANIZATION_ID)+ assert StateStore.get(Account.ORGANIZATION_CACHE) is None++ def test_clear_of_an_unset_id_still_raises(self):+ """Callers rely on this (they suppress AttributeError)."""+ with pytest.raises(AttributeError):+ StateStore.clear(Account.ORGANIZATION_ID)++ def test_not_found_is_not_cached(self):+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ with patch(_LOOKUP, side_effect=Organization.DoesNotExist) as lookup:+ assert UserContext.get_organization() is None+ assert UserContext.get_organization() is None+ assert lookup.call_count == 2+ assert StateStore.get(Account.ORGANIZATION_CACHE) is None++ def test_programming_error_is_not_cached(self):+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ with patch(_LOOKUP, side_effect=ProgrammingError) as lookup:+ assert UserContext.get_organization() is None+ assert UserContext.get_organization() is None+ assert lookup.call_count == 2++ def test_deleted_instance_is_not_served(self):+ """Django sets pk to None on delete; fall back to the lookup."""+ deleted = _Org("org-a", pk=None)+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ StateStore.set(Account.ORGANIZATION_CACHE, ("org-a", deleted))+ fresh = _Org("org-a", pk=7)+ with _lookup_returning(fresh):+ assert UserContext.get_organization() is fresh+++class TestCacheOrganization:+ def test_seeded_org_is_served_without_a_lookup(self):+ org = _Org("org-a")+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ UserContext.cache_organization(org)+ with patch(_LOOKUP) as lookup:+ assert UserContext.get_organization() is org+ lookup.assert_not_called()++ def test_seeding_another_org_is_ignored(self):+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ UserContext.cache_organization(_Org("org-b"))+ assert StateStore.get(Account.ORGANIZATION_CACHE) is None++ def test_seeding_without_an_id_is_ignored(self):+ UserContext.cache_organization(_Org("org-a"))+ assert StateStore.get(Account.ORGANIZATION_CACHE) is None++ def test_clear_organization_cache(self):+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ UserContext.cache_organization(_Org("org-a"))+ UserContext.clear_organization_cache()+ assert StateStore.get(Account.ORGANIZATION_CACHE) is None+ UserContext.clear_organization_cache() # idempotent++ def test_drop_derived_drops_the_cache_and_keeps_the_id(self):+ """What the root conftest fixture relies on between tests."""+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ UserContext.cache_organization(_Org("org-a"))+ StateStore.drop_derived()+ assert StateStore.get(Account.ORGANIZATION_CACHE) is None+ assert StateStore.get(Account.ORGANIZATION_ID) == "org-a"++ def test_set_organization_sets_the_id_then_seeds(self):+ org = _Org("org-a")+ with patch(_LOOKUP) as lookup:+ UserContext.set_organization(org)+ assert StateStore.get(Account.ORGANIZATION_ID) == "org-a"+ assert UserContext.get_organization() is org+ lookup.assert_not_called()+++class TestBoundaryHooks:+ """Sent through the signals, so what is pinned is the registration, not+ the receiver's body: ``backend.celery_service`` connects task_postrun when+ the ``backend`` package is imported, ``utils.user_context`` connects+ request_finished on import.+ """++ def test_celery_task_postrun_drops_the_cache(self):+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ UserContext.cache_organization(_Org("org-a"))+ task_postrun.send(+ sender=object(),+ task_id="t",+ task=None,+ args=(),+ kwargs={},+ retval=None,+ state=None,+ )+ assert StateStore.get(Account.ORGANIZATION_CACHE) is None++ @pytest.mark.django_db # Django's own close_old_connections receiver needs it+ def test_request_finished_drops_the_cache(self):+ """The boundary for paths that set the id and never clear it."""+ StateStore.set(Account.ORGANIZATION_ID, "org-a")+ UserContext.cache_organization(_Org("org-a"))+ request_finished.send(sender=object())+ assert StateStore.get(Account.ORGANIZATION_CACHE) is Nonediff --git a/backend/utils/user_context.py b/backend/utils/user_context.pyindex e0f2d4fc1..a0576f1e5 100644--- a/backend/utils/user_context.py+++ b/backend/utils/user_context.py@@ -1,9 +1,17 @@from account_v2.models import Organization+from django.core.signals import request_finishedfrom django.db.utils import ProgrammingErrorfrom utils.constants import Accountfrom utils.local_context import StateStore+# The cached organization is dropped whenever the organization id is set or+# cleared; a lookup that finds no row is not cached. A path that sets the id+# and never clears it (whitelisted paths return from CustomAuthMiddleware+# before its clear; some Celery tasks set it and leave it set) gets a boundary+# hook instead: request_finished below, task_postrun in backend.celery_service.+StateStore.register_derived_key(Account.ORGANIZATION_ID, Account.ORGANIZATION_CACHE)+class UserContext:@staticmethod@@ -15,12 +23,41 @@ class UserContext:def set_organization_identifier(organization_identifier: str) -> None:StateStore.set(Account.ORGANIZATION_ID, organization_identifier)+ @staticmethod+ def set_organization(organization: Organization) -> None:+ """Set the organization id from a row the caller already loaded, and cache it.++ One call, in this order, so the drop that setting the id triggers can+ never land after the seed.+ """+ StateStore.set(Account.ORGANIZATION_ID, organization.organization_id)+ UserContext.cache_organization(organization)+@staticmethoddef get_organization() -> Organization | None:+ """Resolve the current organization, caching a hit.++ Later calls return the same instance until the id is next set, the+ cache cleared, or another instance cached with ``cache_organization``,+ so a write to the row through another instance is not reflected in it+ until then. Conversely, every caller shares that+ instance: an attribute changed on it and not saved is seen by later+ org-scoped code in the same request or task.+ """organization_id = StateStore.get(Account.ORGANIZATION_ID)# Skip the query so this stays evaluable on a DB-less/unmigrated setup.if not organization_id:return None+ # Every org-scoped queryset calls this. The cached entry carries the id+ # it was resolved for and is used only while that id is still current.+ cached = StateStore.get(Account.ORGANIZATION_CACHE)+ if isinstance(cached, tuple) and cached[0] == organization_id:+ cached_organization: Organization = cached[1]+ # ``.delete()`` on this instance sets its pk to None (a row deleted+ # through another instance is not detected); fall through to the+ # lookup.+ if cached_organization.pk is not None:+ return cached_organizationtry:organization: Organization = Organization.objects.get(organization_id=organization_id@@ -32,4 +69,40 @@ class UserContext:# especially during the execution of management commands# other than runserverreturn None+ # Misses above are not cached, so they behave exactly as before.+ StateStore.set(Account.ORGANIZATION_CACHE, (organization_id, organization))return organization++ @staticmethod+ def cache_organization(organization: Organization) -> None:+ """Seed the cache with an organization the caller already loaded.++ Ignored unless ``organization`` is the current organization, so it must+ run after the id is set (``set_organization`` does both, in order).+ """+ organization_id = StateStore.get(Account.ORGANIZATION_ID)+ if organization_id and organization.organization_id == organization_id:+ StateStore.set(Account.ORGANIZATION_CACHE, (organization_id, organization))++ @staticmethod+ def clear_organization_cache() -> None:+ if StateStore.get(Account.ORGANIZATION_CACHE) is not None:+ StateStore.clear(Account.ORGANIZATION_CACHE)+++def _drop_cached_organization(**kwargs: object) -> None:+ """Request boundary for paths that set the organization id and never clear it.++ Whitelisted paths return from CustomAuthMiddleware before its clear, and+ some views behind them (API deployments, the OSS default-user login) set+ the id themselves. Without this the cached row would stay on the gunicorn thread+ until the id is next set, and be served stale to a later request on that+ thread that relies on the leftover id.+ """+ UserContext.clear_organization_cache()+++request_finished.connect(+ _drop_cached_organization,+ dispatch_uid="utils.user_context.drop_cached_organization",+)