| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
Sorry, something went wrong.
We need a per-task copy of decimal.Context() so that mutations are isolated between asyncio tasks and threads using sys.flags.thread_inherit_context. This is done by adding a "depth" counter to PyContext and copying the decimal.Context() instance whenever it doesn't match the depth of the current PyContext.
|
Checking the performance impact of this, for asyncio tasks. I'm not concerned about threads since starting a thread should be much more expensive than copying decimal.Context. Here is an analysis from GPT 5.6: Clang -O3, normal GIL build:
So the incremental first-use isolation cost was about 220–300 ns per task here. A deliberately tiny task doing nothing except accessing decimal slowed by about 14%; realistic tasks should amortize that quickly. There is also a steady-state cost of roughly 6 ns per current-context lookup from checking the depth. A basic decimal-addition benchmark did not show a measurable slowdown, although code-layout noise makes such tiny differences difficult to isolate. The C decimal Context grew from 120 to 128 bytes, and each contextvars.Context from 80 to 88 bytes on this build. Generalizing beyond tasks: the copy occurs once for each distinct copied contextvars.Context that first accesses an inherited decimal context. Arbitrary callbacks that capture separate contexts can therefore also each incur one copy, but asyncio task resumptions explicitly reuse the task’s existing context. |
Sorry, something went wrong.
| Back | FazBrowse Home | New Git URL |
Ensure that decimal.getcontext() returns a per-task copy of the decimal.Context so that mutations are isolated between asyncio tasks and threads when sys.flags.thread_inherit_context is set.
This change is required because decimal.Context instances are mutable. The contextvars.Context object uses an immutable data structure (HAMT) to store variable bindings. That ensures each task has its own set of contextvar bindings. However, it doesn't help if the contextvar value itself is mutated.
This is an alternative to GH-146482. In this PR, we add a "depth" counter to PyContext, incremented every time we copy the HAMT. Then, the decimal.Context() instance can use this to determine that getcontext() needs to copy the instance. This ensures each thread or asyncio task has it's own copy of the decimal.Context() instance.
This differs from GH-146482 as follows: