---
title: "Compiler fuel in Scala 3.10: What Dotty counts when type checking gets
  too deep"
author: Szymon Cytrowski
url: https://cytrowski.me/posts/scala-compiler-fuel/
published: 2026-11-20T00:00:00.000Z
description: "A source-level look at Scala 3.10 compiler fuel: what it measures,
  how Dotty reports recursion, and how to diagnose deeply nested types."
tags:
  - scala
  - compiler
  - type-level
language: en
---

# Compiler fuel in Scala 3.10: What Dotty counts when type checking gets too deep

A source-level look at Scala 3.10 compiler fuel: what it measures, how Dotty reports recursion, and how to diagnose deeply nested types.

## Key Takeaways

- **Fuel limits active nesting.** Returning from a guarded compiler operation restores the available recursion depth.
- **The diagnostic identifies recurring work.** Dotty counts the active operations and the entry it rejected, then reports the most frequent category.
- **The right fix depends on the cause.** A recursive cycle, a deep finite computation, and expensive shallow work need different responses.

A type-level computation can have a clear base case and still fail with `Recursion limit exceeded`. By default, once Scala 3.10 has 550 guarded compiler operations active, it refuses to enter another, even if the compiler thread has stack space to spare. Increasing the JVM's `-Xss` leaves that threshold at 550.

For years, Dotty handled some cases of deep recursion by catching `StackOverflowError`. Scala 3.10 introduces **compiler fuel** so Dotty can stop at a depth it controls and report the work that led there. [scala/scala3#25937](https://github.com/scala/scala3/pull/25937)

The name suggests a resource that gets used up as compilation progresses. In this implementation, however, returning from an operation restores the available depth. Understanding that distinction explains both what a fuel error means and when increasing the limit can help.

The implementation also has an interesting constraint: a recursion guard on a hot compiler path needs to retain useful diagnostic information without paying for a freshly constructed diagnostic on every successful check.

## Why Catching a Stack Overflow Wasn't Enough

Recursive match types, nested type constructors, and compile-time code can all send the compiler through long chains of typing and subtype checks.

Catching `StackOverflowError` is a fragile way to bound that work. The thread has already exhausted its stack, just as the compiler needs room to unwind and explain the problem. The failure threshold also depends on the shape of the call stack and the JVM's `-Xss` setting.

Fuel moves the normal recursion limit to a point the compiler can check explicitly. A [best-effort top-level handler](https://github.com/scala/scala3/blob/3.10.0/compiler/src/dotty/tools/dotc/Driver.scala#L37-L47) still exists for actual stack overflows, but it is no longer the intended stopping mechanism for guarded recursion.

This changes which programs reach the limit. The [Scala 3.10 release notes](https://www.scala-lang.org/news/3.10/) warn that deeply nested types which compiled on earlier versions may now need a larger fuel budget. A new fuel error is therefore not, by itself, evidence of a new type error in the program.

## What the 550-Unit Limit Measures

The default fuel limit is **550**, configured through `-Xmax-fuel`. It bounds the number of **simultaneously active, fuel-checked compiler operations**.

A simplified sequence illustrates what is counted:

| Event | Active guarded operations |
| --- | ---: |
| Enter a subtype check | 1 |
| Enter match-type reduction inside it | 2 |
| Enter another subtype check inside the reduction | 3 |
| Return from the inner subtype check | 2 |
| Return from match-type reduction | 1 |
| Return from the outer subtype check | 0 |
| Start an unrelated subtype check | 1 |

Each guarded entry occupies one level until it returns. If another entry would exceed the limit, the compiler raises `RecursionOverflow`.

One level is an instrumented compiler operation, not a JVM stack frame. A single operation may involve several method calls. Likewise, 550 is not a limit on type checks per file, reductions per build, or CPU time.

A compiler can perform an enormous amount of shallow work without exhausting fuel. A shorter computation can hit the limit if it keeps entering guarded operations before earlier ones return. Fuel is a recursion-depth guard; it does not determine whether a computation will eventually terminate.

## One Countdown, Two Different Limits

Consider a finite inline computation:

```scala
//> using scala 3.10.0

import scala.compiletime.constValue
import scala.compiletime.ops.int.-

transparent inline def countdown[N <: Int]: Int =
  inline if constValue[N] == 0 then 0
  else 1 + countdown[N - 1]

val result: Int = countdown[40]
```

For this call, each expansion decreases the type-level integer until it reaches zero. There is a clear stopping point, but reaching it requires successive inline expansions.

Scala has a separate limit for those expansions: `-Xmax-inlines`, which defaults to **32**. That limit is reached first here.

The following compile-only checks were repeated on November 20, 2026 with **Scala 3.10.0**, **OpenJDK 21.0.13**, and the compiler JVM stack fixed at **`-Xss8m`**:

| Additional compiler options | Compilation result |
| --- | --- |
| None | Failed: 32 successive inline expansions |
| `-Xmax-inlines:100` | Succeeded |
| `-Xmax-inlines:100 -Xmax-fuel:50` | Failed: `Recursion limit exceeded` |

With fuel set to 50, the trace shows several operations for one value of `N`. At 27, Dotty is still typing the enclosing addition and the inline conditional when it types the recursive call. Here are three consecutive entries, with the conditional abbreviated:

```text
typing countdown[scala.compiletime.ops.int.-[(27 : Int), 1]]
typing 1 + countdown[scala.compiletime.ops.int.-[(27 : Int), 1]]
typing inline if scala.compiletime.constValue[(27 : Int)] == 0 then 0 else ...
```

Save the snippet as `Countdown.scala` to reproduce the fuel failure with Scala CLI:

```sh
scala-cli compile Countdown.scala --server=false \
  -O -J-Xss8m \
  -O -Xmax-inlines:100 \
  -O -Xmax-fuel:50
```

Here, `-O` forwards compiler options. With the build server disabled, the `-J-Xss8m` option configures the **compiler's JVM**. This invocation was also checked with Scala CLI 1.19.0; the [compiler-options guide](https://scala-cli.virtuslab.org/docs/commands/compile/#java-options-for-the-compiler) documents the distinction between compiler JVM settings and application JVM settings.

In `Countdown.scala`, replace `countdown[40]` with `countdown[200]`. In the command above, keep `-J-Xss8m` and change the inline limit to `-Xmax-inlines:256`. Run it first with `-Xmax-fuel:550`, then with `-Xmax-fuel:1200`. The table shows the results for Scala 3.10.0 on OpenJDK 25.0.2.

| Fuel for `countdown[200]` | Compilation result |
| --- | --- |
| `-Xmax-fuel:550` (default) | Failed with `Recursion limit exceeded` |
| `-Xmax-fuel:1200` | Succeeded |

## When Reducing a Match Type Requires More Reduction

A match type chooses a result type by inspecting another type. A small recursive example makes that concrete:

```scala
//> using scala 3.10.0

type Leaf[X] = X match
  case List[t] => Leaf[t]
  case _ => X

val evidence = summon[Leaf[List[List[Int]]] =:= Int]
```

For `List[List[Int]]`, the first case removes one `List` layer and continues with `List[Int]`. The next step reaches `Int`, which cannot match `List[t]`, so the final case returns `Int`. The equality evidence compiles with the default limits in Scala 3.10.0.

The argument gets smaller at each step. A more difficult situation arises when deciding which case applies requires another reduction before the current decision can finish.

### A Compiler Test That Reaches the Fuel Limit

This [negative test from Scala 3.10.0](https://github.com/scala/scala3/blob/3.10.0/tests/neg/i17132.min.scala) deliberately exercises that situation:

```scala
//> using scala 3.10.0

class P[T]
class Q[T <: P[Any]] extends P[R[T]]

type R[U] = U match
  case Q[t] => R[t]
  case P[t] => t
```

Dotty re-enters reduction while deciding whether the first case applies, before it can select the recursive `R[t]` on the right-hand side.

The dependency develops in three steps:

1. **Checking `Q`'s parent brings in `R[T]`.** The declared parent is `P[R[T]]`, and the compiler attempts to reduce the match type inside it.
2. **The first case must be resolved before the second is considered.** Knowing `T <: P[Any]` does not let the compiler jump straight to `case P[t]`. Under the [match-type reduction rules](https://docs.scala-lang.org/scala3/reference/new-types/match-types.html#match-type-reduction), skipping a case requires proving that the scrutinee and its pattern are disjoint: no value can belong to both types.
3. **The disjointness check introduces another `R`.** At their common base class `P`, the upper bound of `T` gives `P[Any]`, while the parent of `Q[t]` gives `P[R[t]]`. Comparing those arguments brings `R[t]` back into the analysis. Since `t` has the same upper bound as `T`, Dotty faces the same case decision while the earlier one is still active. [Common base class analysis in TypeComparer](https://github.com/scala/scala3/blob/3.10.0/compiler/src/dotty/tools/dotc/core/TypeComparer.scala#L3272-L3336)

The compilation fails at `P[R[T]]` with the following recurring operation (abbreviated):

```text
Recursion limit exceeded.
Maybe there is an illegal cyclic reference?
...
A recurring operation is (inner to outer):
  match cases for t
  match cases for t
  ...
  match cases for T
```

This result was reproduced with Scala 3.10.0 and OpenJDK 21.0.13. It also agrees with the compiler's [version-pinned expected output](https://github.com/scala/scala3/blob/3.10.0/tests/neg/i17132.min.check).

The two examples show different paths into the same guard: typing inline expansions and recursively checking match-type cases. The error identifies recurring compiler work. It does not, on its own, prove that the user's computation can never terminate.

## Inside Dotty: `Context.handleRecursive`

The guard lives in [`Contexts.scala`](https://github.com/scala/scala3/blob/3.10.0/compiler/src/dotty/tools/dotc/core/Contexts.scala#L538-L556). This is the implementation from Scala 3.10.0, with comments omitted and the signature wrapped:

```scala
final inline def handleRecursive[T](
    title: String,
    details: RecursiveOperationDetails,
    pos: SrcPos | Null = null
)(inline block: T): T =
  val depth = base.recursiveDepth
  val ops = base.recursiveOperations
  if depth >= ops.length then
    throw RecursionOverflow(ops, title, details, pos)
  if depth >= 0 then
    base.recursiveDepth = depth + 1
    ops(depth).title = title
    ops(depth).details = details
    ops(depth).pos = pos
  try block
  finally base.recursiveDepth = depth
```

The body first checks whether another guarded operation fits. It then increments the depth and records the operation in the slot corresponding to that depth. The `finally` block restores the previous value on both normal return and exception.

The `depth >= 0` condition supports a diagnostic escape hatch. When `-Xno-enrich-error-messages` is enabled, initialization sets the depth to `Int.MinValue`. The normal accounting and fuel check are bypassed, allowing an actual stack overflow to surface for investigation. Despite the option's name, it changes more than the wording of the error.

### The Array Is Both a Limit and a Trace

During initialization, `ContextBase` allocates an array of mutable `RecursiveOperation` records whose length is the configured fuel limit. The array provides both the boundary and the information about the active operations leading to it.

Reusing those records avoids constructing a new record for every guarded entry. This matters on paths such as subtype checking. It does not make every call allocation-free: a call site may still supply a closure for its diagnostic details.

The details are stored as a `Showable` value or a function that produces a string later. Formatting every type comparison eagerly would add work to successful compilation, and displaying a complex type can itself trigger more compiler operations. Deferring that work keeps it on the failure path.

The state belongs to the compiler's `ContextBase`, so it tracks the nesting of work sharing that base context. It is not a JVM-wide account of compilation effort.

### Reporting the Failure

[`RecursiveOperation.scala`](https://github.com/scala/scala3/blob/3.10.0/compiler/src/dotty/tools/dotc/core/RecursiveOperation.scala) handles the other half of the mechanism.

When a new guarded entry would exceed the limit, Dotty copies the active records and includes the operation whose entry was rejected. That snapshot has to survive subsequent reuse of the array. Unwinding restores the depth; later guarded operations, including those used to format the error, can overwrite the available slots.

The reporting code groups the snapshot by operation title and selects the most frequent category. It displays up to 20 entries from that category, ordered from inner to outer. If there are more, it keeps ten from each end and abbreviates the middle.

Dotty chooses the source position separately. It scans the **whole snapshot** from inner to outer for the first operation with a usable position. In the `Q` example, the compiler points at `P[R[T]]` in the parent declaration. The repeated `match cases for t` entries tell you which work recurred while Dotty checked that declaration. Operations with other titles still count toward the depth, even though the message omits them.

`RecursionOverflow` extends `Error` instead of the compiler's `TypeError`. As the source comment explains, a `TypeError` could be caught too early, while the compiler still has too little stack space to produce the useful report. The exception also overrides `fillInStackTrace()`, avoiding construction of a JVM stack trace that will not be shown.

The retained operation records supply the explanation: repeated subtype tests, match-case checks, or typing operations tied to the computation being compiled.

### Why Tail Recursion Also Matters

The comment on [`TypeApplications.typeParams`](https://github.com/scala/scala3/blob/3.10.0/compiler/src/dotty/tools/dotc/core/TypeApplications.scala#L217-L221) calls its guard *load-bearing*: without it, the function would be tail-recursive and could loop forever.

Both `handleRecursive` and its `block` parameter are inline, so its `try`/`finally` surrounds the recursive work at the call site. Each recursive call must return before its caller can restore the saved depth. Those pending `finally` blocks prevent [Scala's tail-call transformation](https://github.com/scala/scala3/blob/3.10.0/compiler/src/dotty/tools/dotc/transform/TailRec.scala#L446-L455) from turning the calls into a loop.

A cycle therefore keeps adding active guarded scopes until fuel runs out. An ordinary loop that enters and leaves a guarded scope on every iteration can keep the depth constant. That is another reason a depth limit cannot bound all compiler work.

## Depth and Work Are Different Budgets

Zig 0.15.2 counts backward branches during compile-time evaluation. A long `comptime` loop can exhaust its default quota of 1,000 while the call stack stays shallow. In Dotty, a loop that returns from each guarded operation before starting the next can keep going at the same fuel depth. [Zig's `@setEvalBranchQuota`](https://ziglang.org/documentation/0.15.2/#setEvalBranchQuota)

## Choosing the Right Fix

| Compiler message | What to check first |
| --- | --- |
| `Maximal number of successive inlines (32) exceeded` | Follow the recursive call in the inline stack trace. In `countdown[40]`, each expansion moves toward zero, and raising `-Xmax-inlines` to 100 is sufficient. |
| `Recursion limit exceeded` | Read the highlighted expression alongside the recurring operation. Does the argument get smaller, as in `countdown`, or does the same unresolved case return, as in `R[t]`? A deeper finite input can justify more fuel. A cycle calls for a change to the recursion. |
| `Stack overflow in the compiler.` (`StackOverflowError`) | If you enabled `-Xno-enrich-error-messages` to get a raw stack trace, remove it to restore the fuel guard. If the overflow occurs on Scala 3.10 with the guard enabled and both fuel and compiler JVM stack size at their defaults, report it as the [compiler guide](https://docs.scala-lang.org/overviews/compiler-options/compiling-deeply-nested-code.html) requests. |

This is the same distinction that appears in compile-time derivation. In [my article on type materialization](https://cytrowski.me/posts/when-types-become-values-scala-3/), recursive traversal needs cycle detection and caching to avoid cycles and repeated work. Compiler fuel cannot provide either feature for the derivation algorithm.

If a library requires more fuel for ordinary inputs, I would first examine the structure of its derivation. For inputs that are intentionally deep, raising the budget can be reasonable.

### Raising the Limit

In sbt, set the compiler option with:

```scala
scalacOptions += "-Xmax-fuel:2000"
```

The larger budget may also require a larger **compiler host JVM stack**. With the standard sbt runner, configure that in `.jvmopts` and restart sbt:

```text
-Xss8m
```

For Scala CLI, use the compiler JVM option shown in the countdown command, adjusting `-Xmax-fuel` to the needed value. With its build server enabled, the corresponding JVM settings belong to Bloop; the [Scala CLI guide](https://scala-cli.virtuslab.org/docs/commands/compile/#java-options-for-the-compiler) documents `--bloop-java-opt` for that case.

The values `-Xmax-fuel:2000` and `-Xss8m` are illustrative, not a recommended baseline or a guaranteed pairing. Fuel and stack space are separate resources. Raising fuel alone can allow the recursion to reach a real `StackOverflowError`.

Configure the environment running the compiler. When a JVM-hosted compiler targets Scala.js, its thread stack still follows the host JVM's settings. A compiler running in JavaScript has different constraints.

The useful change in Scala 3.10 is the combination of a controlled stopping point and an explanation of the work that reached it. Dotty records that context while compilation is still proceeding, with a default limit intended to leave enough stack for reporting. The same design consideration applies to any recursive engine: the limit needs to leave room to explain why it was reached.
