Skip to content

gh-161387: Check the type of the decimal context ContextVar - #161399

Open
0z5a wants to merge 8 commits into
python:mainfrom
0z5a:fix-decimal-contextvar-type
Open

0z5a wants to merge 8 commits into
python:mainfrom
0z5a:fix-decimal-contextvar-type

Conversation

@0z5a

@0z5a 0z5a commented Nov 5, 2026 •

Copy link
Copy Markdown

Refs gh-161387.

_decimal.current_context() returned whatever the internal decimal_context ContextVar held, without checking PyDecContext_Check. Callers immediately cast the value to PyDecContextObject *, so setting the variable to a non-context (for example 1) segfaults on the next decimal operation.

Raise TypeError from current_context() when the stored value is not a context. CURRENT_CONTEXT already propagates NULL, so callers fail cleanly.

Tests: new CContextAPItests.test_current_context_var_wrong_type. Built current main (5aa2f705) with the C _decimal extension (libmpdec 2.5.1): the reproducer exits with SIGSEGV (rc=139) before the change and raises TypeError after. The new test and the full test_decimal suite (751 tests, 9 skipped) pass.

Comment thread Modules/_decimal/_decimal.c Resolved
Comment thread Lib/test/test_decimal.py Resolved
Comment thread Lib/test/test_decimal.py Resolved
@0z5a

0z5a commented Nov 5, 2026

Copy link
Copy Markdown
Author

Addressed in c10e2e7: the error now reports the received type (expected a Context instance, got int), and the test now finds the matching context vars, saves reset tokens, restores them via a helper, and only then asserts the TypeError.

Comment thread Lib/test/test_decimal.py Resolved

@sobolevn sobolevn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, assert that after the exception is handled: context var must not be cleared. Its value must not change

Comment thread Modules/_decimal/_decimal.c Resolved
Comment thread Modules/_decimal/_decimal.c Resolved
Comment thread Lib/test/test_decimal.py Resolved
0z5a and others added 3 commits November 5, 2026 12:37
Co-authored-by: sobolevn <mail@sobolevn.me>
Co-authored-by: sobolevn <mail@sobolevn.me>
Comment thread Lib/test/test_decimal.py Resolved
@skirpichev skirpichev added needs backport to 3.14 bugs and security fixes needs backport to 3.15 bugs and security fixes labels Nov 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting merge needs backport to 3.14 bugs and security fixes needs backport to 3.15 bugs and security fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants