Description
I'd like to propose that we deprecate checkpoint_if_cancelled()
in favor of a synchronous function that I'm thinking of as trio.check_cancelled()
(happy to take suggestions on the name, or move into hazmat). This would raise Cancelled
if the current scope is cancelled, and do nothing otherwise. i.e., it is a pure cancel point, not a schedule point, not even a schedule point if we're cancelled.
This becomes possible due to some recent or pending changes:
- Consider relaxing the await-always-checkpoints rule to await-always-checkpoints-on-non-error #474, which permits the sync-color by saying we don't need to checkpoint before raising an exception (I'm assuming Cancelled counts as an exception for the purposes of that rule)
- Delay deciding which cancel scope a Cancelled exception belongs to #901, which means the Cancelled-raising path is just
raise Cancelled._init()
- Refactor cancellation system to eagerly propagate effective state #958, which makes it fast to see if we're cancelled or not
And I think would have benefits for:
- Either optimize yield_briefly or de-optimize yield_briefly_no_cancel #70, by implementing efficient
checkpoint()
asawait cancel_shielded_checkpoint(); check_cancelled()
- Propagating cancellation through threads #606, allowing
run_sync_in_worker_thread
functions to call check_cancelled() occasionally without messing with portals (because it's synchronous! and if/when Refactor cancellation system to eagerly propagate effective state #958 lands I think we can make the check_cancelled() operation sufficiently thread-safe) - iirc Discussion: Cancel-myself-now operation? cancel-and-wait-for-it-to-finish operation? #658 indicated some user interest in a sync-colored raise-cancelled operation?
Possible downside: a sync-colored function called from an async function can now call check_cancelled() and wind up raising Cancelled. Previously that couldn't happen. My feeling is that "functions that do something off-the-wall might raise an exception their caller wasn't expecting" is hardly a new problem, but maybe there's some aspect of what we'd be giving up here that I'm missing.