Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,16 @@ All notable changes to SkillEvaluator are documented in this file.
find-to-xargs pipeline under a literal temporary root: these pipelines now
score Security `1.0` instead of a destructive-command finding. Unknown
producers, joined shell words and link traversal keep the finding.
- The calculator reference skill refuses Boolean constants and caps whole-number
results at 1000 digits; results that involve a division or a decimal number
stay within the floating-point range (about 1.8e308), as before. It checks
exponentiation before computing it, so integer results of 1001 to 4300
digits, which printed before, now return
`Error: result is too large`. Larger, infinite or non-real results report an
error instead of hanging or raising a cryptic conversion error. The limits
apply to intermediate values as well as the final result, so
`10**1000 - 10**1000`, which printed `Result: 0` before, now returns
`Error: result is too large` because each power has 1001 digits.

## 1.0.1 - 2026-11-17

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ For conversions:
- No symbolic algebra (no variables, no equations).
- Only supports basic arithmetic operators: `+`, `-`, `*`, `/`, `**`, `%`, parentheses.
- Unit conversions are limited to: celsius/fahrenheit, miles/km, kg/lbs, meters/feet.
- Arithmetic results are limited to 1000 decimal digits for whole-number math, and to the floating-point range (about 1.8e308) when a division or a decimal number is involved; larger, infinite, or non-real arithmetic results return an error. These limits apply to intermediate values as well as the final result, so an expression with a small final value can still be rejected: `10**1000 - 10**1000` returns `Error: result is too large` because each power has 1001 digits.

## Troubleshooting

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""Calculator — safe arithmetic evaluation and unit conversions."""

import ast
import math
import operator
import re
import sys
Expand All @@ -20,6 +21,74 @@
ast.UAdd: operator.pos,
}

# Keep printed integers below Python's default int-to-str limit (4,300 digits).
MAX_RESULT_DIGITS = 1000
MAX_INTEGER_RESULT = 10**MAX_RESULT_DIGITS - 1


def _log10_int(n: int) -> float:
"""Return log10(n) for a positive int without converting the whole value to float."""
text = str(n)
lead = text[:12]
significand = int(lead) / 10 ** (len(lead) - 1)
return math.log10(significand) + len(text) - 1


def _integer_pow_exceeds_digit_budget(base: object, exp: object) -> bool:
if type(base) is not int or type(exp) is not int or exp <= 0:
return False
abs_base = abs(base)
if abs_base <= 1:
return False
# |base| >= 2 gives at least exp * log10(2) > 0.3 * exp digits, so a large
# exponent is over budget without the float estimate, which would overflow.
if exp >= 4 * MAX_RESULT_DIGITS:
return True
digits_minus_one = exp * _log10_int(abs_base)
Comment thread
chrisknvidia marked this conversation as resolved.
Resolved
return not math.isfinite(digits_minus_one) or digits_minus_one >= MAX_RESULT_DIGITS


def _check_result(value):
if isinstance(value, complex):
raise ValueError("result is not a real number")
if isinstance(value, float) and not math.isfinite(value):
raise ValueError("result is too large")
if type(value) is int and abs(value) > MAX_INTEGER_RESULT:
raise ValueError("result is too large")
return value


def _outside_float_range(value: object) -> bool:
if type(value) is not int:
return False
try:
float(value)
except OverflowError:
return True
return False


def _apply(op, *args):
try:
return _check_result(op(*args))
except OverflowError:
# A float operation first converts its int operands, which can overflow
# whatever the size of the result, as in 0.5**(10**400) or (10**400)*0.0.
if any(type(arg) is float for arg in args) and any(_outside_float_range(arg) for arg in args):
raise ValueError("number is outside the floating-point range") from None
raise ValueError("result is too large") from None


def _pow(base, exp):
if type(base) is int and type(exp) is int and exp < 0 and base != 0:
# |result| < 10**-1000 underflows to 0, as 2**-2000 already does.
if _integer_pow_exceeds_digit_budget(base, -exp):
return 0.0
return _apply(operator.truediv, 1, base**-exp)
if _integer_pow_exceeds_digit_budget(base, exp):
Comment thread
rng1995 marked this conversation as resolved.
Resolved
raise ValueError("result is too large")
return _apply(operator.pow, base, exp)


def safe_eval(expr: str) -> float:
"""Evaluate arithmetic expression using AST — no eval()."""
Expand All @@ -28,18 +97,24 @@ def safe_eval(expr: str) -> float:
def _eval(node):
if isinstance(node, ast.Expression):
return _eval(node.body)
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.Constant):
if type(node.value) not in (int, float):
raise ValueError(f"Unsupported value: {type(node.value).__name__}")
return _check_result(node.value)
if isinstance(node, ast.BinOp):
op = OPERATORS.get(type(node.op))
if op is None:
raise ValueError(f"Unsupported operator: {type(node.op).__name__}")
return op(_eval(node.left), _eval(node.right))
left = _eval(node.left)
right = _eval(node.right)
if isinstance(node.op, ast.Pow):
return _pow(left, right)
return _apply(op, left, right)
if isinstance(node, ast.UnaryOp):
op = OPERATORS.get(type(node.op))
if op is None:
raise ValueError(f"Unsupported unary: {type(node.op).__name__}")
return op(_eval(node.operand))
return _apply(op, _eval(node.operand))
raise ValueError(f"Unsupported node: {type(node).__name__}")

return _eval(tree)
Expand Down
95 changes: 94 additions & 1 deletion tests/test_reference_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@
CALC = Path(__file__).resolve().parents[1] / "src/skillevaluator/tier3/reference_skills/calculator/scripts/calc.py"


def _calc(expression: str) -> subprocess.CompletedProcess[str]:
def _calc(expression: str, timeout: float = 3) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[sys.executable, str(CALC), expression],
check=False,
capture_output=True,
text=True,
timeout=timeout,
)


Expand Down Expand Up @@ -50,6 +51,25 @@ def test_conversions_and_percentages_accept_signed_numbers(expression: str, expe
assert result.stdout.strip() == expected


@pytest.mark.parametrize(
("expression", "expected"),
[
("2 + 3 * 4", "Result: 14"),
("(100 - 25) / 3", "Result: 25"),
("2 ** 10", "Result: 1024"),
("2**64", "Result: 18446744073709551616"),
("2**-2", "Result: 0.25"),
("5 miles to km", "5 miles = 8.047 km"),
("10 kg to lbs", "10 kg = 22.05 lbs"),
],
)
def test_documented_examples_and_exact_powers_are_unchanged(expression: str, expected: str) -> None:
result = _calc(expression)

assert result.returncode == 0, result.stderr
assert result.stdout.strip() == expected


@pytest.mark.parametrize(
"expression",
[
Expand All @@ -68,3 +88,76 @@ def test_input_beyond_a_conversion_or_percentage_is_rejected(expression: str) ->
assert result.stdout == ""
assert result.stderr.startswith("Error: ")
assert "Traceback" not in result.stderr


@pytest.mark.parametrize(
"expression",
[
"9**9**9",
"10**10**10",
"10.0**400",
"1e308*10",
"2**4000",
"2**(10**309)",
"2**(10**999)",
pytest.param(hex(10**1000), id="first-oversized-integer"),
pytest.param("0x" + "f" * 4000, id="oversized-hex-literal"),
],
)
def test_oversized_results_are_rejected_quickly(expression: str) -> None:
result = _calc(expression)

assert result.returncode == 1
assert result.stdout == ""
assert result.stderr.strip() == "Error: result is too large"


@pytest.mark.parametrize(
("expression", "expected"),
[
("2**-(10**309)", "Result: 0"),
("(-3)**-(10**400)", "Result: 0"),
("(10**999)**-1", "Result: 0"),
("2**-5000", "Result: 0"),
("1**-(10**309)", "Result: 1"),
("(-1)**-3", "Result: -1"),
],
)
def test_huge_negative_integer_exponents_underflow(expression: str, expected: str) -> None:
result = _calc(expression)

assert result.returncode == 0, result.stderr
assert result.stdout.strip() == expected


@pytest.mark.parametrize("expression", ["0.5**(10**400)", "(10**400)*0.0"])
def test_int_operands_outside_float_range_are_reported(expression: str) -> None:
result = _calc(expression)

assert result.returncode == 1
assert result.stdout == ""
assert result.stderr.strip() == "Error: number is outside the floating-point range"


def test_non_real_results_are_rejected() -> None:
result = _calc("(-8)**(1/3)")

assert result.returncode == 1
assert result.stdout == ""
assert result.stderr.strip() == "Error: result is not a real number"


def test_boolean_constants_are_rejected() -> None:
result = _calc("True+True")

assert result.returncode == 1
assert result.stdout == ""
assert result.stderr.strip() == "Error: Unsupported value: bool"


def test_division_by_zero_message_is_unchanged() -> None:
result = _calc("1/0")

assert result.returncode == 1
assert result.stdout == ""
assert result.stderr.strip() == "Error: division by zero"
Loading