Heiko Seeberger

Where your stack lives can move a benchmark by 50%

When we added timers to tellus, our actor framework for Rust, a benchmark comparison said that the queued benchmarks of our messaging suite got 55% slower. The same comparison said that the flood benchmarks got up to 24% faster.

flood measures how long it takes until a single actor has processed 100,000 messages from one sender. queued does the same with concurrent sender tasks. A fixed per-message overhead would slow both workloads down, so we were seeing something else as well. But what? Let’s look at what we found, and at how we compare benchmarks since. The full story, with all the measurements, is in the investigation report.

Two wrong turns

Our first idea was to bisect the pull request. Without the select arm which waits for a timer to fire, with the rest of the timer code still compiled in, queued was still 55% slower. Then we added one unused 16-byte field to the ActorContext of the complete pull request, and the difference dropped to 7 or 8%. The same field on main changed nothing.

So the timer code was not the cause, but an unused field moved the result by 48 percentage points. At first we concluded that timers cost about 7%. That was wrong: the field changed the memory layout, and a single layout cannot tell the cost of the timers apart from the luck of where things land.

Next we aligned all functions and branch targets to 64 bytes with LLVM flags. Now the pull request ran at main’s speed, and the pull request with the unused field was the slow one. So code placement was the cause? No, that was wrong, too. These flags change more than the addresses of instructions: they also move stack temporaries, the values the compiler keeps in a function’s stack frame on its own, and those turned out to matter. To tell the two apart, we needed an experiment which moves the stack and nothing else.

Shifting the stack

To move the stack without changing the binary, we wrote a small C library. Loaded ahead of libc through the LD_PRELOAD environment variable, it replaces pthread_create, which Rust’s std::thread::spawn calls to start a thread, with a version which reserves STACK_SHIFT extra bytes on every new thread before the thread’s function runs:

__attribute__((noinline)) static void *entry(void *p) {
    struct launch launch = *(struct launch *)p;
    free(p);
    volatile char *pad = alloca(launch.shift + 16);
    pad[0] = 1;
    void *result = launch.f(launch.arg);
    pad[0] = 0;
    return result;
}

So every Tokio worker thread of the benchmark does its work STACK_SHIFT bytes deeper in its stack than at shift 0. The two writes to pad only keep the compiler from removing the allocation, and a probe checks that a shift moves the stack by exactly that many bytes. The full library is 35 lines.

Then we ran the same, unchanged binaries at different shifts. If the stack is what matters, a binary should get faster or slower with the shift alone, and it did. On queued with four senders, pinned to one CPU, main took 3.49 ms at shift 0 and 5.83 ms at shift 96: the same binary, 67% slower, only because its stacks lay 96 bytes deeper. The pull request took 6.14 ms at shift 48 and 4.18 ms at shift 64. So both binaries had fast and slow shifts, and the timers had only moved them. Each penalty came back exactly 4096 bytes later, at the size of a page. And because it also showed up on a single CPU, contention between cores could not be the cause.

One unaligned load

A penalty which repeats with the page size points to a memory access which crosses a page boundary. So we went through the stack accesses on the receive path of the slow binary. We looked for a load which, at a slow shift, reads across the boundary between two pages, the 4096-byte blocks in which the operating system manages memory. In Mailbox::recv, which takes the next message out of an actor’s mailbox, we found it: the aarch64 instruction ldur q0, [sp, #13] copied a received Incoming out of a stack buffer. That is a 16-byte load from an address which is not 16-byte aligned. At the slow shift, the address lay at page offset 0xffd, so the load read across a page boundary, and such a load is slow. To prove it, we patched the binary to move only that temporary, keeping every instruction at its address. The time dropped from 6.78 to 4.73 ms. A second patch, which restored the temporary’s original address, brought it back to 6.81 ms.

Why is the copy unaligned in the first place? Because of these two types:

pub struct ActorId(Uuid);

pub enum Incoming<M> {
    /// A message sent to this actor.
    Message(M),

    /// The signal that a watched actor has terminated. ...
    Terminated(ActorId),
}

A Uuid is a [u8; 16] with alignment 1. So Incoming<()> is 17 bytes with alignment 1: a tag, plus the 16 bytes which hold the ID in a Terminated. Every message we send reaches the actor as an Incoming, and in Rust moving a value copies its bytes, here from one stack frame to the next. With alignment 1, the compiler does these copies with unaligned loads and stores. Several such copies lay along our receive path. Whether one of them crosses a page depends on where the stack of the worker thread running the actor lies, and any unrelated change can move that.

Why not just align it?

Our obvious fix was #[repr(align(16))] on ActorId. On my aarch64 machine it removed the shifts at which main had been slow in every run, and every such copy on the receive path became provably aligned. But it almost doubled the memory of a mailbox full of empty messages. And on GitHub’s runners it cost up to 21% on fan_out, where one actor sends to many, on Neoverse-N2 and 4 to 6% on several benchmarks on x86_64.

We tried five more variants: aligning Incoming instead, an aligned ID inside ActorRef only, Tokio’s unbounded channel instead of flume (which the mailbox used at the time), an aligned receive slot in Mailbox::recv, and that slot on aarch64 only. Each of them either cost too much somewhere or fixed only some shifts. Even the most promising one left other shifts 30 to 40% slower, and it depended on where the compiler places one temporary, which can change with any release. So main stayed as it was.

Does that mean we lost? Not quite. What we kept is the knowledge that a comparison of two builds at one shift can show tens of percent either way that have nothing to do with the change. So let’s look at how we compare builds now.

The stack sweep

The per-PR benchmark comparison in our CI still runs, but only as a hint. It measures one shift, and on identical code flood/bounded has moved anywhere from -35.7% to +19.9% there. The verdict comes from the stack sweep, a workflow which we start with a label on the pull request:

  • It runs 4 jobs on x86_64 and 4 on Neoverse-N2. Each job builds the candidate and its parent and runs both, plus a copy of the parent as an A/A control: the parent measured against itself, which shows how much change the setup alone produces.
  • Each binary runs at 16 shifts, 0 to 3840 bytes in steps of 256, in 3 repetitions with a rotating binary order.
  • A job’s figure for a benchmark is how much the median of the candidate’s 48 runs differs from the median of the parent’s 48 runs, so +5% means 5% slower. If the A/A figure of that job is off by more than 3%, the job does not count for that benchmark.
  • Across the jobs, the median decides: below +3% a benchmark passes, above +5% it fails, and in between it gets a second run. If too few jobs remain or their figures spread by more than 6 points, the benchmark is inconclusive.

Why steps of 256 bytes, when the penalty sits on a 16-byte load? Because the sweep does not look for slow shifts. A slow shift may well lie between two of its steps. What we need is 16 different shifts spread over a page, so that one unlucky shift cannot decide the comparison. That’s why it compares the median over all of them.

All limits were fixed before we used them, and they only change in a commit of their own. The scripts which measure and judge come from the parent, never from the candidate, so a pull request cannot loosen its own gate.

Does the sweep raise false alarms? To find out, we ran it on main against itself. In four such null runs of the messaging benchmarks, 76 of 80 verdicts passed and 4 were inconclusive, all on x86_64. None failed, so on identical code the sweep raised no false alarm. And it does catch real costs: the aligned ID from above failed it with +21% on fan_out on Neoverse-N2. A sweep takes a while, but it is the first comparison we trust.

The timers we started with went through it too. With timer code in every actor’s run loop, four designs in a row failed the sweep on x86_64. So timers became opt-in at the type level: an actor without timers runs a loop without any timer code, and that design was accepted. How that works is the topic of my next post.

How do you compare benchmarks of two builds? I am looking forward to your comments.

My thoughts, written with AI assistance.