# The Scariest Bug Is the One That Passes Every Test

# The Scariest Bug Is the One That Passes Every Test

*What I learned fixing six "small" undefined-behaviour bugs in a macOS audio driver, and why one of them printed the right answer while quietly being broken.*

---

I picked up issue [#124](https://github.com/soundsofthesir/AES67_macos_Driver/issues/124) in the [AES67 macOS Driver](https://github.com/soundsofthesir/AES67_macos_Driver) project because of its title: **"Small undefined-behaviour and portability bugs."**

Small. That word turned out to be doing a lot of work.

The project is a virtual audio driver that sends and receives professional audio over a network (AES67, the standard behind Dante and RAVENNA) on macOS. Audio code has no patience for surprises. A glitch is audible, and code running in a driver can't just crash and apologize. So I got to spend a week on the most uncomfortable category of C++ bugs: the ones where the language shrugs and says *"you broke the contract, I owe you nothing."*

This post is the story of those fixes, what each taught me, and the moment a test taught me that **"all tests pass" and "no bug" are different claims.** My pull request is [#223](https://github.com/soundsofthesir/AES67_macos_Driver/pull/223).

---

## First, what "undefined behaviour" really means

Most people think undefined behaviour (UB) means "the program does something random on that line."

It's worse than that. The C++ standard is a contract. You promise never to do certain things, and in return the compiler promises to translate your program faithfully. Break the promise, and the standard places **no requirements on the entire program**, not just the offending line.

Modern optimisers don't *detect* UB and punish you. They **assume it never happens** and reason from there:

- Assume signed overflow can't occur, and `i + 1 > i` is always true, so your overflow check disappears.
- Dereference a pointer and then null-check it, and the compiler concludes the pointer can't be null, so the check disappears.
- Any branch that would require UB is treated as unreachable, and gets deleted.

So UB can "work" for years, then break when a compiler upgrade, an optimisation flag or a different standard library changes its mind. In an audio driver, that is the worst possible failure: intermittent, platform-dependent, and invisible in the debugger.

With that in mind, here are the six bugs.

---

## Bug 1: A distribution that isn't allowed to exist

```cpp
std::uniform_int_distribution<uint8_t> dis(0, 255);
```

This line generated random bytes for UUIDs. It reads perfectly naturally. It's also undefined behaviour.

The standard says the `IntType` of `std::uniform_int_distribution` must be one of `short`, `int`, `long`, `long long`, or their unsigned versions. The character types, which include `char`, `signed char`, `unsigned char` and therefore `uint8_t`, are not on the list. ([cppreference](https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution) spells it out.) Some standard libraries reject it at compile time, others accept it and do whatever they like. That is exactly what makes it a portability bug as well.

The fix is to draw an `unsigned` and narrow it explicitly:

```cpp
template <class Engine>
inline uint8_t randomByte(Engine& engine) {
    std::uniform_int_distribution<unsigned> distribution(0u, 255u);
    return static_cast<uint8_t>(distribution(engine));
}
```

Narrowing an unsigned value is well-defined, since it wraps modulo 2⁸, and here the value is already in range, so nothing is lost.

**Lesson:** "it compiles" is not "it's allowed." Library requirements are part of the contract too.

---

## Bug 2: The timestamp that passed every test while racing

The logger stamped each message with `std::localtime`. That function returns a pointer to **one shared, static `tm` buffer**, and the standard says any later call may overwrite it. Two threads logging at once can trample each other's result. That's a data race, and a data race is UB.

The fix is the re-entrant version, `localtime_r` (POSIX) or `localtime_s` (Windows), which writes into a buffer *you* own:

```cpp
inline bool safeLocalTime(std::time_t time, std::tm& out) {
#if defined(_WIN32)
    return localtime_s(&out, &time) == 0;
#else
    return localtime_r(&time, &out) != nullptr;
#endif
}
```

Now the interesting part. I wanted a regression test, so I wrote one: eight threads, 20,000 conversions each, every result compared against a known-good value. Then I did something I recommend to everyone: I **put the bug back** to see whether the test would catch it.

With plain `std::localtime` restored, the test printed:

```
UB fixes: 20746 passed, 0 failed
```

All green. Zero failures. And yet, in the same run, **ThreadSanitizer reported two data races**: one on the shared buffer I expected, and one inside the timezone handling, where one thread was freeing memory another was allocating.

The values were *correct* while the program was *broken*. The race was real, and my assertions simply never happened to observe it.

That is the whole nature of data races. They are not "wrong answers", they are UB, and UB is allowed to look fine. The only reliable detector is a tool that watches the memory accesses themselves, like ThreadSanitizer. So I added a comment at the top of the test file saying it must also be run with `-fsanitize=thread`. A test that can pass while the bug is present, without telling the reader so, is a trap for the next person.

**Lesson:** a green test suite proves the cases you thought of. For concurrency bugs, you need a sanitizer, and you need to prove the test fails without the fix.

---

## Bug 3: A sequence number that started at zero (and a log line that wrapped)

RTP, the protocol carrying the audio packets, numbers each packet with a 16-bit sequence counter. [RFC 3550 §5.1](https://www.rfc-editor.org/rfc/rfc3550) says the initial value **SHOULD be random**. The driver already randomised the SSRC and the timestamp, but the sequence number started at 0. The fix is one line, using the `std::random_device` already in the constructor:

```cpp
sequenceNumber_ = static_cast<uint16_t>(rd());
```

Truncating an unsigned value to 16 bits is well-defined and keeps the distribution uniform.

Randomising it exposed a second, sneakier bug nearby. When a send failed, the driver logged `sequenceNumber_ - 1`. But `uint16_t` arithmetic promotes to `int`, so when the counter had just wrapped to 0, the log printed `-1` as an unsigned: **4294967295** instead of 65535. With a start value of zero that corner almost never mattered. With a random start it can show up in the first few seconds. The fix is to convert back to 16 bits before printing.

**Lesson:** fixing one thing changes which corner cases are reachable. Go and look at the neighbours.

---

## Bug 4: `%zu` fed a `uint16_t`

```cpp
AES67_LOGF("... (devCh=%zu, count=%u)", name, mapping.deviceChannelStart, numChannels);
```

`printf`-style functions are *variadic*, and variadic arguments aren't type-checked. `%zu` tells the function to read a `size_t` (8 bytes on a 64-bit machine). The caller passed a `uint16_t`, which was promoted to a 4-byte `int`. The function reads bytes that were never passed. That's UB, and in practice it prints garbage.

The fix is a cast: `static_cast<size_t>(mapping.deviceChannelStart)`. I found the same pattern in a second file, so I fixed that too.

**Lesson:** compile with `-Wformat`, and remember that integer promotion happens *before* your value reaches `printf`.

---

## Bug 5: The macro that stole an `else`

```cpp
#define LOG_INFO(msg) if (AES67::g_logger) AES67::g_logger->info(msg)
```

Looks harmless. Now use it like this:

```cpp
if (needsLogging)
    LOG_INFO("hello");
else
    doSomethingElse();
```

After expansion, the `else` attaches to the **macro's own `if`**, not yours. When `needsLogging` is false, `doSomethingElse()` never runs. When it's true and no logger exists, `doSomethingElse()` runs when it shouldn't. This is the classic dangling-else problem, and the classic fix is to make the macro a single statement:

```cpp
#define LOG_INFO(msg) do { if (AES67::g_logger) { AES67::g_logger->info(msg); } } while (0)
```

I tested both directions. With the old macros, two checks failed, and the compiler itself warned with `-Wdangling-else`. With the new ones, both pass.

**Lesson:** a multi-statement macro should be a single statement. `do { ... } while (0)` is ugly, and it works.

---

## Bug 6: A move constructor that never existed

The ring buffer the audio threads share declared its move operations as `= default`. But the class holds `std::atomic` indices, and atomics can't be moved, so the compiler had quietly defined those "defaulted" moves as *deleted* all along. The comment above them said "Allow move." The code said otherwise.

No behaviour changed, because nothing could ever have moved the buffer. But a comment that lies is a bug waiting for a reader to trust it. I made the deletion explicit, fixed the comment, and added compile-time `static_assert`s so that anyone who tries to make it movable later will have to change a test first.

**Lesson:** code should say what it does. If the compiler overrides your intention, make the intention match.

---

## The one I didn't have to fix

The issue also listed a `memset` over a struct containing `std::atomic` members. That one is nasty in its own way: `memset` is a plain, non-atomic write, so it races with any thread touching those atomics, and it bypasses the memory orderings you carefully chose. But by the time I looked at the current code, it was already gone.

That was a useful lesson in itself. My fork was two commits behind upstream, and several items from the issue had already been fixed. **Fetch upstream and diff before you start.** Otherwise you fix things that aren't broken and conflict with the people who did.

---

## Proving it (on a Windows machine with no compiler)

The driver targets macOS, but I develop on Windows, so verifying took some improvisation.

- No C++ compiler installed → I ran an Ubuntu 24.04 container in Docker with clang 18.
- ThreadSanitizer crashed immediately with a cryptic `personality` error → Docker's default security profile blocks the system call TSan uses to control address-space randomisation. Starting the container with `--security-opt seccomp=unconfined` fixed it.
- Half my commands failed because PowerShell treats the comma in `-fsanitize=address,undefined` as an array operator. It took me an embarrassing while to see that this was a shell problem and not a compiler problem.

The final result on Linux, for the new regression tests (20,751 checks): **zero failures and zero sanitizer reports under AddressSanitizer + UBSan, and again under ThreadSanitizer.** And, just as important, **each fix was shown to fail when removed**: the old macros fail two checks, and the old `localtime` triggers ThreadSanitizer data-race reports.

What I *couldn't* verify locally are the macOS-only files, which depend on Mach and Core Audio headers. That's why the pull request is a **draft**: the project's macOS CI is the first real compile of those changes, and I'd rather say that plainly than imply a certainty I don't have.

---

## What I deliberately left out

Part of doing a fix well is saying what you *didn't* do:

- **Creating the global logger inside the driver.** It would change runtime behaviour: opening a log file from inside a system audio daemon that may be sandboxed, plus a mutex and heap allocation on threads near the audio path. That's a design decision for the maintainer, not a drive-by fix.
- **Real-time-safe logging**, a redesign and not a small fix.
- **SSRC collision detection** from RFC 3550, which is a feature and deserves its own issue.

I listed all three in the PR description and offered to take them as follow-ups.

---

## A note on how I worked

I used an AI assistant as a mentor and reviewer throughout: to explain the language rules behind each bug, to sanity-check my reasoning and to help me design the tests, including the "put the bug back" checks. The decisions, the verification runs and the scope calls were mine to make and to defend, and I made sure I understood every line well enough to explain it. I think that's the honest way to say it, and I'd encourage anyone doing the same to say so too.

---

## Where it stands

Pull request [#223](https://github.com/soundsofthesir/AES67_macos_Driver/pull/223) is open as a draft: 11 files, about +289/−21 lines, with a new regression test registered in CTest. As I write this, the CI workflows are waiting for a maintainer to approve a first-time contributor's run, so the macOS side isn't proven yet. The story isn't finished, and I'd rather publish an honest middle than a tidy ending I haven't earned.

## Takeaways

1. **UB is a contract violation, and the optimiser assumes you never break it.** "Works on my machine" is not evidence.
2. **A data race can pass every functional test.** Use ThreadSanitizer, and say so in the test.
3. **Put the bug back.** A test you haven't seen fail might not be testing anything.
4. **Fixing one thing exposes its neighbours.** Look around the change.
5. **Fetch upstream first.** Some of the work may already be done.
6. **Say what you left out and why.** Scope is part of the fix.

The most valuable thing I took from "small" bugs: the small ones are the ones that hide.

*Thanks to the maintainers of the AES67 macOS Driver for a clearly written issue that made a good first contribution possible.*
