I Just Wanted to Roll D20

·25 min read·Lateleoi
I Just Wanted to Roll D20

The first version of this bot shipped in 2018. It had dice notation and some flavor messaging, decent for the time and better than most Discord bots. Then life happened… I moved, left the internet for a while, and lost the source code. When I came back, I rewrote the whole thing, and this time I just kept going.

This post is what eight years of kept going looks like.

Before the 2018 version, before the notation, the flavor, or any of the bells and whistles, there was the line anyone writing a Discord bot starts with:

await ctx.send(f"You rolled {random.randint(1, 20)}!")

Bots shipped with hundreds of mediocre commands typically have some form of that line. Mine did. That random.randint is still in the code, technically, buried in roll_dice() under everything that grew on top of it. The last living descendant of the original one-liner.

Today, a single /roll parses dice notation, dice inside dice, and evaluates them through an AST-allowlisted arithmetic parser (no eval anywhere, we’ll get to that). It compiles optional success conditions into reusable predicates, computes probability distributions using arbitrary-precision rationals, scores luck as roll percentiles, and then logs the whole affair to SQLite on a separate thread. The surrounding cog handles saved macros, autocomplete, reroll-from-history, and per-server feature toggles.

Over time, I justified forty small decisions, each one defensible the day I made it. Then I looked up and realized I was maintaining an arbitrary-precision probability engine with a JavaScript twin. Whoops.

Here’s how that happened, decision by decision.

Note

If you’d rather poke at this than read about it: the engine runs live, right now, on the dashboard! The source for everything quoted here is on GitHub. (lite version: dashboard and databases stripped, engine intact). All outputs in this post are real, pulled from a seeded run. Your dice might differ, your probabilities won’t.

A regex that learned recursion

Dice notation looks innocent: 2d6+3. Some dice, a d, some sides, and some arithmetic. At its heart, the parser is still just a regex and a callback; that part has barely changed since 2018:

DICE_PATTERN_STR = r'(?:[\d.]|\([^)]+\))*[dD](?:[\d.]|\([^)]+\))+(?:(?:k[hl]?|[hl])(?:[\d.]|\([^)]+\))*)?'

The callback simply matches a die, then rolls it:

def roll_callback(match):
    ...
    _, rolls = roll_dice(num_dice, num_sides)
    ...
    return str(total)

sanitized = re.sub(DICE_PATTERN_STR, roll_callback, dice_string, flags=re.IGNORECASE)

2d6+3 goes in, 7+3 comes out, and whatever remains is plain arithmetic for the next stage. One pass handles the dice, another handles the math, and the two concerns never really touch:

You rolled: `[6 + 1 = 7] + 3` = **10!**

Then I decided I wanted dice inside the dice. 2d(5+1d5): roll a d5, add five, and that becomes your number of sides. Since the sides expression contains another die, the callback hands it straight back to the parser:

if any(x in raw_sides for x in 'dD'):
    sides_resolved, sides_breakdown = parse_and_roll(raw_sides, sort)

parse_and_roll calling parse_and_roll. Dice are allowed in the count, the sides, and even the keep clause, with every nested layer resolving before the layer above it rolls.

The keep syntax is where breakdown strings earn their keep. 4d6kh3 rolls four dice and keeps the highest three, with braces marking the dropped one:

You rolled: `kh3[3 + 2 + 2 + {2} = 7]` = **7!**

And 4d6kl1 (keep the lowest) cheerfully discards three sixes just to save a one:

You rolled: `kl1[{6} + {6} + {6} + 1 = 1]` = **1!**

There’s a limit, of course. The pattern matches parenthesized sub-expressions with [^)]+, which cannot span nested parentheses, so deeply nested constructs eventually fall over. When a roll fails and the input looks like that, you’ll hit this fun little easter egg:

await ctx.followup.send("My abacus just filed a restraining order. "
                        "Try something like 2d(5+1d5) instead")

I personally love it when error messages double as documentation for exactly where the parser gives up.

Math you can’t eval()

Once every die has been substituted with its rolled total, the rest is arithmetic: 7+3, 2*(3+4), or maybe a caret for exponents. The lazy option is eval(). The lazy option is also how a dice bot acquires a remote code execution vulnerability. To avoid that, I used an allowlist:

ALLOWED_OPERATORS = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
                     ast.Div: op.truediv, ast.Pow: op.pow,
                     ast.USub: op.neg, ast.UAdd: op.pos}
ALLOWED_NODES = [ast.Expression, ast.BinOp, ast.UnaryOp, ast.Constant,
                 *ALLOWED_OPERATORS.keys()]

I parse the expression into a syntax tree, walk it, and reject anything not on the guest list. No function calls, names, or attribute access; only numeric constants and seven operators:

tree = ast.parse(expression, mode='eval')
for node in ast.walk(tree):
    if type(node) not in ALLOWED_NODES:
        raise ValueError(f"Invalid expression: Disallowed node {type(node).__name__}")

A recursive-descent walk over the surviving nodes computes the result. I smooth over two dialect quirks first: users often write ^ where Python wants **, and 2(3+4) where Python expects 2*(3+4):

expression = str(expression).replace('^', '**')
sanitized_string = re.sub(r'(?<=[\d)])\(', '*(', sanitized_string)

The security story ends up being “allowlist the syntax tree,” which beats regex-filtering raw input on every axis I care about. And because the dice pass already replaced every die with a number, the arithmetic parser never has to know dice exist.

How lucky was that, exactly?

Flavor messaging was already in the 2018 bot. “Nat 20!” and other notable results. Cute, but the rewrite’s escalation was subtler: I wanted the bot to know how lucky a roll was, not just how notable.

The natural definition here is a percentile. Given the distribution of what you rolled, your luck score is P(X ≤ result), the probability of doing as badly or worse. Zero is the worst possible roll, 0.5 is the median, and 1.0 means you topped out:

pmf = await asyncio.to_thread(expression_to_pmf, user_input)
p_better = p_at_least(pmf, int_total)
p_worse = p_at_most(pmf, int_total)
luck_score = float(p_worse)  # P(X <= result): 0 = worst, 0.5 = median, 1 = best

That trailing comment is the most expensive line in the codebase. Computing P(X ≤ result) means knowing the probability of every outcome; the full distribution of the exact expression. One UX nicety later, and suddenly my dice roller had to become a probability engine.

Because there’s no cache anywhere in the codebase, the bot pays for that engine on every single roll. Every /roll, including the four-thousandth 1d20 of a busy Friday night, spins up a thread, enumerates the entire distribution as fresh Fractions, sums two tail probabilities, throws the whole table away, just to print one funny italic line in subtext.

Worth it, would do again. Roll the mode of 4d6kh3 and you get a 13, the single most likely outcome, and even that sits at the 64.5th percentile.

The flavor tiers came along for free because they’re just tail probabilities with jokes attached. Roll the maximum (an 18, exactly 7/432, a 1-in-62 event), and the engine picks a one-liner:

The maximum possible outcome - only a 1.62% chance!
Legendary. 1 in 62 rolls go this well (1.62%)
Couldn't have rolled higher if you tried (1.62%)
You're welcome... 1.62% odds

It’s one in 62, exactly, because everything underneath is exact. Which brings me to the next decision.

PMFs and the tyranny of floats

A probability mass function (PMF) is in short a lookup table: every possible outcome of an expression mapped to its probability. For a d20, that’s twenty rows of 1/20. For 2d6+3, it’s eleven rows shifted up by three. The engine’s job is deriving that table for whatever a user types.

First of two structural decisions: those probabilities are Fractions (arbitrary-precision rationals), not floats.

PMF = dict[int, Fraction]  # outcome -> probability

def uniform_die(sides: int) -> PMF:
    p = Fraction(1, sides)
    return {face: p for face in range(1, sides + 1)}

Because floats lie. 1/3 in floating point isn’t actually a third, and those lies compound with every operation. A luck score is a claim about rarity; when someone rolls a 1-in-2,000 outcome, “approximately 0.00049999” isn’t the energy the moment deserves. Fraction keeps an exact numerator and denominator regardless of size, so the 1-in-62 mentioned above is actually 7/432, only rounded for display.

Of course, exactness has its limits. mean, variance, and stdev are cast to float the moment they leave the engine, and a target probability is only printed as a fraction when the denominator is convenient to read:

frac_str = f" = {p_hit.numerator}/{p_hit.denominator}" if p_hit.denominator <= 10000 else ""

So the real position isn’t “floats lie.” It’s “rationals all the way through, floats faces the user at display, and exactness when it’s legible.”

The second decision: distributions combine by convolution. If X and Y are independent, the PMF of X+Y is every pair of outcomes, multiplied and summed at their combined value:

def convolve(a: PMF, b: PMF) -> PMF:
    result: PMF = defaultdict(Fraction)
    for av, ap in a.items():
        for bv, bp in b.items():
            result[av + bv] += ap * bp
    return dict(result)

Conceptually, that’s the whole engine. NdM is a uniform die convolved with itself N−1 times. Every + in an expression is a convolution; every - is a convolution with a negated distribution; every constant is a distribution concentrated on one value. One pairwise multiply-and-sum covers all the arithmetic the parser can produce. P(2d6 = 7) comes out as exactly 1/6, which is the textbook answer.

Keep-highest, exactly

This is where the textbook runs out of pages and scope creep gets fun.

D&D players roll 4d6kh3 for stats: four dice, keep the best three. You can’t compute that with convolutions because keeping the best three couples the dice, AKA they’re no longer independent and the beautiful pairwise math stops applying. Brute force would enumerate all 6^4 = 1,296 raw outcomes. That’s fine for 4d6, but the same people also roll 20d6, and 6^20 ≈ 3.7 × 10^15 raw outcomes is… not so fine.

However, dice kept or dropped together are only distinguished by their sorted multiset, meaning which values came up and how many times, regardless of order. The number of raw sequences behind each multiset is exactly the multinomial coefficient N! / (c₁! · c₂! · …), where cᵢ counts how many dice landed on face i. Python hands you both pieces:

denom = Fraction(1, sides ** num_dice)
for combo in combinations_with_replacement(range(1, sides + 1), num_dice):
    ways = math.factorial(num_dice)
    for face in set(combo):
        ways //= math.factorial(combo.count(face))
    kept_sum = sum(sorted(combo, reverse=highest)[:keep])
    result[kept_sum] += ways * denom

By enumerating sorted outcomes and weighting each by how many of the M^N raw sequences produce it, I can sum the dice being kept. This gives exact probabilities for keep-highest using the same Fraction arithmetic as everything else, and complexity collapses:

Expression Raw outcomes Sorted multisets
4d6kh3 6^4 = 1,296 C(9,4) = 126
10d6 6^10 ≈ 6.0 × 10^7 C(15,10) = 3,003
20d6 6^20 ≈ 3.7 × 10^15 C(25,20) = 53,130

For 20d6, that’s a factor of about seventy billion. P(4d6kh3 = 18) still comes out as 7/432 (21/1296), the number printed in every D&D stat table since 1974.

Discord can’t figure out visuals

Now that we have the exact distribution, we have to show it in Discord. That means dealing with monospace text, 2,000-character message limits, and people reading on phones. /odds 4d6kh3 target >=15 produces the following (real output, unabridged):

Range:     3 … 18
Mean:     12.24
Median:   12
Mode:      13  (13.27%)
Quartiles: 10 | 12 | 14
Std dev:  ±2.847

 3 |   0.08%
 4 | ▍  0.31%
 5 | █▏  0.77%
 6 | ██▍  1.62%
 7 | ████▍  2.93%
 8 | ███████▏  4.78%
 9 | ██████████▌  7.02%
10 | ██████████████▏  9.41%
11 | █████████████████▏ 11.42%
12 | ███████████████████▍ 12.89%
13 | ████████████████████ 13.27%
14 | ██████████████████▌ 12.35%
15 | ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ 10.11%
16 | ▒▒▒▒▒▒▒▒▒▒▒░  7.25%
17 | ▒▒▒▒▒▒░  4.17%
18 | ▒▒░  1.62%

P(`>=15`) = 23.15% = 25/108
Odds: 1 in 4.32

The bars are block characters at eighth-block resolution, and the ▒ shading marks the outcomes your target accepts. The bar renderer lives in a shared engine module, imported by both the exact view and the simulation view. /odds 4d6kh3 and /simulate 4d6kh3 x100000 use the same function, so the bars mean the same thing when you eyeball one against the other.

Distributions with too many rows get bucketed into ranges first. The CDF view handles them differently, sampling evenly across the support so the table stays readable:

if len(items) > max_rows:
    step = len(items) // max_rows
    items = items[::step][:max_rows]

The CDF table itself is exactly / at-most / at-least, with ◄ marking rows your target hits (abridged here; the real one carries all sixteen rows):

Roll | Exactly | At most | At least
─────┼─────────┼─────────┼─────────
  13 |  13.27% |  64.51% |  48.77%
  14 |  12.35% |  76.85% |  35.49%
  15 |  10.11% |  86.96% |  23.15% ◄
  16 |   7.25% |  94.21% |  13.04% ◄
  17 |   4.17% |  98.38% |   5.79% ◄
  18 |   1.62% | 100.00% |   1.62% ◄

(The CDF is built from a running total kept in a dict named cum_lookup, commented at source as, “it’s cumulative but I am immature”. I’m keeping the comment. Trust me, there’s worse.)

Because everything underneath is exact, the target line is a fraction: 25/108, odds 1 in 4.32.

Both views live in the same message. Summary and CDF use first-class Discord components, so switching between them is a single tap that edits the message in place. A green Roll button below fires an actual roll, scores it against the distribution you’re currently looking at, and logs it. After a five-minute timeout, the buttons grey themselves out.

The views are deliberately packed like sardines. Six summary stats, sixteen histogram rows at eighth-block resolution, sixteen more rows of CDF, and the target as an exact fraction. All inside a 2,000-character budget, you can drop into a channel mid-session without pushing everyone’s phone screen off the rails. You can even hide it from others with whisper: True to send an ephemeral message instead.

Everything target-shaped in this section, the ▒ shading, the ◄ markers, the verdict lines, runs off one compiled predicate. >=15, 8-12, !even, and in {18, 19, 20} each compile once into a closure and a human-readable string:

if m := re.fullmatch(r'(?:between\s+)?(-?\d+(?:\.\d+)?)\s*-\s*(-?\d+(?:\.\d+)?)', t):
    lo, hi = sorted((float(m.group(1)), float(m.group(2))))
    return (lambda x: lo <= x <= hi), f"{lo:g}-{hi:g}"

Ranges sort their own bounds, so 12-8 and 8-12 are treated as the same target, and ! wraps anything in negation. The whole DSL is about twenty lines, and every consumer just calls the closure.

Ceilings? It’s a feature

Exactness has a price, and convolution is where you pay it. The double loop is O(|a|·|b|) in outcomes, and something like 9999d999999999 would like a word. To prevent the bot from crashing, the engine refuses before allocating anything by estimating the total cost up front. For NdM, the convolution work is a sum of arithmetic-series terms and the support grows predictably, so the estimate is exact:

def _estimate_sum_dice_cost(num_dice: int, sides: int) -> tuple[int, int]:
    if num_dice < 1:
        return 1, 0
    final_size = num_dice * (sides - 1) + 1
    work = 0
    current_size = sides
    for _ in range(num_dice - 1):
        work += current_size * sides
        current_size += sides - 1
        if work > MAX_CONVOLUTION_WORK:
            return final_size, work  # bail early, caller will reject
    return final_size, work

If it’s too big, you’re told politely with actual numbers, then pointed toward the right tool:

raise ValueError(f"{num_dice}d{sides} has {final_size:,} possible outcomes! "
                 f"(limit: 100,000) Try /simulate")

The ceilings act like a gradient with their own geography. A size check in the uniform-die constructor, a pre-flight cost estimate in sum_dice, a work check and a post-hoc size check inside the convolution, and a multiset count in keep_dice. There are even hard caps on dice and sides way down in the roller. Input limits descend in steps with how expensive the command is: /roll accepts 1,024 characters, /simulate 512, and /odds 256.

At the far end of /roll’s allowance sits the shortest refusal in the codebase:

await ctx.followup.send("I'm....not rolling this", ephemeral=True)

As the amount of work to keep everything together became too difficult to maintain solo, error messages started becoming load-bearing UX. Once computationally heavy expressions point you to /simulate, the routing layer becomes obvious:

Command Promise When the math is too expensive
/roll always rolls rolls anyway, luck scoring silently skipped
/odds exact or nothing refuses, with a cost estimate
/simulate always answers approximates but never refuses

9999d999999999: /roll shrugs and rolls 9,999 dice, /odds declines with a number in the trillions, and /simulate grinds until its time budget expires, returning partial results under a warning banner.

There’s a second reason /odds declines, and it’s less dignified than cost. The roller and the exact engine don’t actually share a parser; the latter is weaker.

The roller’s parser is the regex-and-callback from the top of this post, recursive and rolling dice as it reads. The engine can’t use any of that because substituting a die with its rolled total is precisely the move a probability engine cannot make. Consequently, the odds module grew its own reader:

_TERM_RE = re.compile(r'(\d*)[dD](\d+)(?:(k[hl]?|[hl])(\d+))?')

This is paired with a loop that accumulates dice terms and integer constants with a pending-sign state variable. It handles NdM, one keep clause, and +/- between terms. However, nesting, implicit multiplication, or 2d(5+1d5) are unsupported, as the engine speaks a strict dialect of a language the roller is fluent in.

And /roll’s graceful degradation is a try/except block with a confession:

except (ValueError, NotImplementedError, TypeError, SyntaxError,
        ZeroDivisionError, KeyError):
    pass  # PMF too complex for exact computation - skip luck/flavor

The luck feature became expensive enough to make itself optional at runtime. I’d love to claim this was foresight, but it wasn’t. That comment grew a command economy around it.

It’s also doing double duty. Half the time that pass fires, it isn’t “the math was too expensive”, instead NotImplementedError from the second parser, but that’s less fun to declare. Luck scoring degrades silently, and the comment lets you believe it was about complexity. After the JavaScript port, I ended up with four parsers for one notation, two deliberately dumber than the others.

While reviewing my own code, I noticed MAX_DICE_FOR_KEEP = 30 sits defined and unused in the odds module, superseded by the multiset threshold in keep_dice(). If you look hard enough, you can find more. Maybe I’ll comment them out one day.

Monte Carlo? Where!

/simulate is where everything too big for exact math gets routed: roll the expression up to a million times and report what actually happened.

Since a Discord bot is a single event loop with response deadlines, the simulation runs on a thread under a hard eight-second budget. The clock is checked once per percent of trials rather than once per trial, because a million time.monotonic() calls are their own denial of service:

check_every = max(1, trials // 100)
for i in range(trials):
    if i % check_every == 0 and time.monotonic() > deadline:
        return results, True   # partial results, flagged, still delivered

If you hit the budget mid-run, you’ll still get results! Just from however many trials finished, accompanied by a warning banner. I want to apologize in advance if you were checking whether your one-million-ogre army survived the battle, only to find 567,000 magically vanished.

The modifier parameter is a generalized advantage: simulate 1d20 x100000 modifier 2 rolls each trial twice and keeps the higher. Elven accuracy, the Lucky feat, and every “roll twice, keep best” house rule all collapse into one integer.

When estimating a hit rate from N trials, the honest move is a Wilson confidence interval, not the Wald formula everyone memorizes. Wald misbehaves at the extremes, producing intervals that dip below zero for rare events or wobble where they shouldn’t. Wilson stays bounded and sane:

def wilson_ci(successes: int, trials: int, z: float = 1.96) -> tuple[float, float]:
    p = successes / trials
    denom = 1 + z * z / trials
    center = (p + z * z / (2 * trials)) / denom
    margin = (z * math.sqrt(p * (1 - p) / trials + z * z / (4 * trials * trials))) / denom
    return max(0.0, center - margin), min(1.0, center + margin)

Here is the result of a seeded run, a hundred thousand simulated d20s against target >=15. The true answer is 30%:

hits: 30,157 / 100,000  (30.16%)
Wilson 95% CI: 29.87% – 30.44%
longest hit streak: 8    (theory says ~10)
longest miss streak: 31  (theory says ~32)

Because 100k trials also answer the question people actually ask: “Am I cursed, or just unlucky?” I added streak analysis: run lengths of hits and misses, plus the theoretical ceiling. For n trials with hit probability p, the expected longest streak of hits is about log(n)/log(1/p); a million fair coin flips should top out around 20 in a row. In the example above, the observed streaks sit right where theory says they should.

BATTLE READY

At this point, I needed insurance. The question shifted from “can the engine do this” to “how do I know it isn’t lying.” Exact probabilities are a strong claim, and strong claims need a test suite. I wrote one, and it says more about this project than any feature in it.

The fuzzers generate random expressions, nested dice, keep clauses, exponents, and implicit multiplication across thousands of seeds, then thrown at the engine. Here’s what passing looks like:

EXPECTED = (ValueError, NotImplementedError, ZeroDivisionError, SyntaxError)
...
except EXPECTED:
    continue  # a clean refusal is a pass

A refusal is a pass. The suite encodes the thesis of the ceilings section as a constant: the engine is allowed to say no, and saying no correctly is a success.

You don’t need to ask, of course there’s a time limit on refusals:

HOSTILE_TIME_LIMIT = 2.0  # seconds, refusals must be effectively instant

Refuse means refuse fast. That assertiveness came after watching the bot think about 9^9^9. The hostile-input roster reads like a YouTube griefing tutorial: (9^9)^9, 2^999999999, 2d6; print('hi'), import os.

Every hostile-input test since then is a thank-you note. safe_eval: hostile input is refused (issue #1), breakdown display regressions (issue #2). Somewhere out there are the people those numbers belong to. Issue #1 came from somebody who figured out they could exponentiate the bot into a coma (me).

Then the suite proves the two halves of the engine describe the same universe:

pmf = expression_to_pmf(expr)
for _ in range(AGREEMENT_ROLLS):
    total, _ = roll_expression(expr)
    assert int(total) in pmf

25,000 rolls, every one landing inside its own exact distribution. The keep-highest math is checked against brute force on all 54 small combinations. The 7/432 from earlier is pinned in an assert.

My favorite is the structural test. To verify that breakdown strings don’t lie (3+2d6 ➜ 3+[6 + 1 = 7]), the suite strips brackets and parentheses in a fixpoint loop until nothing changes, then asserts the operator sequence survived:

def op_sequence(text: str) -> list[str]:
    prev = None
    while prev != text:
        prev = text
        text = re.sub(r'\[[^\[\]]*\]', '', text)
        text = re.sub(r'\([^()]*\)', '', text)
    ...

What’s this about pytest? This testing is a manually invoked harness with a scoreboard that prints BATTLE READY when everything passes.

All of this rigor lives on one side of the project. The suite proves the roller and the odds engine agree, but it says nothing about the rest of the system, and it does not cross borders.

The bot becomes a platform

I just kept yearning for more small decisions, and justified with more buttons, interactions, and data points. Saved macros with Discord-native autocomplete, random tables with weighted entries, reroll-from-history, and per-server feature toggles. When commands became too cumbersome for these features, the next step was a website.

Every roll is logged (expression, breakdown, result, luck score), and that last field is the tell: the data was the point all along. I used one SQLite file per server, stored in a folder named after the server’s ID. The dashboard serves the log back as interactable data containing most rolls, luckiest, unluckiest, top rolls, and most-used expressions:

self.cursor.execute("CREATE INDEX IF NOT EXISTS idx_roll_luck ON roll_history(luck_score)")

Logging exact percentiles means the dashboard can chart whether a server runs “hot” over time, and you can frame that 2d10000 ➜ 2 roll on the wall.

The exactness doesn’t extend to everything, though. The roll-history endpoint paginates, and its count function knows about fewer filters than the query does:

# Note: get_roll_count only supports user/date filters, so `total`
# can overestimate when other filters are active. Fine for now.

With the backend set up, it was time to start the frontend. I quickly realized Flask isn’t async, so the dashboard is a Quart app on stilts, running as a coroutine sibling on the bot’s event loop:

await asyncio.gather(serve(app, config), bot.start(get_token()))

This application is one process, with the web server and the Discord bot as two arguments to gather.

The engine that computes 7/432 ships a page counter that can overestimate, and the code knows it. There’s also a macro-edit endpoint that doesn’t pretend to work:

return {"error": "Editing is not wired up yet"}, 501

A present route that declines is that same “half-feature” species as the orphaned functions in the odds module, you’ll meet them later. Less importantly, there are the standard per-command cooldowns: rolls at three per five seconds, simulations at two per ten.

Then came the part that finally scared me. I’m not even talking about self-hosting, docker, nginx, cloudflare, or the oauth full stack. An odds engine in a browser meant allowing anything running Chrome to run arbitrary expressions directly on bare metal: the same expressions whose cost I’d spent this whole post refusing in /odds.

So the engine got ported to JavaScript. All of it. Your client crunches the numbers while my server serves static files and stays out of the way. BigInt rationals where Python had Fraction. The convolver, the multiset enumeration, the cost ceilings, the three-regime routing, and the entire exact-plus-empirical apparatus. Since we were opening doors, I threw in moderation too, because why not? I added starboards, reaction roles, and welcome messages; I can’t even blame that on the dice.

I’d call you a fool if you asked me to double my workload. I paid the parity tax anyway, every feature from now on costs two implementations. It’s my problem, but the downside is real: the Python side and the JS side have to agree or the dashboard quietly lies to people.

Parity isn’t fair

I said the engine got built twice, but what I meant is that “twice” is costly. Python’s refusals emigrated with the code, for better and worse:

if (sides > MAX_OUTCOMES) throw new Error(`A d${sides.toLocaleString()} has more outcomes than the engine can handle! (limit: ${MAX_OUTCOMES.toLocaleString()}) Try /simulate`);

There aren’t even slash commands on a web page. The ceilings, Discord time budgets, and other server anxieties were ported into an environment where the routing they describe doesn’t exist. In a Web Worker, on the user’s own machine, nothing is waiting.

“Math you can’t eval()” was a twelve-line story because ast.parse is in Python’s standard library. JavaScript has no ast and I’m still avoiding eval, so the parity tax on that one section was a hand-rolled precedence climber:

function parsePower() {
    let base = parseFactor();
    if (peek() === '*' && expr[pos + 1] === '*') {
        pos += 2;
        return Math.pow(base, parsePower()); // right-associative
    }
    return base;
}

The same safety guarantee, but five times the code, now becomes my personal responsibility.

The term regex exists twice, anchored and global, because JavaScript regexes carry lastIndex as mutable state. Which resulted in this beauty:

// Reset lastIndex in case (replace doesn't use it, but split might on some engines)
DICE_PATTERN.lastIndex = 0;

The renderers disagree on fundamentals, too. Discord’s 2,000-character budget caps the bot’s tables at 20 rows; the browser uses 120, 150, or 40. Same expression, different bucketing, different bars. The constraint that shaped every rendering decision in this post simply doesn’t exist on the other side.

Every command’s target supports odd, and the implementations look the same across both languages:

lambda x: int(x) % 2 == 1        # Python
x => Math.trunc(x) % 2 === 1     // JavaScript

However, Python’s % returns the sign of the divisor, so -3 is odd. JavaScript’s returns the sign of the dividend, so -3 is not odd. I wrote earlier that the two sides have to agree “or the dashboard quietly lies to people.”

I also want to bring up one more structural problem. The exact engine’s keep-highest weights come from a factorial built as a Number loop, and from Math.pow(sides, numDice) for the denominator. factorial(20) is about 2.4 × 10¹⁸, which is past the point where integers survive floating point. So for anything like 20d6kh3, which is well inside the engine’s own limits, the browser’s “exact” answer isn’t actually exact. I only found that out while writing this section.

But the gap that matters is this: the test suite proves the Python roller and the Python odds engine describe the same universe. 25,000 rolls, all landing inside their own support.

There is currently no equivalent on the JavaScript side. There is no cross-language test at all. Parity, that thing I said I’d be paying for forever? It’s verified the old-fashioned way: using eyes and aligning bar charts. It just looks right. The “careful” part got me -3 anyway.

The seed incident

I want to close with the scope creep that happened while writing this post, because it’s the purest specimen I have.

While drafting the section about random.randint, I thought: reproducible rolls would be nice. A seed parameter to replay a sequence, settle “the bot rigged my nat 1” disputes, or provide deterministic replays for testing. Reasonable, right? Here’s the chain it started:

  1. Python: random.seed(), Mersenne Twister. Done in ten minutes.
  2. JavaScript: Math.random() is not seedable by spec. Fine… grab a seeded PRNG library.
  3. …which implements a different algorithm than Mersenne Twister, so the same seed produces different roll sequences on the bot and the dashboard.
  4. Ah, I know! To solve parity, I’ll just implement one shared PRNG in both languages, plus a test suite proving the two implementations produce identical streams.
  5. Which means ripping out the random.randint call in roll_dice(), the last living descendant of the one-liner this post opened with.

The newest feature would have killed the oldest fossil. I want to be honest with myself, I have the know-how to pull it off. Instead, I stopped at step five and wrote this section.

For further evidence that this project intends to continue without my consent, the odds module already contains opposed-roll support: p_greater(), p_equal(), and margin_pmf(). Implemented but called by nothing, waiting for a slow weekend.

Though, none of this is a complaint. The one-liner still works; you can see it in there, buried in sediment, with eight years of “reasonable” decisions layered on top. I haven’t decided it’s done, and I’m not sure if I ever will. There’s a non-zero chance this post is already the newest layer, and there’s still work to be done.

Again, if you want to poke at the strata: the full dashboard is live, add it to your server and experiment. Or view the public lite version on GitHub, that includes all core features of this post.

Thanks for reading, see you around! ✧ ദ്ദി