#!/usr/bin/env python3 """Deterministic Chapter 3 traces: WSGI/ASGI handlers, middleware onion, hooks, exception walls, sync/async mode adaptation, and thread-lane crossings. """ from __future__ import annotations import asyncio import atexit import io import logging import sys import tempfile import threading from contextlib import contextmanager from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(Path(__file__).resolve().parent)) from harness import Recorder, boot_desk # noqa: E402 boot_desk(seed_data=True, with_editor=True) import asgiref.sync # noqa: E402 from asgiref.sync import AsyncToSync, SyncToAsync, async_to_sync # noqa: E402 from django.conf import settings # noqa: E402 from django.core import signals # noqa: E402 from django.core.exceptions import ( # noqa: E402 BadRequest, DisallowedHost, ImproperlyConfigured, MiddlewareNotUsed, PermissionDenied, SuspiciousOperation, ) from django.core.handlers.asgi import ASGIHandler # noqa: E402 from django.core.handlers.wsgi import WSGIHandler # noqa: E402 from django.core.management import call_command # noqa: E402 from django.db import connections # noqa: E402 from django.http import Http404, HttpResponse # noqa: E402 from django.template.response import TemplateResponse # noqa: E402 from django.test import override_settings # noqa: E402 from django.urls import path # noqa: E402 from django.utils.deprecation import MiddlewareMixin # noqa: E402 from django.utils.module_loading import import_string # noqa: E402 from seed import seed # noqa: E402 # First capture the classic `:memory:` SQLite cross-thread trap under ASGI before # switching `default` to a file-backed temporary SQLite DB that worker threads share. _MEM_ASGI_ERROR: str = "" with override_settings(MIDDLEWARE=[], DEBUG_PROPAGATE_EXCEPTIONS=True): _mem_handler = ASGIHandler() async def _probe_mem_trap(): sent_body = False async def _recv(): nonlocal sent_body if not sent_body: sent_body = True return {"type": "http.request", "body": b"", "more_body": False} await asyncio.Event().wait() return {"type": "http.disconnect"} async def _send(_m): pass scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http", "path": "/wire/status/", "raw_path": b"/wire/status/", "root_path": "", "query_string": b"", "headers": [(b"host", b"desk.example")], "client": ("127.0.0.1", 50000), "server": ("desk.example", 80), } await _mem_handler(scope, _recv, _send) try: asyncio.run(_probe_mem_trap()) except Exception as _exc: _MEM_ASGI_ERROR = f"{type(_exc).__name__}: {_exc}" # Switch `default` to a temporary file-backed SQLite DB so ASGI's per-request # ThreadSensitiveContext worker threads read the exact seeded `desk/` schema & data. _TMP_DIR = tempfile.TemporaryDirectory(prefix="ch03_desk_") atexit.register(_TMP_DIR.cleanup) _DB_PATH = str(Path(_TMP_DIR.name) / "desk.sqlite3") # Force-close the :memory: SQLite connection (DatabaseWrapper.close() is a no-op # while is_in_memory_db() is True) before switching to the file-backed DB. settings.DATABASES["default"]["NAME"] = _DB_PATH connections.databases["default"]["NAME"] = _DB_PATH connections["default"].settings_dict["NAME"] = _DB_PATH connections.close_all() call_command("migrate", verbosity=0, interactive=False) seed(with_editor=True) connections.close_all() atexit.register(connections.close_all) rec = Recorder("ch03-handlers", "Django 6.1.3 on SQLite: ch03-handlers") # --------------------------------------------------------------------------- # Helpers for deterministic WSGI / ASGI invocation and thread labelling # --------------------------------------------------------------------------- def make_wsgi_environ( path_info: str = "/wire/status/", *, method: str = "GET", body: bytes = b"", host: str = "desk.example", script_name: str = "", ) -> dict[str, Any]: return { "REQUEST_METHOD": method, "SCRIPT_NAME": script_name, "PATH_INFO": path_info, "QUERY_STRING": "", "SERVER_NAME": host, "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "HTTP_HOST": host, "CONTENT_LENGTH": str(len(body)), "CONTENT_TYPE": "text/plain", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": io.BytesIO(body), "wsgi.errors": io.StringIO(), "wsgi.multithread": False, "wsgi.multiprocess": True, "wsgi.run_once": False, } def make_asgi_scope( path_str: str = "/wire/status/", *, method: str = "GET", host: str = "desk.example", root_path: str = "", ) -> dict[str, Any]: return { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method, "scheme": "http", "path": path_str, "raw_path": path_str.encode("ascii"), "root_path": root_path, "query_string": b"", "headers": [(b"host", host.encode("ascii"))], "client": ("127.0.0.1", 50000), "server": (host, 80), } def run_wsgi(handler: WSGIHandler, environ: dict[str, Any]) -> tuple[str, list[tuple[str, str]], bytes]: captured: dict[str, Any] = {} def start_response(status: str, headers: list[tuple[str, str]], exc_info=None): captured["status"] = status captured["headers"] = headers response = handler(environ, start_response) try: body = b"".join(response) finally: response.close() return captured["status"], captured["headers"], body async def run_asgi( handler: ASGIHandler, scope: dict[str, Any], *, body_chunks: list[bytes] | None = None, disconnect_after_body: bool = False, ) -> list[dict[str, Any]]: chunks = list(body_chunks) if body_chunks is not None else [b""] messages: list[dict[str, Any]] = [] idx = 0 async def receive(): nonlocal idx if idx < len(chunks): chunk = chunks[idx] idx += 1 return { "type": "http.request", "body": chunk, "more_body": idx < len(chunks), } if disconnect_after_body: return {"type": "http.disconnect"} # Wait until TaskGroup cancels listen_for_disconnect on RequestProcessed. await asyncio.Event().wait() return {"type": "http.disconnect"} async def send(msg: dict[str, Any]): messages.append(msg) await handler(scope, receive, send) return messages def norm_headers(headers: list[tuple[str, str]]) -> list[str]: out = [] for k, v in headers: if k.lower() == "x-desk-ms": out.append(f"{k}=") else: out.append(f"{k}={v}") return out # --------------------------------------------------------------------------- # Block 1: WSGIHandler vs ASGIHandler entry points & lifecycle # --------------------------------------------------------------------------- with rec.block("WSGIHandler vs ASGIHandler on GET /wire/status/"): wsgi_events: list[str] = [] def on_started(sender, **kwargs): key = "environ" if "environ" in kwargs else "scope" wsgi_events.append(f"signal request_started sender={sender.__name__} arg={key}") def on_finished(sender, **kwargs): wsgi_events.append(f"signal request_finished sender={sender.__name__}") signals.request_started.connect(on_started) signals.request_finished.connect(on_finished) try: wsgi_handler = WSGIHandler() captured_wsgi: dict[str, Any] = {} def start_resp(status, headers, exc_info=None): captured_wsgi["status"] = status captured_wsgi["headers"] = headers wsgi_events.append(f"start_response status={status!r} headers={len(headers)}") resp = wsgi_handler(make_wsgi_environ("/wire/status/"), start_resp) wsgi_events.append( f"handler returned {type(resp).__name__} _handler_class={resp._handler_class.__name__} closed={resp.closed}" ) body = b"".join(resp) resp.close() wsgi_events.append(f"after resp.close() closed={resp.closed} body={body.decode()}") rec.emit("WSGIHandler lifecycle:") for ev in wsgi_events: rec.emit(f" {ev}") rec.emit(f" headers={norm_headers(captured_wsgi['headers'])}") # Now ASGIHandler wsgi_events.clear() asgi_handler = ASGIHandler() # First check non-HTTP scope rejection try: asyncio.run(asgi_handler({"type": "websocket"}, None, None)) except ValueError as exc: rec.emit(f"ASGI non-http scope -> {type(exc).__name__}: {exc}") asgi_msgs = asyncio.run(run_asgi(asgi_handler, make_asgi_scope("/wire/status/"))) rec.emit("ASGIHandler lifecycle:") for ev in wsgi_events: rec.emit(f" {ev}") for m in asgi_msgs: if m["type"] == "http.response.start": hdrs = norm_headers([(k.decode("ascii"), v.decode("latin1")) for k, v in m["headers"]]) rec.emit(f" send http.response.start status={m['status']} headers={hdrs}") elif m["type"] == "http.response.body": rec.emit( f" send http.response.body bytes={len(m['body'])} more_body={m.get('more_body', False)} body={m['body'].decode()}" ) finally: signals.request_started.disconnect(on_started) signals.request_finished.disconnect(on_finished) with rec.block("ASGIHandler body spooling (RAM vs disk rollover) and client disconnect"): asgi_handler = ASGIHandler() async def probe_spool(limit: int, chunks: list[bytes]) -> tuple[bool, int]: idx = 0 async def recv(): nonlocal idx chunk = chunks[idx] idx += 1 return {"type": "http.request", "body": chunk, "more_body": idx < len(chunks)} with override_settings(FILE_UPLOAD_MAX_MEMORY_SIZE=limit): f = await asgi_handler.read_body(recv) rolled = getattr(f, "_rolled", False) data = f.read() f.close() return rolled, len(data) r_mem, n_mem = asyncio.run(probe_spool(1024, [b"a" * 512])) r_disk, n_disk = asyncio.run(probe_spool(1024, [b"a" * 600, b"b" * 600])) rec.emit(f"read_body limit=1024 payload=512B -> _rolled={r_mem} bytes_read={n_mem}") rec.emit(f"read_body limit=1024 payload=1200B -> _rolled={r_disk} bytes_read={n_disk}") # Disconnect during read_body async def probe_early_disconnect(): sent = [] called_handle_req = False orig = asgi_handler.get_response_async async def spy(req): nonlocal called_handle_req called_handle_req = True return await orig(req) asgi_handler.get_response_async = spy try: async def recv(): return {"type": "http.disconnect"} async def send(m): sent.append(m) await asgi_handler(make_asgi_scope("/wire/status/"), recv, send) finally: asgi_handler.get_response_async = orig return called_handle_req, len(sent) called_view, sent_cnt = asyncio.run(probe_early_disconnect()) rec.emit(f"early http.disconnect in read_body -> get_response_async_called={called_view} messages_sent={sent_cnt}") # Disconnect mid-request while view awaits fin_events: list[str] = [] def on_fin_disc(sender, **kwargs): fin_events.append(f"request_finished sender={sender.__name__}") signals.request_finished.connect(on_fin_disc) try: async def probe_mid_disconnect(): cancelled = False async def slow_view(request): nonlocal cancelled try: await asyncio.sleep(5) except asyncio.CancelledError: cancelled = True raise return HttpResponse("late") class TempUrls: urlpatterns = [path("slow/", slow_view)] with override_settings(ROOT_URLCONF=TempUrls, MIDDLEWARE=[]): h = ASGIHandler() step = 0 sent = [] async def recv(): nonlocal step step += 1 if step == 1: return {"type": "http.request", "body": b"", "more_body": False} await asyncio.sleep(0.01) return {"type": "http.disconnect"} async def send(m): sent.append(m) await h(make_asgi_scope("/slow/"), recv, send) return cancelled, len(sent) was_cancelled, sent_after = asyncio.run(probe_mid_disconnect()) rec.emit( f"mid-request http.disconnect -> view_cancelled={was_cancelled} messages_sent={sent_after} signals={fin_events}" ) finally: signals.request_finished.disconnect(on_fin_disc) # --------------------------------------------------------------------------- # Block 2: Middleware capabilities & BaseHandler.load_middleware on desk/ # --------------------------------------------------------------------------- with rec.block("desk/ MIDDLEWARE capabilities and BaseHandler.load_middleware construction"): rec.emit("index middleware mixin sync async hooks") for idx, mp in enumerate(settings.MIDDLEWARE): cls = import_string(mp) is_mixin = issubclass(cls, MiddlewareMixin) sc = getattr(cls, "sync_capable", True) ac = getattr(cls, "async_capable", False) hooks = [ h for h in ("process_request", "process_view", "process_template_response", "process_exception", "process_response") if hasattr(cls, h) ] hooks_s = ",".join(hooks) if hooks else "(direct __call__)" rec.emit(f"{idx:<5d} {cls.__name__:<28s} {str(is_mixin):<5s} {str(sc):<5s} {str(ac):<5s} {hooks_s}") for mode_label, is_async in (("WSGI load_middleware(is_async=False)", False), ("ASGI load_middleware(is_async=True)", True)): rec.emit("") rec.emit(f"{mode_label}:") adapt_log: list[str] = [] h = ASGIHandler.__new__(ASGIHandler) if is_async else WSGIHandler.__new__(WSGIHandler) orig_adapt = h.adapt_method_mode def spy_adapt(target_async, method, method_is_async=None, debug=False, name=None): res = orig_adapt(target_async, method, method_is_async=method_is_async, debug=debug, name=name) if res is not method: bridge = type(res).__name__ adapt_log.append(f" adapt({name or getattr(method, '__qualname__', type(method).__name__)}): {bridge}") return res h.adapt_method_mode = spy_adapt h.load_middleware(is_async=is_async) # Walk outward-to-inward chain to show exact layers rec.emit(f" adaptations ({len(adapt_log)}):") for line in adapt_log: rec.emit(f" {line}") rec.emit( f" hooks: _view_middleware={len(h._view_middleware)} " f"_template_response_middleware={len(h._template_response_middleware)} " f"_exception_middleware={len(h._exception_middleware)}" ) # Inspect each MiddlewareMixin instance's async_mode by walking closures layers: list[str] = [] node = h._middleware_chain seen = set() while node is not None and id(node) not in seen: seen.add(id(node)) if isinstance(node, (SyncToAsync, AsyncToSync)): layers.append(f"{type(node).__name__}(thread_sensitive={getattr(node, '_thread_sensitive', '-')})") node = node.func if isinstance(node, SyncToAsync) else node.awaitable continue wrapped = getattr(node, "__wrapped__", None) if wrapped is not None and getattr(node, "__name__", "") == "inner": # convert_exception_to_response wrapper node = wrapped continue if hasattr(node, "get_response"): am = getattr(node, "async_mode", None) suffix = f" async_mode={am}" if am is not None else " (sync-only)" if not getattr(node, "async_capable", False) else " (async-only)" layers.append(f"{type(node).__name__}{suffix}") node = node.get_response continue layers.append(getattr(node, "__qualname__", repr(node))) break rec.emit(" outer->inner chain:") for i, layer in enumerate(layers): rec.emit(f" {i:02d}. {layer}") with rec.block("load_middleware edge cases: MiddlewareNotUsed, None factory, invalid flags"): class DisabledMW: def __init__(self, get_response): raise MiddlewareNotUsed("disabled in this environment") def returns_none_factory(get_response): return None class NeitherModeMW: sync_capable = False async_capable = False def __init__(self, get_response): self.get_response = get_response # Expose on this module so import_string finds them cleanly via sys.modules["ch03_temp"] import types mod = types.ModuleType("ch03_edge_mw") mod.DisabledMW = DisabledMW mod.returns_none_factory = returns_none_factory mod.NeitherModeMW = NeitherModeMW sys.modules["ch03_edge_mw"] = mod try: with override_settings(MIDDLEWARE=["ch03_edge_mw.DisabledMW"]): h = WSGIHandler() inner = getattr(h._middleware_chain, "__wrapped__", h._middleware_chain) rec.emit(f"MiddlewareNotUsed -> silently skipped; top callable wraps {inner.__qualname__}") for path_str in ("ch03_edge_mw.returns_none_factory", "ch03_edge_mw.NeitherModeMW"): with override_settings(MIDDLEWARE=[path_str]): try: WSGIHandler() except Exception as exc: rec.emit(f"{path_str.split('.')[-1]} -> {type(exc).__name__}: {exc}") finally: sys.modules.pop("ch03_edge_mw", None) # --------------------------------------------------------------------------- # Block 3: Onion hook ordering & short-circuits # --------------------------------------------------------------------------- TRACE_EVENTS: list[str] = [] SHORT_CIRCUIT_MODE: str | None = None EXC_MODE: str | None = None RECOVER_IN_MIDDLE: bool = False def make_probe_middleware(name: str): class ProbeMW(MiddlewareMixin): def process_request(self, request): TRACE_EVENTS.append(f"{name}.process_request") if EXC_MODE == "inner_mw_crash" and name == "Inner": raise RuntimeError("crash inside Inner.process_request") if SHORT_CIRCUIT_MODE == "request" and name == "Middle": TRACE_EVENTS.append(f"{name}.process_request -> SHORT-CIRCUIT 200") return HttpResponse("short-circuited in process_request", status=200) return None def process_view(self, request, view_func, view_args, view_kwargs): TRACE_EVENTS.append(f"{name}.process_view") if SHORT_CIRCUIT_MODE == "view" and name == "Middle": TRACE_EVENTS.append(f"{name}.process_view -> SHORT-CIRCUIT 200") return HttpResponse("short-circuited in process_view", status=200) return None def process_template_response(self, request, response): TRACE_EVENTS.append(f"{name}.process_template_response") return response def process_exception(self, request, exception): TRACE_EVENTS.append(f"{name}.process_exception({type(exception).__name__})") if RECOVER_IN_MIDDLE and name == "Middle": TRACE_EVENTS.append(f"{name}.process_exception -> RECOVERED 503") return HttpResponse("recovered by Middle", status=503) return None def process_response(self, request, response): TRACE_EVENTS.append(f"{name}.process_response(status={response.status_code})") return response ProbeMW.__name__ = f"{name}MW" ProbeMW.__qualname__ = f"{name}MW" return ProbeMW class ProbeTemplateResponse(TemplateResponse): def render(self): TRACE_EVENTS.append("TemplateResponse.render") self.content = b"rendered-body" self._is_rendered = True return self class CustomBaseCrash(BaseException): pass def probe_view(request): TRACE_EVENTS.append("view.probe_view") if EXC_MODE == "404": raise Http404("story not found") if EXC_MODE == "403": raise PermissionDenied("editors only") if EXC_MODE == "400_bad": raise BadRequest("malformed query") if EXC_MODE == "400_suspicious": raise DisallowedHost("spoofed host header") if EXC_MODE == "500": raise RuntimeError("database desk on fire") if EXC_MODE == "base_exc": raise CustomBaseCrash("non-Exception BaseException") return ProbeTemplateResponse(request, "unused.html") import types as _types # noqa: E402 probe_mod = _types.ModuleType("ch03_probe_mw") probe_mod.OuterMW = make_probe_middleware("Outer") probe_mod.MiddleMW = make_probe_middleware("Middle") probe_mod.InnerMW = make_probe_middleware("Inner") sys.modules["ch03_probe_mw"] = probe_mod class ProbeUrls: urlpatterns = [path("probe/", probe_view)] PROBE_MW_LIST = [ "ch03_probe_mw.OuterMW", "ch03_probe_mw.MiddleMW", "ch03_probe_mw.InnerMW", ] with rec.block("Onion hook ordering: full pass vs process_request and process_view short-circuits"): with override_settings(MIDDLEWARE=PROBE_MW_LIST, ROOT_URLCONF=ProbeUrls): h = WSGIHandler() for label, mode in ( ("Full pass (TemplateResponse view)", None), ("Short-circuit in Middle.process_request", "request"), ("Short-circuit in Middle.process_view", "view"), ): TRACE_EVENTS.clear() SHORT_CIRCUIT_MODE = mode EXC_MODE = None RECOVER_IN_MIDDLE = False status, _, body = run_wsgi(h, make_wsgi_environ("/probe/")) rec.emit(f"{label} -> {status} ({body.decode()}):") for step, ev in enumerate(TRACE_EVENTS, 1): rec.emit(f" {step:02d}. {ev}") rec.emit("") # --------------------------------------------------------------------------- # Block 4: Per-layer exception walls & response_for_exception # --------------------------------------------------------------------------- class LogCaptureHandler(logging.Handler): def __init__(self): super().__init__() self.records: list[tuple[str, str]] = [] def emit(self, record): self.records.append((record.name, record.levelname)) with rec.block("Per-layer exception walls: convert_exception_to_response and response_for_exception"): got_exc = [0] def on_got_exc(sender, **kwargs): got_exc[0] += 1 signals.got_request_exception.connect(on_got_exc) log_cap = LogCaptureHandler() for lname in ("django.request", "django.security"): logging.getLogger(lname).addHandler(log_cap) logging.getLogger(lname).propagate = False try: with override_settings(MIDDLEWARE=PROBE_MW_LIST, ROOT_URLCONF=ProbeUrls, DEBUG=False): h = WSGIHandler() cases = [ ("View raises Http404", "404", False), ("View raises PermissionDenied", "403", False), ("View raises BadRequest", "400_bad", False), ("View raises DisallowedHost (SuspiciousOperation)", "400_suspicious", False), ("View raises RuntimeError", "500", False), ("View raises RuntimeError + Middle.process_exception recovers", "500", True), ("Inner.process_request raises RuntimeError", "inner_mw_crash", False), ] for label, exc_mode, recover in cases: TRACE_EVENTS.clear() log_cap.records.clear() got_exc[0] = 0 SHORT_CIRCUIT_MODE = None EXC_MODE = exc_mode RECOVER_IN_MIDDLE = recover status, _, _ = run_wsgi(h, make_wsgi_environ("/probe/")) rec.emit(f"{label} -> {status} got_request_exception={got_exc[0]} loggers={log_cap.records}") rec.emit(f" trace: {' -> '.join(TRACE_EVENTS)}") # DEBUG_PROPAGATE_EXCEPTIONS = True with override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True): TRACE_EVENTS.clear() EXC_MODE = "500" RECOVER_IN_MIDDLE = False try: run_wsgi(h, make_wsgi_environ("/probe/")) except RuntimeError as exc: rec.emit(f"DEBUG_PROPAGATE_EXCEPTIONS=True -> escaped {type(exc).__name__}: {exc}") # Non-Exception BaseException bypasses except Exception TRACE_EVENTS.clear() EXC_MODE = "base_exc" RECOVER_IN_MIDDLE = False try: run_wsgi(h, make_wsgi_environ("/probe/")) except CustomBaseCrash as exc: rec.emit(f"CustomBaseCrash(BaseException) -> escaped uncaught: {exc}") finally: signals.got_request_exception.disconnect(on_got_exc) for lname in ("django.request", "django.security"): logging.getLogger(lname).removeHandler(log_cap) logging.getLogger(lname).propagate = True SHORT_CIRCUIT_MODE = None EXC_MODE = None RECOVER_IN_MIDDLE = False # --------------------------------------------------------------------------- # Block 5: Sync/async crossing census & thread-lane traces # --------------------------------------------------------------------------- async def async_ping_view(request): return HttpResponse("pong", content_type="text/plain") def sync_ping_view(request): return HttpResponse("pong", content_type="text/plain") from newsroom import views as newsroom_views # noqa: E402 class BridgeUrls: urlpatterns = [ path("ping/async/", async_ping_view), path("ping/sync/", sync_ping_view), path("wire/status/", newsroom_views.live_wire_status), path("editions/front/", newsroom_views.edition_front), ] DEFAULT_7_MW = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] DESK_8_MW = list(settings.MIDDLEWARE) COALESCED_8_MW = DEFAULT_7_MW + ["desk.middleware.TimingHeaderMiddleware"] PURE_ASYNC_MW = ["desk.middleware.AsyncAuditMiddleware"] PING_PONG_MW = [ "desk.middleware.AsyncAuditMiddleware", "desk.middleware.TimingHeaderMiddleware", "desk.middleware.AsyncAuditMiddleware", ] def describe_target(fn: Any) -> str: # Unwrap partials/wrappers cleanly to a readable deterministic label. if hasattr(fn, "__self__") and fn.__self__ is not None: cls_name = type(fn.__self__).__name__ fn_name = getattr(fn, "__name__", type(fn).__name__) return f"{cls_name}.{fn_name}" wrapped = getattr(fn, "__wrapped__", None) if wrapped is not None and getattr(fn, "__name__", "") == "inner": return f"exc_wall({describe_target(wrapped)})" qn = getattr(fn, "__qualname__", None) if qn: return qn return type(fn).__name__ def classify_hop(target: str) -> str: if any(k in target for k in ("reset_queries", "close_old_connections", "reset_urlconf", ".close", "Signal")): return "shell" if any(k in target for k in ("QuerySet", "acount", "afirst", "count", "fetch", "edition_front", "sync_ping_view", "async_ping_view", "live_wire_status")): return "view_orm" return "middleware" @contextmanager def instrument_bridges(main_role: str): """Count and trace every SyncToAsync and AsyncToSync invocation with deterministic thread labels.""" events: list[tuple[str, str, str, str, str, bool | str]] = [] thread_map: dict[int, str] = {threading.get_ident(): main_role} worker_seq = 0 loop_seq = 0 def label_thread(tid: int, kind: str) -> str: nonlocal worker_seq, loop_seq if tid in thread_map: return thread_map[tid] if kind == "async_loop": loop_seq += 1 lbl = f"async-loop-{loop_seq}" else: worker_seq += 1 lbl = f"sync-worker-{worker_seq}" thread_map[tid] = lbl return lbl orig_s2a = SyncToAsync.__call__ orig_a2s = AsyncToSync.__call__ orig_s2a_th = SyncToAsync.thread_handler orig_a2s_mw = AsyncToSync.main_wrap async def traced_s2a(self, *args, **kwargs): caller = label_thread(threading.get_ident(), "worker") target = describe_target(self.func) slot = len(events) events.append(("sync_to_async", classify_hop(target), target, caller, "?", self._thread_sensitive)) # Record target thread inside thread_handler self._trace_slot = slot try: return await orig_s2a(self, *args, **kwargs) finally: if hasattr(self, "_trace_slot"): delattr(self, "_trace_slot") def traced_s2a_th(self, loop, exc_info, task_context, func, *args, **kwargs): slot = getattr(self, "_trace_slot", None) if slot is not None: dest = label_thread(threading.get_ident(), "worker") kind, cat, target, caller, _, ts = events[slot] events[slot] = (kind, cat, target, caller, dest, ts) return orig_s2a_th(self, loop, exc_info, task_context, func, *args, **kwargs) def traced_a2s(self, *args, **kwargs): caller = label_thread(threading.get_ident(), "worker") target = describe_target(self.awaitable) slot = len(events) events.append(("async_to_sync", classify_hop(target), target, caller, "?", "-")) self._trace_slot = slot try: return orig_a2s(self, *args, **kwargs) finally: if hasattr(self, "_trace_slot"): delattr(self, "_trace_slot") async def traced_a2s_mw(self, call_result, exc_info, task_context, context, awaitable): slot = getattr(self, "_trace_slot", None) if slot is not None: dest = label_thread(threading.get_ident(), "async_loop") kind, cat, target, caller, _, ts = events[slot] events[slot] = (kind, cat, target, caller, dest, ts) return await orig_a2s_mw(self, call_result, exc_info, task_context, context, awaitable) SyncToAsync.__call__ = traced_s2a SyncToAsync.thread_handler = traced_s2a_th AsyncToSync.__call__ = traced_a2s AsyncToSync.main_wrap = traced_a2s_mw try: yield events finally: SyncToAsync.__call__ = orig_s2a SyncToAsync.thread_handler = orig_s2a_th AsyncToSync.__call__ = orig_a2s AsyncToSync.main_wrap = orig_a2s_mw def probe_config(handler_kind: str, mw_list: list[str], url_path: str): with override_settings(MIDDLEWARE=mw_list, ROOT_URLCONF=BridgeUrls): if handler_kind == "ASGI": h = ASGIHandler() # Warm URL resolver once so first-request URL import doesn't distort anything asyncio.run(run_asgi(h, make_asgi_scope(url_path))) with instrument_bridges("event-loop") as evs: msgs = asyncio.run(run_asgi(h, make_asgi_scope(url_path))) status = msgs[0]["status"] return status, evs else: h = WSGIHandler() run_wsgi(h, make_wsgi_environ(url_path)) with instrument_bridges("wsgi-thread") as evs: status_s, _, _ = run_wsgi(h, make_wsgi_environ(url_path)) status = int(status_s.split()[0]) return status, evs CONFIGS = [ ("ASGI pure-async (AsyncAuditMW)", "ASGI", PURE_ASYNC_MW), ("ASGI coalesced (7 built-ins + Timing bottom)", "ASGI", COALESCED_8_MW), ("ASGI desk/ stack (Timing at #2)", "ASGI", DESK_8_MW), ("ASGI default 7 MiddlewareMixin", "ASGI", DEFAULT_7_MW), ("ASGI ping-pong (Async/Timing/Async)", "ASGI", PING_PONG_MW), ("WSGI desk/ stack", "WSGI", DESK_8_MW), ] with rec.block("Mode-crossing census on zero-DB async ping (/ping/async/)"): rec.emit("configuration status total s2a a2s shell mw view_orm workers") detailed_traces: dict[str, list] = {} for label, kind, mw_list in CONFIGS: status, evs = probe_config(kind, mw_list, "/ping/async/") detailed_traces[label] = evs s2a = sum(1 for e in evs if e[0] == "sync_to_async") a2s = sum(1 for e in evs if e[0] == "async_to_sync") shell_n = sum(1 for e in evs if e[1] == "shell") mw_n = sum(1 for e in evs if e[1] == "middleware") vo_n = sum(1 for e in evs if e[1] == "view_orm") dests = sorted({e[4] for e in evs if e[4] not in ("event-loop", "wsgi-thread", "?")}) rec.emit( f"{label:<44s} {status:<6d} {len(evs):<5d} {s2a:<3d} {a2s:<3d} {shell_n:<5d} {mw_n:<2d} {vo_n:<8d} {','.join(dests) or 'none'}" ) with rec.block("Mode-crossing census on desk/ live_wire_status (/wire/status/, 3 async ORM queries)"): rec.emit("configuration status total s2a a2s shell mw view_orm workers") wire_traces: dict[str, list] = {} for label, kind, mw_list in CONFIGS: status, evs = probe_config(kind, mw_list, "/wire/status/") wire_traces[label] = evs s2a = sum(1 for e in evs if e[0] == "sync_to_async") a2s = sum(1 for e in evs if e[0] == "async_to_sync") shell_n = sum(1 for e in evs if e[1] == "shell") mw_n = sum(1 for e in evs if e[1] == "middleware") vo_n = sum(1 for e in evs if e[1] == "view_orm") dests = sorted({e[4] for e in evs if e[4] not in ("event-loop", "wsgi-thread", "?")}) rec.emit( f"{label:<44s} {status:<6d} {len(evs):<5d} {s2a:<3d} {a2s:<3d} {shell_n:<5d} {mw_n:<2d} {vo_n:<8d} {','.join(dests) or 'none'}" ) with rec.block("Exact crossing sequence on /ping/async/ (default 7 built-ins vs desk/ vs coalesced vs WSGI)"): for label in ( "ASGI default 7 MiddlewareMixin", "ASGI desk/ stack (Timing at #2)", "ASGI coalesced (7 built-ins + Timing bottom)", "ASGI pure-async (AsyncAuditMW)", "WSGI desk/ stack", ): evs = detailed_traces[label] noun = "crossing" if len(evs) == 1 else "crossings" rec.emit(f"{label} ({len(evs)} {noun}):") for idx, (bridge, cat, target, caller, dest, ts) in enumerate(evs, 1): rec.emit(f" {idx:02d}. {bridge:<13s} [{cat:<10s}] {caller:<13s} -> {dest:<13s} ts={str(ts):<5s} {target}") rec.emit("") with rec.block("WSGI -> async live_wire_status CurrentThreadExecutor round-trip (/wire/status/)"): evs = wire_traces["WSGI desk/ stack"] rec.emit(f"WSGI desk/ stack on /wire/status/ ({len(evs)} crossings):") for idx, (bridge, cat, target, caller, dest, ts) in enumerate(evs, 1): rec.emit(f" {idx:02d}. {bridge:<13s} [{cat:<10s}] {caller:<13s} -> {dest:<13s} ts={str(ts):<5s} {target}") with rec.block("ThreadSensitiveContext isolation, SQLite :memory: trap, ATOMIC_REQUESTS and AsyncToSync guards"): rec.emit(f"ASGIHandler + SQLite ':memory:' on /wire/status/ -> {_MEM_ASGI_ERROR}") # 1. Prove two concurrent ASGI requests get distinct ThreadSensitiveContext worker threads async def probe_concurrent_tsc(): barrier = threading.Barrier(2, timeout=5) seen_tids: dict[str, int] = {} def sync_work(tag: str): seen_tids[tag] = threading.get_ident() barrier.wait() return threading.get_ident() async def one_req(tag: str): async with asgiref.sync.ThreadSensitiveContext(): t1 = await asgiref.sync.sync_to_async(sync_work, thread_sensitive=True)(tag) t2 = await asgiref.sync.sync_to_async(threading.get_ident, thread_sensitive=True)() return t1 == t2, t1 (same_a, tid_a), (same_b, tid_b) = await asyncio.gather(one_req("A"), one_req("B")) loop_tid = threading.get_ident() return same_a, same_b, (tid_a != tid_b), (tid_a != loop_tid and tid_b != loop_tid) same_a, same_b, distinct_ab, off_loop = asyncio.run(probe_concurrent_tsc()) rec.emit( f"concurrent ThreadSensitiveContext -> reqA_sticky={same_a} reqB_sticky={same_b} " f"distinct_worker_threads={distinct_ab} off_event_loop={off_loop}" ) # 2. ATOMIC_REQUESTS=True + async view -> RuntimeError in BaseHandler.make_view_atomic orig_atomic = connections.settings["default"]["ATOMIC_REQUESTS"] connections.settings["default"]["ATOMIC_REQUESTS"] = True try: with override_settings(MIDDLEWARE=[], ROOT_URLCONF=BridgeUrls, DEBUG_PROPAGATE_EXCEPTIONS=True): h = ASGIHandler() try: asyncio.run(run_asgi(h, make_asgi_scope("/ping/async/"))) except RuntimeError as exc: rec.emit(f"ATOMIC_REQUESTS=True + async view -> {type(exc).__name__}: {exc}") finally: connections.settings["default"]["ATOMIC_REQUESTS"] = orig_atomic # 3. Calling async_to_sync directly from the event-loop thread -> RuntimeError async def bad_sync_call_on_loop(): async def inner(): return 1 return async_to_sync(inner)() try: asyncio.run(bad_sync_call_on_loop()) except RuntimeError as exc: rec.emit(f"async_to_sync inside event loop -> {type(exc).__name__}: {exc}") rec.write()