Agent Wranglers

ARC-70Required

Stop integer arithmetic from overflowing

Give every count, amount and size a type wide enough for its largest valid value. Arithmetic on values from outside fails with an error instead of wrapping around or losing digits.

How to do it

Fixed-size integers wrap silently in many languages, so a large total turns negative. JavaScript numbers lose exact digits above Number.MAX_SAFE_INTEGER, which is 2^53 - 1. Check outside numbers against a minimum and a maximum when you parse input once at the boundary. Use checked operations, such as Math.addExact in Java or checked_add in Rust, or a big integer type such as BigInt. Money follows hold money as integer minor units everywhere.

Examples

Java example

// Bad: two large totals wrap around to a negative number
int total = basketTotal + shippingTotal;

// Good: throws ArithmeticException instead of wrapping
long total = Math.addExact(basketTotal, shippingTotal);

TypeScript example

// Bad: above 2^53 - 1 the last digits are silently wrong
const ledgerTotal = rows.reduce((sum, row) => sum + row.amount, 0);

// Good: BigInt keeps every digit, and the input is checked first
if (!rows.every(row => Number.isSafeInteger(row.amount))) throw new AmountOutOfRange();
const ledgerTotal = rows.reduce((sum, row) => sum + BigInt(row.amount), 0n);

Plain text example

// Good: checked_add returns None on overflow, so the error is explicit
let total = basket_total.checked_add(shipping_total).ok_or(Error::AmountOutOfRange)?;

How to check

A test feeds each numeric input its maximum, its maximum plus one and a negative value. It expects the maximum to work and the other two to be refused with an error. Linters flag unchecked casts and arithmetic, such as Clippy arithmetic_side_effects and cast_possible_truncation for Rust, or -ftrapv and -fsanitize=integer for C.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/architecture/data-shapes/integer-overflow">Agent Wranglers architecture playbook</a>. In code you write, add a comment next to it with the same link.