Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ All notable changes to SkillEvaluator are documented in this file.
inspection rather than observed unsafe behavior. The Tier 3 guide lists the
forms that are not read. Both the host checker and the bundled Harbor
verifier apply the fix.
- The calculator reference skill refuses Boolean constants, bounds exponentiation
Comment thread
rng1995 marked this conversation as resolved.
Resolved
before computing it, and reports non-real or oversized results instead of hanging
or raising a cryptic conversion error.

## 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 expressions return a real number of at most 1000 decimal digits; larger, infinite, or non-real arithmetic results return an error.
Comment thread
rng1995 marked this conversation as resolved.
Resolved

## 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,58 @@
ast.UAdd: operator.pos,
}

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


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 _int_digit_count(n: int) -> int:
return len(str(abs(n)))


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 _int_digit_count(value) > MAX_RESULT_DIGITS:
Comment thread
rng1995 marked this conversation as resolved.
Resolved
raise ValueError("result is too large")
return value


def _apply(op, *args):
try:
return _check_result(op(*args))
except OverflowError:
raise ValueError("result is too large") from None


def _pow(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 +81,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
58 changes: 57 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 All @@ -42,6 +43,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",
["10% of 50 + 5", "5 km to miles please", "1.2.3 km to miles"],
Expand All @@ -53,3 +73,39 @@ 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)"],
)
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"


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