Skip to content

Python implementation of Decimal can hang in floor division #140036

Done

Description

@serhiy-storchaka

Bug report

# import decimal
import _pydecimal as decimal

_unbounded_dec_context = decimal.getcontext().copy()
_unbounded_dec_context.prec = decimal.MAX_PREC
_unbounded_dec_context.Emax = decimal.MAX_EMAX
_unbounded_dec_context.Emin = decimal.MIN_EMIN
_unbounded_dec_context.traps[decimal.Inexact] = 1 # sanity check
decimal.setcontext(_unbounded_dec_context)

x = decimal.Decimal('1')
y = x // 1

The C implementation evaluates the last line instantly, but the Python implementation hangs for a long time (infinitely?). The modulus operation has the same behavior.

cc @tim-one

Linked PRs

Activity

  1. added
    type-bug
    stdlib
    3.13
    3.14
    3.15
    on Oct 13, 2025
  2. picnixz commented on Oct 13, 2025

    @picnixz
    Member

    In _divide, it tries to compute 10 ** context.prec which in this case is 10 ** 999999999999999999 to compare to q. However, taking the base-10 logarithm on both sides may result in a precision loss and have an incorrect result.

  3. efimov-mikhail commented on Oct 13, 2025

    @efimov-mikhail
    Member

    In _divide, it tries to compute 10 ** context.prec which in this case is 10 ** 999999999999999999 to compare to q. However, taking the base-10 logarithm on both sides may result in a precision loss and have an incorrect result.

    But why it's possible to calculate this in the C implementation?
    Those implementations aren't the same in terms of precision?

  4. picnixz commented on Oct 13, 2025

    @picnixz
    Member

    It's possible because the backend actually stores the number of digits of the divmod result. So you can just do some q->digits > ctx->prec check without having to re-raise to the power of 10. (I believe the implementations are identical for the precision handling; it just that the C implementation doesn't have some $10^{prec}$ check because it knows the number of digits in q already while the Python implementation doesn't).

  5. skirpichev commented on Oct 13, 2025

    @skirpichev
    Member

    Maybe just:

    if q <= 0 or _math.log10(q) < context.prec:
        ...
  6. picnixz commented on Oct 13, 2025

    @picnixz
    Member

    We could speed-up some cases by relying on .bit_length() to get the maximum number of the next power of 2. We can switch to that estimation if we know in advance that 10**context.prec will take a long time (for instance, on my machine 10 ** 1000000 becomes slow, so anything below can be directly computed).

    if q <= 0 or _math.log10(q) < context.prec:

    For most cases, it would be fine, but _math.log10 may either overestimate or underestimate if we exceed 15 digits. So I don't think it would sufficient here.

  7. serhiy-storchaka commented on Oct 13, 2025

    @serhiy-storchaka
    MemberAuthor

    Oh, a similar issue was already discussed in #118027 and #118164.

  8. skirpichev commented on Oct 13, 2025

    @skirpichev
    Member

    For most cases, it would be fine, but _math.log10 may either overestimate or underestimate if we exceed 15 digits.

    I assume special handling of integers, available in math.log*():

    cpython/Modules/mathmodule.c

    Lines 2302 to 2313 in 52996aa

    if (x == -1.0 && PyErr_Occurred()) {
    if (!PyErr_ExceptionMatches(PyExc_OverflowError))
    return NULL;
    /* Here the conversion to double overflowed, but it's possible
    to compute the log anyway. Clear the exception and continue. */
    PyErr_Clear();
    x = _PyLong_Frexp((PyLongObject *)arg, &e);
    assert(e >= 0);
    assert(!PyErr_Occurred());
    /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
    result = func(x) + func(2.0) * e;
    }

  9. picnixz commented on Oct 13, 2025

    @picnixz
    Member

    Wouldn't we still have a problem with the exact computation of the log as the result is a float?
    For instance, with a context precision of 30 and x = decimal.Decimal('1e30') - 1, we have $q = 999999999999999999999999999999$. However math.log10(q) == 30 so the condition log10(q) < ctx.prec would fail, whereas q < 10 ** 30 would succeed (that's where we underestimate the log10 because of the inexact return type)

  10. self-assigned this
    on Oct 13, 2025
  11. skirpichev commented on Oct 13, 2025

    @skirpichev
    Member

    You are right, it should be something like q.bit_length() < 1 + context.prec*3.32192809488736.

  12. 32 remaining items

  13. removed
    3.15
    on Oct 23, 2026
  14. added 3 commits that reference this issue on Oct 23, 2026
  15. picnixz commented on Oct 28, 2026

    @picnixz
    Member

    I've asked Claude to investigate how to fix the modulo operation but there were other cases that could likely be slow. More generally, I want to see if we can defer 10**k computations when k is very large as much as possible.

  16. removed their assignment
    on Oct 28, 2026
  17. added 2 commits that reference this issue on Oct 28, 2026
  18. skirpichev commented on Nov 24, 2026

    @skirpichev
    Member

    Maybe we could backport this? In principle, this could lead to DoS in some environments.

    If we do this, fix eventually will reach alternative implementations, using CPython's stdlib, e.g. PyPy or GraalPy.

    Edit: can be applied to v3.11 cleanly.

  19. StanFromIreland commented on Nov 24, 2026

    @StanFromIreland
    Member

    If we do this, fix eventually will reach alternative implementations, using CPython's stdlib, e.g. PyPy or GraalPy.

    I can cherry-pick this to PyPy, would you like to open a PR against py3.12 there?

  20. skirpichev commented on Nov 24, 2026

    @skirpichev
    Member

    I can cherry-pick this to PyPy, would you like to open a PR against py3.12 there?

    Yes, this can be applied to v3.12 cleanly, as for v3.11. That was noted before. But what about GraalPy, for example?

    I also suspect that deviations from the stdlib increase maintenance burden for alternative implementations.

  21. added 2 commits that reference this issue on Dec 3, 2026
  22. skirpichev commented on Dec 3, 2026

    @skirpichev
    Member

    Ok, it seems nobody willing to backport this...

    Everything merged, I'm closing this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions