← Back to Pull requests

Allow nesting ThreadSensitiveContext. #596

Merged
cjrh merged 4 files (840 lines) on Oct 23, 2026 06:38 UTC
View on GitHub
cjrh cjrh commented on Oct 04, 2026 01:26 UTC
Author

See this comment on trac.

I have been working on this in communication with @carltongibson.

In this PR, we're aiming to allow a caller of ThreadSensitiveContext to specify an executor. This will allow Django's transaction.atomic, in an async context (i.e., async with ...), to provide a new thread executor so that the context inside the transaction.atomic will use a separate thread, and therefore separate Connection, for transaction handling. This thread (connection) separation prevents the transaction isolation issues that would occur without using separate connections.

Regarding AI usage there was a lot. I discussed this issue and the core considerations in some detail at a Django sprint, and I have carefully worked through the subtleties myself (like the CurrentThreadExecutor reentrancy concerns, wow), but I have used AI extensively to examine this problem and various potential solutions, and to write the tests which I subsequently reviewed.

One of the alternative solutions I looked at was a new force_new_thread parameter for the ThreadSensitiveContext, like so:

ThreadSensitiveContext(force_new_thread: bool)

and the implementation was similar to this PR in the use of the self._old_executor to "hide" an existing executor. Then, the actual new thread would get created by the existing logic in SyncToAsync.__call__ (because now there would be no existing outer thread). The logic falls through to the # Create new thread executor in current context branch.

The current PR design is similar but has an advantage: on the caller side (the caller provides the executor), The caller may choose to re-use executors, in a small pool say. On the Django side, this pool of executors could retain connections , assuming the CONN_MAX_AGE allowed it. So that is the idea behind allowing a caller to provide an executor. In this case, inside SyncToAsync.__call__ we hit the branch of # Re-use thread executor in current context since that is what gets populated in the ThreadSensitiveContext.__aenter__.

Diff: 840 lines (+831 / -9) across 4 files Reviewer: carltongibson Review duration: 27671m
All Vouch review confidence checks passed
Residual risk 0.09 = Change Risk (0.47) × (1 − Review Confidence (0.81)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.47 · 840 lines diff across 4 files
0.47
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.76 · 5 substantive comment(s)
0.76
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
81%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Real PR Conversation Timeline
13 items
cjrh cjrh commented on Oct 04, 2026 02:08 UTC
Author

Referring to the django issue number (#33882) in the PR title is probably incorrect here, I'm guessing? I don't see that in other PRs. How should I change it?

cjrh cjrh commented on Oct 04, 2026 13:32 UTC
Author

@carltongibson I added you as collaborator to my fork so you can also push commits to this branch

carltongibson carltongibson commented on Oct 04, 2026 13:40 UTC
Contributor

Great. Thanks @cjrh 👍

carltongibson carltongibson commented on Oct 08, 2026 08:34 UTC
Contributor

Hey @cjrh — got one for you that (probably) needs to be (initially) addressed here (if we can).

We end up with three rule for using async atomic:

1. Only the task opening the outer atomic block can make use of nested atomic. (Now enforced in https://github.com/django/django/pull/22074)
2. "Avoid subtasks inside an atomic block" (Just advice in the docs)
3. If you do use them, enforce structured concurrency. (Use TaskGroup, or await gather() so subtasks complete before exiting the atomic block.)

Now 3 isn't currently enforced. So anything can happen, depending on when the subtask runs. It might join in with the transaction. It might use the same connection before we close it. It might try to schedule work on a shutdown worker. It might get itself a fresh worker and a connection (which we might or might not properly clean up 🤷)

So, I'm not too worried about this: they already ignored our advice twice (both 2 and 3 say "Don't do this!") BUT I wonder if marking the TSC as closed somehow on the way out would allow us to error loudly in this kind of case?

cjrh cjrh commented on Oct 08, 2026 14:22 UTC
Author

BUT I wonder if marking the TSC as closed somehow on the way out would allow us to error loudly in this kind of case?

I understand what you're describing. I'll give it some thought. Are you thinking something along the lines of preventing a second __aenter__ on a TSC?

carltongibson carltongibson commented on Oct 08, 2026 14:38 UTC
Contributor

Argh! On the phone now... 🫠

I'm thinking that a subtask that tried to use sync to async could raise if the wrapping atomic (and so tsc) had already exited, so enforcing the use structured concurrency requirement.

(I can paste a code sketch when I'm on the computer to communicate better)

carltongibson carltongibson commented on Oct 09, 2026 09:21 UTC
Contributor

Hey @cjrh, I posted a write up of the approach here. There I mention the three rules we suggested:

1. Only the task opening the transaction can use atomic
2. Do avoid subtasks.
3. But if you must use them enforce structure concurrency.

The question is, can we error sensibly if someone ignores 2 and 3?

async with transaction.atomic():
    # So you insist on using subtasks? 
    # These are OK: both tasks complete, inside the transaction, before the block exits.
    async with asyncio.TaskGroup() as tg:
        tg.create_task(Log.objects.acreate(msg="one"))
        tg.create_task(Log.objects.acreate(msg="two"))


    # BUT: This could happen at ANY time 🔥
    await asyncio.create_task(Log.objects.acreate(msg="three"))

Can we catch the last case there, if it's scheduled after atomic.__aexit__?

I consider this a nice to have, so we can add it after the main PR, if at all. (Can we do it? Is it worth the cost? — Not sure on either right now.)

Make sense?

carltongibson carltongibson commented on Oct 19, 2026 12:43 UTC
Contributor

I added a test for the case above to the Django PR https://github.com/django/django/pull/22074/changes/b42b87d4140f0d434990af9b90ace395304b7760 (it passes)

carltongibson carltongibson commented on Oct 19, 2026 14:43 UTC
Reviewer

OK, close @cjrh — This is good.

I looked at the tests. See edits. I just want to go over the comments in sync.py, and then the README.

🎁

carltongibson carltongibson commented on Oct 20, 2026 09:58 UTC
Contributor

Hey @cjrh — Right, I've gone over everything and pushed the edits that I think are appropriate. Can I ask you to take a look and let me know if you have feedback, and if you're happy with them or not?

carltongibson carltongibson commented on Oct 20, 2026 10:01 UTC
Contributor

@jacobtylerwalls This is ready to go to my eye. Just pinging you in case you want to have a look.

carltongibson carltongibson approved these changes on Oct 23, 2026 06:34 UTC
Approved Reviewer

Approved these changes.

Reviewers
Assignees
cjrh cjrh
Labels
risk: low confidence: 81.3% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 47.4% (MEDIUM) · Higher = larger blast radius
47.4%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 81.3% · Lower = rushed or shallow review
81.3%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 8.9% · Safe to merge
8.9%
Repository