GH-141148: Ensure decimal.getcontext() returns fresh copy.#151953
Open
nascheme wants to merge 2 commits into
Open
GH-141148: Ensure decimal.getcontext() returns fresh copy.#151953nascheme wants to merge 2 commits into
nascheme wants to merge 2 commits into
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Ensure that
decimal.getcontext()returns a per-task copy of thedecimal.Contextso that mutations are isolated between asyncio tasks and threads whensys.flags.thread_inherit_contextis set.This change is required because
decimal.Contextinstances are mutable. Thecontextvars.Contextobject 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 thedecimal.Context()instance.This differs from GH-146482 as follows:
ctx_vars_originreference. Instead, we are just using a 64-bit integer counter here to track depth._pydecimaland_decimal.ccode, since it has to track the depth on its Context instance