Allow nesting ThreadSensitiveContext. #596
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?
@carltongibson I added you as collaborator to my fork so you can also push commits to this branch
Great. Thanks @cjrh 👍
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?
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?
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)
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?
I added a test for the case above to the Django PR https://github.com/django/django/pull/22074/changes/b42b87d4140f0d434990af9b90ace395304b7760 (it passes)
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.
🎁
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?
@jacobtylerwalls This is ready to go to my eye. Just pinging you in case you want to have a look.
Approved these changes.
carltongibson
cjrh
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 thetransaction.atomicwill use a separate thread, and therefore separateConnection, 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
CurrentThreadExecutorreentrancy 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_threadparameter for theThreadSensitiveContext, like so:and the implementation was similar to this PR in the use of the
self._old_executorto "hide" an existing executor. Then, the actual new thread would get created by the existing logic inSyncToAsync.__call__(because now there would be no existing outer thread). The logic falls through to the# Create new thread executor in current contextbranch.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 contextsince that is what gets populated in theThreadSensitiveContext.__aenter__.