The Deterministic Active-Safety Layer

The car ahead has stopped and the driver is looking at the radio. A small, simple program must decide to brake. At 72 km/h on a dry road, with 0.3 s of delay, it must start by about 1.55 seconds before impact.

Press Go with the trigger at 1.0 s and watch the car hit. Move it to 2.0 s and the car stops. Now add the overhead sign: the early trigger also brakes for nothing. Find the narrow window that does both jobs. Then we build the whole layer, piece by piece.

You need speed = distance / time and some programming. We build the rest from zero.

Brake in time

Ready
72 km/h
1.0 s
0.30 s
8.0 m/s²

Press Go to run the approach.

Toy kinematics: constant speed, then a pure delay (the latency), then constant deceleration at the grip value. A warning shows 1.0 s of TTC before the brake trigger. The ghost road is the same car on an empty road: the toy radar takes the sign for a stopped car until 35 m, and the bag sits in the lane from 45 m to 25 m. All numbers are typical or illustrative, not from any product or test protocol.

Chapter 0

The last line

See which part of the car stops it when everything before it has gone wrong

Traffic on a city road slows, then stops. The driver of our car glances down at the radio to change the station. At 72 km/h the car covers 20 metres every second. A two-second glance is 40 metres of road that nobody is watching.

A modern car has several chances to save this moment. The driver might look up in time. If the car has a driver-assistance stack, its planner might already be slowing for the queue. And if both of those fail, one more piece of software is still watching the road. This lesson is about that last piece.

We call it the active-safety layer: a small program that watches for an imminent collision and acts on its own, by warning the driver and then braking. Its best-known job is automatic emergency braking (AEB): braking hard when a crash is close and nearly certain.

Three words describe how it is built. It is simple: a few hundred lines that one engineer can read in an afternoon. It is deterministic: the same inputs always give the same output, in the same time, every cycle. And it is independent: it does not share the failures of the big stack it backs up.

Who stops the car?

Our car approaches a stopped car at 72 km/h. Three lines of defence can act. Switch each one off and press Run. The lower rows show when each line acted.

Toy: the main stack brakes gently (3 m/s²) from a TTC of 5 s. A watching driver starts braking (7 m/s²) 1.2 s after the TTC reaches 3.5 s; a distracted driver reacts only to the warning, 1.5 s after it. The layer warns at a TTC of 2.6 s and brakes fully (8 m/s²) at 1.6 s, plus 0.3 s of latency. Illustrative numbers.

Start with everything off except the layer. The main stack missed the car and the driver is looking at the radio. The layer warns at 52 m, then brakes. It stops about a metre short. Now switch the layer off too: the car hits at full speed.

Look at when each line acts. The main stack acts first and gently, at a time to collision of 5 seconds. The driver acts in the middle. The layer acts last and hardest, about 1.6 seconds out. That order is on purpose. The layer stays quiet unless the others have failed, because a needless hard brake is a hazard of its own.

The arithmetic of the last moment

Here is the problem in numbers. At 72 km/h our speed is 72 / 3.6 = 20 m/s. A dry road lets the tyres slow the car at about 8 m/s² (a typical figure). From 20 m/s, stopping takes 20 / 8 = 2.5 s and covers 25 m. Add 0.3 s of system delay, during which the car still covers 6 m.

brake must start at 20 × 0.3 + 20² / (2 × 8) = 6 + 25 = 31 m  ·  that is 31 / 20 = 1.55 s before impact

The hero's narrow window comes from exactly this sum. Brake later than 1.55 s and the car hits, whatever the brakes can do. Brake much earlier and the layer also brakes for things that are not there. Chapter 1 derives the sum from zero, and Chapter 5 is about the things that are not there.

The whole decision fits in one small function. This is the hero's rule in C++. Every later chapter improves one line of it.

// The hero's rule in one function: brake when the time we have is no more
// than the time we need. Inputs come from one track, in SI units.
struct Threat { double range_m; double closing_ms; };  // from the layer's own track
struct Car { double latency_s; double grip_ms2; };      // configured, checked at start-up

// Time we have  = range / closing speed: the time to collision (Ch 2).
// Time we need  = latency + the time-equivalent of the braking distance (Ch 1).
bool must_brake(const Threat& t, const Car& car, double margin_s) {
  if (!(t.closing_ms > 0.0)) return false;   // not closing, or a NaN: nothing to brake for
  if (!(t.range_m > 0.0)) return true;       // already touching: brake
  if (!(car.grip_ms2 > 0.0)) return false;   // a broken config disables the layer at start-up;
                                             // it must never brake on a number it cannot trust
  const double time_have = t.range_m / t.closing_ms;
  const double time_need = car.latency_s + t.closing_ms / (2.0 * car.grip_ms2) + margin_s;
  return time_have <= time_need;
}

// The same rule as a range: the distance at which braking must begin.
double trigger_range(double closing_ms, const Car& car, double margin_s) {
  if (!(closing_ms > 0.0) || !(car.grip_ms2 > 0.0)) return 0.0;
  return closing_ms * (car.latency_s + margin_s) + closing_ms * closing_ms / (2.0 * car.grip_ms2);
}

Test it on the numbers above. At 40 m and 20 m/s closing, the time we have is 2.0 s and the time we need is 1.55 s, so no brake yet. At 30 m the time we have is 1.5 s, under 1.55 s, so brake. The trigger range is 20 × 0.3 + 400 / 16 = 31 m.

When the last line shares a failure

One failure mode matters from the first day. Suppose the layer reads its objects from the main stack's object list. Then the main computer freezes. The planner stops, and so does every update to the object list. The layer keeps reading the last list, which shows an empty road. Both lines fail at the same moment, for the same reason.

How do you find this in a log? Plot the timestamp of each input the layer used, against the layer's own clock. If the input timestamps stop advancing while the layer keeps running, the layer was acting on old data. Chapter 8 builds the defences: its own sensor path, its own checks on how old each input is, and a rule that old data never counts as an empty road.

The whole lesson in one line. Estimate how much time is left before impact, compare it with how much time braking needs, act in stages, and refuse to act on evidence you cannot trust, all inside a fixed time budget on hardware that does not share the main stack's failures.

A perception onboard software lead at a robotics or vehicle company owns this layer, or works closely with the team that does. It is a favourite interview topic because it mixes physics, statistics, real-time code and judgement. Here is the road.

  1. Stopping distance from zero: reaction distance plus braking distance, and why speed hurts twice. This is the hero's speed and grip.
  2. Time to collision: range over closing speed, its blind spots, and the enhanced form with acceleration. This is the hero's trigger.
  3. The latency chain: from photon to brake pressure, stage by stage, in milliseconds and metres. This is the hero's latency.
  4. Deciding to brake: required deceleration, the warning, partial and full cascade, hysteresis and a latch.
  5. Braking for ghosts: signs, bridges, manhole covers, the next lane on a curve, and the false-positive budget. This is the hero's ghost road.
  6. A track you can trust: confirmation counts, two sensors before full braking, coasting, and what each costs in metres.
  7. Collision checking with simple shapes: boxes, circles, swept paths and margins, in C++.
  8. Staying independent: why the last line must not share the failures it backs up.
  9. What the driver sees: a display that matches the system's belief, with bounded delay.
  10. Testing it: scenario sweeps, replays, and how many kilometres prove a rare event is rare.
  11. The active-safety bench: five scenarios, every knob, hundreds of runs. Break it on purpose.
  12. Interview arsenal: cheat sheet, design prompts, drills and debugging scenarios.
An interviewer asks: "A learned model detects more objects than your simple tracker. Why keep the emergency-braking layer simple and deterministic?"

Chapter 1

Stopping distance from zero

Add the distance before braking to the distance while braking, and see why speed hurts twice

A child steps out between two parked cars, 30 metres ahead. You are driving at 50 km/h. Can you stop? The answer has two parts, and most people forget the first one.

First, nothing happens for a while. Your eyes must notice the child, your brain must decide, and your foot must move to the pedal. During that time the car keeps its full speed. The distance it covers is the reaction distance.

Then the brakes work. The tyres push back on the road and the car slows. The distance it covers while slowing is the braking distance. The stopping distance is the sum of the two.

Part one: the distance before braking

While nobody brakes, the speed is constant. Distance is speed times time. So the reaction distance is the speed times the delay. A human driver's delay is typically about 1 to 1.5 seconds; it is longer when the driver is surprised or distracted. A machine's delay is shorter, typically a few tenths of a second, but never zero. Chapter 3 counts where those tenths go.

dreact = v × treact
dreact
the distance covered before the brakes start to slow the car, in metres
v
the speed, in metres per second; divide km/h by 3.6
treact
the delay before braking begins, in seconds: a person's reaction time, or a system's latency

Part two: the distance while braking

Now derive the braking distance. Assume the brakes slow the car at a steady rate, a constant deceleration a, in metres per second per second. "8 m/s²" means the car loses 8 m/s of speed every second.

  1. Speed falls in a straight line: after t seconds, the speed is v − a t.
  2. The car stops when v − a t = 0, so the time to stop is v / a.
  3. Speed falls evenly from v to 0, so the average speed while braking is v / 2.
  4. Distance is average speed times time: (v / 2) × (v / a) = v² / (2a).
dbrake = v² / (2 a)     dstop = v treact + v² / (2 a)
dbrake
the distance covered while slowing from v to zero, in metres
v
the speed when braking starts, in m/s; it appears squared, which is the whole story of this chapter
a
the deceleration the road and tyres allow, in m/s²: typically about 7 to 9 on dry asphalt, less on a wet road, much less on snow or ice
dstop
the stopping distance: reaction distance plus braking distance
treact
the delay before braking, as above

The same result falls out of a formula from school physics, vend² = v² − 2 a d. Put vend = 0 and solve for d. Two routes, one answer: that is a good sign.

Split the stopping distance

The bar shows the road ahead to scale. The first part is the reaction distance, the second the braking distance. The faint bar below is the same car at twice the speed. The child stands at 30 m.

50 km/h
1.50 s
8.0 m/s²

Constant deceleration from the first instant of braking. Real brakes take a short time to build pressure; Chapter 3 shows why that adds about half the build-up time to the delay. Typical figures only.

Worked at two speeds

Take a human delay of 1.5 s and a dry road at 8 m/s². Work 50 km/h first. The speed is 50 / 3.6 = 13.89 m/s.

reaction 13.89 × 1.5 = 20.83 m braking 13.89² / (2 × 8) = 192.9 / 16 = 12.06 m stopping 20.83 + 12.06 = 32.9 m

Now 100 km/h, which is 27.78 m/s.

reaction 27.78 × 1.5 = 41.67 m (twice as far) braking 27.78² / (2 × 8) = 771.6 / 16 = 48.23 m (four times as far) stopping 41.67 + 48.23 = 89.9 m (2.73 times as far)

Doubling the speed doubles the reaction distance, because it grows with v. It quadruples the braking distance, because that grows with v². The total lands in between, here 2.73 times as far. At higher speeds the braking part dominates, so the ratio creeps toward four.

Back to the child at 30 m. A human at 50 km/h needs 32.9 m, so the car hits. How hard? After the 20.83 m of reaction distance, 9.17 m remain. The speed at the child is √(13.89² − 2 × 8 × 9.17) = 6.8 m/s, about 24 km/h. A machine with a 0.3 s delay needs only 4.17 + 12.06 = 16.2 m, and stops 13.8 m short.

Why a machine helps most here. The machine cannot brake harder than the tyres allow; physics sets a. What it can shrink is the delay. At 50 km/h, cutting the delay from 1.5 s to 0.3 s saves 16.7 m, more than the whole braking distance.

From distance to a trigger time

The layer needs a rule for when to brake. Suppose an object is stopped ahead, and we brake at a range R. We stop in time if R is at least the stopping distance with the system's latency tL as the delay. Divide both sides by v, because R / v is the time left before impact at constant speed.

Ttrigger ≥ tL + v / (2 a)
Ttrigger
the time before impact at which braking is triggered, in seconds; Chapter 2 names it the time to collision
tL
the system's latency, from the moment the object is visible to the moment the brakes bite
v
the closing speed, in m/s
a
the deceleration the road allows, in m/s²

72 km/h, dry: 0.3 + 20 / 16 = 1.55 s  ·  72 km/h, wet (5 m/s²): 0.3 + 20 / 10 = 2.30 s  ·  130 km/h, dry: 0.3 + 36.1 / 16 = 2.56 s

This is why a fixed trigger time cannot be right everywhere. The needed trigger grows with speed and with lower grip. Go back to the hero, set 130 km/h, and see that a 2.0 s trigger no longer stops the car.

Here is the arithmetic as code. It is small, but it already shows the habits of the whole layer: plain structs, no heap, explicit units, and an answer for every bad input.

// Stopping distance = distance at full speed before braking + distance while braking.
// Units: metres, seconds, m/s, m/s^2. Plain structs, no heap, no exceptions.
#include <cmath>

struct StopParts {
  double reaction_m;   // covered at full speed before the brakes bite
  double braking_m;    // covered while slowing at constant deceleration
  double total_m() const { return reaction_m + braking_m; }
};

constexpr double kmh_to_ms(double kmh) { return kmh / 3.6; }

// v: speed (m/s), t_react: delay before braking (s), a: deceleration (m/s^2)
StopParts stopping_distance(double v, double t_react, double a) {
  StopParts s{0.0, 0.0};
  if (!(v > 0.0)) return s;              // standing still, or a NaN speed: nothing to stop
  s.reaction_m = v * t_react;            // constant speed: distance = speed x time
  if (!(a > 0.0)) {                      // no grip at all: we never stop, so say so
    s.braking_m = INFINITY;
    return s;
  }
  s.braking_m = v * v / (2.0 * a);       // from v_end^2 = v^2 - 2 a d, with v_end = 0
  return s;
}

// The latest time to collision at which braking can still stop short of a
// stopped object: the latency, plus the time-equivalent of the braking distance.
double latest_trigger_ttc(double v, double t_latency, double a) {
  if (!(a > 0.0)) return INFINITY;       // no grip: no trigger is early enough
  return t_latency + v / (2.0 * a);      // from v*T >= v*t_L + v^2 / (2a)
}

The tests check the worked numbers: 32.9 m at 50 km/h, 89.9 m at 100 km/h, and a latest trigger of 1.55 s at 20 m/s, 0.3 s and 8 m/s². They also check that zero grip gives an infinite braking distance and a NaN speed gives zero, never a crash.

Failure mode: the road gave less grip than the trigger assumed

A layer tuned for a dry road meets a wet one. Its trigger assumes 8 m/s², but the tyres can only deliver about 5. It brakes at 1.55 s, which is now too late: at 72 km/h it needed 2.30 s. The car hits at a reduced but real speed.

How to diagnose it from a log: compare the commanded deceleration with the achieved deceleration, which you get from the change in wheel speed or the inertial sensor. If the achieved value sits well below the command while the wheels slip, the road gave less grip than the trigger assumed. The fix is to estimate grip conservatively (wipers on, low temperature, slip seen during earlier braking) and to move the trigger earlier when grip is uncertain.

An interviewer asks: "Your stopping distance is about 33 m at 50 km/h and about 90 m at 100 km/h. Why does doubling the speed nearly triple it?"

Chapter 2

Time to collision

Turn range and closing speed into seconds, and find where that number lies

You follow a van on a highway. It is 40 m ahead and slower than you, so the gap shrinks by 10 metres every second. If nothing changes, you reach it in 4 seconds. Then its brake lights come on. Is it still 4 seconds?

The layer reads two numbers from its track of the van. The range R is the distance from our front bumper to the van's rear. The closing speed vc is how fast that range shrinks: our speed minus the van's speed. Radar measures it directly, from the Doppler shift; a camera estimates it from how fast the van grows in the image.

TTC = R / vc     only when vc > 0
TTC
the time to collision: seconds until contact if neither car changes speed
R
the range from our front to the object's back, in metres
vc
the closing speed, in m/s: positive when the gap shrinks; zero or negative means no collision ahead at constant speed

Worked: R = 40 m, our speed 25 m/s, the van's 15 m/s. Then vc = 25 − 15 = 10 m/s and TTC = 40 / 10 = 4.0 s.

Why time is the natural trigger

Range alone is a bad trigger. 30 m is far at 20 km/h and almost too late at 120 km/h. TTC folds speed in. It is measured in seconds, and so is everything it gets compared with: the latency of Chapter 3, a driver's reaction time, the braking time of Chapter 1. That is why warnings and brakes are often triggered on TTC, or on numbers built from it.

Where TTC lies

TTC assumes constant speeds. Real traffic breaks that in four ways.

The enhanced form, with acceleration

Fix the first two lies by letting the speeds change. Call the relative acceleration arel = alead − aego, where braking counts as negative. If the van brakes at 6 m/s² and we hold our speed, arel = −6. The gap then follows the same school formula as any distance under constant acceleration.

gap(t) = R − vc t + ½ arel t²
gap(t)
the range t seconds from now, if both accelerations hold
t
time from now, in seconds
R
the range now
vc
the closing speed now
arel
the lead's acceleration minus ours, in m/s²; negative when the lead brakes harder than we do

The enhanced TTC is the first time the gap reaches zero. Set gap(t) = 0. That is a quadratic, ½arel t² − vc t + R = 0, and the school formula solves it. Work the van:

½(−6) t² − 10 t + 40 = 0 → −3 t² − 10 t + 40 = 0 discriminant 10² − 4(−3)(40) = 100 + 480 = 580, √580 = 24.08 roots t = (10 ± 24.08) / (2 × −3) = −5.68 or 2.35 s take the smallest positive root: enhanced TTC = 2.35 s (plain TTC said 4.0 s)

The van's brake lights cut the true time from 4.0 s to 2.35 s. A layer using plain TTC thinks it has 1.65 s more than it does. At 25 m/s that is 41 m of false comfort.

One check remains. The formula assumes the van keeps braking. It stops after 15 / 6 = 2.5 s. Our contact at 2.35 s comes first, so the answer stands. If the van had stopped first, the code must recompute with a stopped van.

Now flip the sign: if the van accelerates at 2 m/s², the discriminant is 100 − 4(1)(40) = −60. There is no real root, so the gap never closes. Plain TTC would still say 4.0 s.

Watch TTC lie

The road shows our car behind the van. The plot shows three curves as time passes: plain TTC, enhanced TTC, and the true time left, which only hindsight knows. Brake the van, or make it speed up.

−6.0
40 m
15 m/s

We hold 25 m/s and never brake, so the curves show what each estimate believes. The van stops when its speed reaches zero. Enhanced TTC is recomputed every 50 ms from the current speeds and accelerations, exactly as a layer would.

Watch the plain TTC curve. Behind a braking van it sits above the true curve the whole way, and then collapses at the end. Behind an accelerating van it falls toward a collision that never comes. The enhanced curve tracks the truth until the van stops; then it jumps to the plain value, because a stopped van has no acceleration.

The code, with every guard

Here are both forms in C++. Notice how much of the code is guards. Each guard answers a question an interviewer will ask: what if the closing speed is zero, negative, NaN? What if arel is tiny? What if both roots are in the past?

#include <cmath>
#include <limits>

constexpr double kNoCollision = std::numeric_limits<double>::infinity();

// Constant-velocity TTC. range: metres to the object's rear.
// closing: how fast the range shrinks (m/s) = our speed - the lead's speed.
double ttc_cv(double range, double closing) {
  if (!(range > 0.0)) return 0.0;               // touching, or a NaN range: assume the worst
  if (!(closing > 1e-3)) return kNoCollision;   // receding or level: no collision ahead
  return range / closing;                       // safe: closing > 1e-3, never zero
}

// Enhanced TTC with relative acceleration a_rel = a_lead - a_ego (m/s^2).
// Solves range - closing*t + 0.5*a_rel*t^2 = 0 for the smallest t > 0.
// Valid while both accelerations hold; once the lead stops, recompute.
double ttc_accel(double range, double closing, double a_rel) {
  if (!(range > 0.0)) return 0.0;
  if (std::fabs(a_rel) < 1e-6) return ttc_cv(range, closing);  // the quadratic is a line
  const double A = 0.5 * a_rel, B = -closing, C = range;
  const double disc = B * B - 4.0 * A * C;
  if (disc < 0.0) return kNoCollision;          // the gap never reaches zero
  const double sq = std::sqrt(disc);
  // Stable roots: never subtract two nearly equal numbers.
  const double q = -0.5 * (B + std::copysign(sq, B));
  double t1 = q / A;
  double t2 = (q != 0.0) ? C / q : kNoCollision;
  if (t1 > t2) { const double tmp = t1; t1 = t2; t2 = tmp; }
  if (t1 > 0.0) return t1;                      // the first future contact
  if (t2 > 0.0) return t2;
  return kNoCollision;                          // both roots lie in the past
}

The tests: 4.0 s for the van at constant speed; 2.347 s braking; no collision when it accelerates; and a nice corner case. A van that is pulling away (vc = −2) but braking at 4 m/s² from 20 m gives an enhanced TTC of 3.70 s. Plain TTC says "never" for that van.

Failure mode: the textbook formula brakes for nothing

A tidy engineer writes the quadratic straight from the textbook: t = (−B − √disc) / (2A). It works in every test. Then, on the road, a lead car's acceleration estimate hovers near zero, say 10−7 m/s². In single-precision float, B² and the discriminant are almost equal. The subtraction cancels every digit, and the formula returns 0.000 s. A TTC of zero means full braking, for a car 40 m away.

We compiled exactly that case: the textbook form returns 0.000000 and the stable form returns 4.000000. How do you diagnose it? The log shows a TTC that drops to zero in one cycle while range and closing speed are smooth. Any TTC that jumps without a matching jump in its inputs points at the arithmetic. The fix is in the listing above: the stable root form, plus a fallback to plain TTC when arel is close to zero.

An interviewer asks: "The lead car brakes hard. Does plain TTC = range / closing speed trigger too early or too late, and what do you do about it?"

Chapter 3

The latency chain

Follow one photon from the brake lights ahead to the pressure in our brakes, and count the metres

The car ahead brakes. Its brake lights send out light. Some of that light enters our camera. Before our own brakes squeeze, that light must become pixels, pixels must become an object, and the object must become a decision and then pressure in a pipe. Every step takes time, and the car keeps moving the whole while.

The latency of the layer is the time from the moment something becomes visible to the moment the brakes actually slow the car. Engineers call it "photon to brake". It is the tL of Chapter 1, and it is spread over a chain of stages owned by different teams.

The stages, with typical times

Here is a typical chain for a camera path. The numbers are illustrative; real systems differ widely. What carries over is the shape: many small stages, one big actuator stage, and a hidden wait.

  1. Exposure and readout (about 25 ms). The sensor collects light, then reads the rows out one by one.
  2. Transfer and image preparation (about 15 ms). Pixels travel to the computer and get corrected for colour and lens distortion.
  3. Perception (about 40 ms). A model or a classical detector turns the image into detections.
  4. Tracking and fusion (about 10 ms). Detections update tracks; radar and camera get combined.
  5. Waiting for the next cycle (about 25 ms on average). The layer runs every 50 ms in this example. A hazard that appears just after a cycle starts waits for the next one: on average half a cycle, at worst a whole one.
  6. Decision (about 2 ms). The layer's own logic: small, and it should stay small.
  7. Bus to the brake controller (about 10 ms). The command crosses the vehicle network.
  8. Brake pressure (about 140 ms effective). Pumps and valves need time before pressure starts to rise, and more time to build it fully.

Count the milliseconds

The top bar is the chain, stage by stage, to scale in milliseconds. A pulse runs along it while our car rolls along the ruler below. Change the speed, the model, and the cycle time.

100 km/h
40 ms
50 ms

Illustrative stage times. "Worst case" uses the slow figure for every stage at once, which is pessimistic but is how a latency budget is checked. The brake stage is shown as its effective delay: dead time plus half the build-up ramp.

What a millisecond costs

Add the typical stages: 25 + 15 + 40 + 10 + 25 + 2 + 10 + 140 = 267 ms. At 100 km/h, which is 27.78 m/s, the car covers 27.78 × 0.267 = 7.4 m before the brakes bite. With every stage at its worst, the chain is 383 ms and the car covers 10.6 m.

1 ms at 100 km/h = 27.78 × 0.001 = 2.8 cm  ·  100 ms = 2.8 m, about two thirds of a car length

So a team that shaves 20 ms off the perception model buys 56 cm at highway speed. A team that adds a 100 ms filter "to make it smoother" spends 2.8 m. Every stage owner should know this conversion by heart.

Why the brake stage counts as half its ramp

Brake pressure does not appear at once. Suppose the deceleration rises in a straight line from 0 to a over a ramp time Tr. During the ramp the average deceleration is a / 2, so the car loses a Tr / 2 of speed. A car that waited Tr / 2 and then braked fully for Tr / 2 would lose the same speed.

What about distance? Work it for a ramp of 0.18 s at 27.78 m/s and a = 8 m/s². The true ramp covers v Tr − a Tr² / 6. The "wait half, then full" model covers v Tr − a Tr² / 8. They differ by a Tr² / 24 = 8 × 0.0324 / 24 = 0.011 m. One centimetre. So a ramp counts as a pure delay of half its length, plus any dead time before it starts.

The hidden stage. The wait for the next cycle is in nobody's code, so nobody owns it. Halving the cycle period from 50 ms to 25 ms saves 12.5 ms on average and 25 ms in the worst case, with no algorithm change at all.

A budget the build can check

The trigger thresholds of Chapter 4 are tuned for one latency. If someone later slows a stage, the thresholds silently become late. The cure is to write the budget down as code, so the compiler checks it. The static_assert below fails the build if the worst-case chain exceeds the budget the triggers assume.

#include <array>
#include <cstdint>

struct ChainStage { const char* name; std::uint16_t typical_ms; std::uint16_t worst_ms; };

// Illustrative numbers. The point is the bookkeeping, not the values.
constexpr std::array<ChainStage, 8> kChain{{
  {"exposure + readout",          25,  35},
  {"transfer + image prep",       15,  20},
  {"perception model",            40,  60},
  {"tracking + fusion",           10,  15},
  {"wait for the next cycle",     25,  50},   // on average half a 50 ms cycle; worst, all of it
  {"decision",                     2,   3},
  {"bus to brake controller",     10,  20},
  {"brake pressure (effective)", 140, 180},   // dead time + half the build-up ramp
}};

constexpr unsigned sum_ms(bool worst) {
  unsigned s = 0;
  for (const ChainStage& st : kChain) s += worst ? st.worst_ms : st.typical_ms;
  return s;
}

// The latency the trigger thresholds were tuned for. If someone adds a stage
// or slows one down, the build fails here instead of the car braking late.
constexpr unsigned kBudgetWorstMs = 400;
static_assert(sum_ms(true) <= kBudgetWorstMs, "latency chain exceeds the budget the triggers assume");

// Metres covered during a delay: what every millisecond costs.
constexpr double metres_lost(double speed_ms, unsigned delay_ms) {
  return speed_ms * delay_ms / 1000.0;
}

The tests confirm the sums at compile time: 267 ms typical and 383 ms worst, under the 400 ms budget. At 100 km/h they cost 7.42 m and 10.64 m. A listing of numbers in a header is not a measurement, of course. It is a contract that a timing test on the real target must keep.

Failure mode: the average is fine and the tail is not

A layer averages 267 ms in every lab test. Then, once in about ten thousand cycles, a memory allocation in the tracker triggers a page fault and the cycle takes 120 ms longer. The mean barely moves. But at 100 km/h that one slow cycle costs 3.3 m, and it can fall on the cycle that matters.

How to diagnose it: stamp each message with its capture time and log the stamp at every stage. Plot a histogram per stage and look at the 99.99th percentile and the maximum, not the mean. A long tail in one stage with a flat tail everywhere else points at that stage. The lesson on real-time deterministic C++ covers the usual causes: allocation on the hot path, locks, priority inversion and cache misses.

An interviewer asks: "Your perception team saves 20 ms. Your actuator supplier adds 100 ms of filtering. At 100 km/h, what is the net effect on braking?"

Chapter 4

Deciding to brake

Compare the braking we need with the braking we have, and act in three stages

You roll toward a red light where a car is already waiting. Far away, you lift off the pedal. Closer, you press gently. If you looked up late, you stamp on it. You are already running the logic of this chapter: you compare how hard you must brake with how hard you can.

The braking we need

Chapter 1 gave the braking distance v² / (2a). Turn it around. Given the room we have, what steady deceleration stops us just in time? That number is the required deceleration, areq. The room is the range, minus what the latency eats, minus a small safety margin so that we stop a little short instead of exactly touching.

areq = vc² / ( 2 ( R − vc tL − dm ) )     compare with    amax
areq
the steady deceleration that stops the closing just short of the object, in m/s²
vc
the closing speed; for a lead car moving at constant speed, this works in the lead's frame too
R
the range now
tL
the latency before braking bites (Chapter 3); the car closes vc tL metres meanwhile
dm
the stopping margin, in metres, for example 1 m
amax
the deceleration the road allows (the grip); if areq exceeds it, braking alone cannot avoid the collision

Worked: we close at 20 m/s on a car 40 m ahead, with tL = 0.3 s and dm = 1 m. The room is 40 − 6 − 1 = 33 m. So areq = 400 / 66 = 6.06 m/s². A dry road gives about 8, so braking can still stop us, but we are using three quarters of the grip.

Why is areq a better trigger than TTC alone? It answers the question we care about: "is braking still enough, and how hard must it be?" Recall the misread of Chapter 2: a 1.5 s TTC at 2 m/s needs almost no braking, while the same TTC at 30 m/s needs more than the tyres can give. areq tells those two apart. Many designs use both: TTC for the warning, areq for braking.

Three stages, not one

A single "brake now" threshold forces a bad choice: set it early and the car brakes hard for every ghost; set it late and nobody gets a chance to react. So the response is staged.

  1. Warning. A sound and a symbol, early enough for an attentive driver to brake. It costs little when wrong: an annoyed driver.
  2. Partial braking. A firm but moderate brake, for example 4 m/s² (illustrative). It sheds speed, builds brake pressure, and gets the driver's attention, while the evidence keeps growing.
  3. Full braking. Everything the tyres allow. It is reserved for when the collision is close and the evidence is strong, because a needless full brake can cause a rear-end crash.

Give each stage a threshold on areq, for example 3.0, 4.5 and 6.0 m/s² (illustrative). At a steady 20 m/s of closing with our latency and margin, the stage begins where vc² / (2 (R − 7)) reaches each threshold:

warning a_req ≥ 3.0 → R = 7 + 400 / 6.0 = 73.7 m (TTC 3.68 s) partial a_req ≥ 4.5 → R = 7 + 400 / 9.0 = 51.4 m (TTC 2.57 s) full a_req ≥ 6.0 → R = 7 + 400 / 12.0 = 40.3 m (TTC 2.02 s)

These are the ranges if nothing else changes. In reality the warning makes the driver brake, and partial braking lowers the closing speed. So areq falls, and full braking may never be needed. That is the point of the cascade.

What if areq already exceeds amax? Then the collision cannot be avoided by braking. Brake fully anyway. Impact energy grows with the square of speed, so every m/s shed matters. In the hero, braking at a TTC of 1.0 s still hits, but at 48 km/h instead of 72: 44% of the energy.

Warn, then partial, then full

Our car closes on a stopped car at 20 m/s. The plot shows the measured areq with its noise, the three enter levels (solid) and exit levels (dashed). The band below is the stage each cycle. Switch hysteresis and the latch off and count the changes.

1.5×

Toy: 50 ms cycles, 0.3 s latency, partial braking 4 m/s², full 8 m/s². Noise at 1× is 0.8 m on range and 0.5 m/s on closing speed. Thresholds are illustrative, not from any product or test protocol.

Hysteresis: a stage must not flicker

Measurements are noisy. When areq hovers near 3.0, a plain threshold turns the warning on, off, on, off, ten times a second. The driver hears a stutter and learns to ignore it. The fix is hysteresis: enter a stage at one level, but leave it only at a lower level, and only after several calm cycles in a row.

We ran the C++ below on twelve noisy readings around 3.0 (2.8, 3.1, 2.9, 3.05 and so on). With no hysteresis the stage changed 11 times. With an exit level of 2.0 and a hold of 3 cycles it changed once: on, and stayed on. Notice what hysteresis does not do. It never delays a step up. Escalation is immediate; only the step down waits.

The latch: full braking must not pump

Full braking creates its own trap. Braking lowers the closing speed, so areq falls below the full threshold, so the brake releases, so the closing speed rises again. The car pumps its brakes, and loses metres every time pressure rebuilds. A latch holds full braking until the car stops or the target is clearly gone. Switch the latch off in the device and watch the band stutter near the end.

#include <cstdint>

enum class Stage : std::uint8_t { None = 0, Warn = 1, Partial = 2, Full = 3 };

// Deceleration that stops the closing just short of the object.
// range (m), closing (m/s), t_lat: latency before braking bites (s), margin (m)
double required_decel(double range, double closing, double t_lat, double margin) {
  if (!(closing > 0.0)) return 0.0;                      // not closing: nothing to do
  const double room = range - closing * t_lat - margin;  // what is left after the latency
  if (room <= 0.01) return 1e3;                          // no room left: no brake is enough
  return closing * closing / (2.0 * room);               // v^2 = 2 a d, solved for a
}

// Per stage {Warn, Partial, Full}, in m/s^2. exit < enter gives hysteresis.
struct Thresholds { double enter[3]; double exit[3]; std::uint8_t hold_cycles; };

struct Decider {
  Stage stage = Stage::None;
  std::uint8_t calm = 0;    // cycles in a row below the current stage's exit level

  Stage step(double a_req, bool target_valid, bool ego_stopped, const Thresholds& th) {
    const int cur = static_cast<int>(stage);
    // The latch: full braking holds while the target is real and we still move.
    if (stage == Stage::Full && target_valid && !ego_stopped) return stage;
    int want = 0;                                        // highest stage whose enter level is met
    for (int s = 0; s < 3; ++s)
      if (target_valid && a_req >= th.enter[s]) want = s + 1;
    if (want > cur) { stage = static_cast<Stage>(want); calm = 0; return stage; }  // escalate now
    if (cur == 0) { calm = 0; return stage; }
    // De-escalate one stage only after hold_cycles in a row below its exit level.
    const bool below = !target_valid || ego_stopped || a_req < th.exit[cur - 1];
    calm = below ? static_cast<std::uint8_t>(calm + 1) : 0;
    if (calm >= th.hold_cycles) { stage = static_cast<Stage>(cur - 1); calm = 0; }
    return stage;
  }
};

The tests check the worked areq of 6.06 m/s² and the 11 against 1 stage changes. They also check a latch that holds while the target is valid, and a release that steps down one stage after three calm cycles once the target is gone. The decider keeps two bytes of state and runs a fixed loop of three. It cannot allocate, throw or take a variable time.

Failure mode: the latch that would not let go

A car ahead turns off into a side street while we brake for it. Our car keeps braking hard, on an empty road, for another second. The latch did its job too well: it holds while the target is "valid", and the track of the turning car kept coasting on its last prediction.

How to diagnose it: log, every cycle, the stage, the latch state and the reason the target counts as valid (fresh detection or coasting). Here the log shows full braking with "coasting" for 20 cycles. The fix belongs to Chapter 6: cap the coasting time for a latched target, and release the latch when the target leaves the path, not only when it vanishes.

An interviewer asks: "Why does full braking need a latch, and what releases it?"

Chapter 5

Braking for ghosts

Find out why signs, manhole covers and the next lane look like a stopped car, and how to tell

A highway passes under a steel sign gantry. To a radar, the gantry is a large, strong, stationary reflector, straight ahead and closing at our full speed. That is exactly what a stopped car looks like. If the layer believes it, the car brakes hard on an empty highway, with a truck behind.

A false positive (or false activation) is a warning or brake with no real hazard. Engineers often call a false brake phantom braking, and its cause a ghost. A false negative is the opposite: a real hazard the layer misses. Chapter 0 showed the trade in the hero: every move that catches hazards earlier also catches more ghosts.

Where ghosts come from

Radar and camera fail in different ways, which is the most useful fact in this chapter.

RadarCamera
Strong atrange and closing speed, in rain, fog and darknesswhat an object is, where its edges are, which lane it is in
Weak atheight, fine sideways position, telling a car from a signrange far away, glare, darkness, a dirty lens
Typical ghostssign gantries, bridges, manhole covers, expansion joints, guardrails, a can on the roadshadows, road markings, a picture of a car on a truck, spray, reflections
Why stationary is hardthe road is full of stationary metal; a stopped car looks like all of ita stopped car looks like a parked car beside the road

Because the failures differ, a ghost that fools one sensor usually does not fool the other. A gantry gives a strong radar return but no car in the image. A shadow fools a camera but returns nothing to radar. Chapter 6 turns this into a rule: full braking needs both.

The "in my lane" test

Many ghosts are real objects that are simply not in our way: a car in the next lane, a parked car, a guardrail. The layer must predict where our car will go and keep only objects in that corridor. That is the in-path test.

The simplest prediction is a straight line. On a curve it is wrong. A better one uses the yaw rate, how fast the car is turning, in radians per second, from the inertial sensor. Divide by speed and you get the curvature k of the path, one over its radius. For small distances the path's sideways offset grows with the square of the distance.

k = ω / v     ypath(x) ≈ ½ k x² = x² / (2 Rc)
k
the path's curvature, in 1/m
ω
the yaw rate, in rad/s, positive when turning left
v
our speed, in m/s
ypath
how far sideways our path is, x metres ahead
x
distance ahead along our current heading, in metres
Rc
the radius of the curve, 1 / k

Work a gentle highway curve of radius 500 m at 25 m/s. The yaw rate is 25 / 500 = 0.05 rad/s, about 2.9 degrees per second. At 60 m ahead, our lane has moved sideways by 60² / 1000 = 3.6 m (the exact circle gives 3.61 m). A lane is about 3.5 m wide. So the car in the next lane on the outside of the curve sits at about 3.61 − 3.5 = 0.11 m from the straight line, dead ahead.

The straight line fails twice. On that curve, a straight-line in-path test flags the harmless car in the next lane as a threat. And it ignores a stopped car in our own lane at 90 m, because our lane is about 8.2 m to the side of the straight line there. One wrong assumption gives a ghost and a miss at once.

Which objects are in my path?

A top-down view of a curving road. Our car is at the bottom. The warm corridor is the path the layer predicts. Objects inside it get a warm ring. Change the curve and the path model, then switch on the two extra checks.

left, 500 m
0.0 °/s

Toy road at 25 m/s: our lane 3.5 m wide. The car in our lane is stopped at 90 m (yellow). A car in the outer lane drives at 60 m. A sign gantry spans the road at 75 m and a manhole cover lies in our lane at 35 m; radar sees both as stationary returns. Corridor: half our width plus the object's half width plus 0.2 m, plus 0.005 m per metre of distance. Sideways distances are drawn stretched so the lanes stay visible.

Try the straight line on the 500 m curve: one ghost (the car in the next lane) and one miss (our stopped car). Switch to the arc and both problems vanish. Now add a yaw-rate bias of 0.5 degrees per second. 0.5 degrees per second is 0.0087 rad/s. At 25 m/s it changes the predicted curvature by 0.0087 / 25 = 0.00035 per metre. That moves the path 0.6 m sideways at 60 m and 1.4 m at 90 m. Small biases matter far ahead.

The gantry and the manhole cover are in our path, so the path test cannot remove them. Two other checks do. A radar that measures height (elevation) can see that the gantry is 5 m up. And neither object looks like a car to the camera. Switch on both checks and both ghosts are gone.

#include <cmath>

struct PathModel { double speed; double yaw_rate; };   // m/s, rad/s (left turn positive)
struct Obj { double x, y; double half_width; };         // our frame: x ahead, y left (m)

// Lateral position of our predicted path at distance x ahead, for constant
// curvature k = yaw_rate / speed. Exact circle; close to k x^2 / 2 for small x.
double path_y(const PathModel& p, double x) {
  if (!(p.speed > 1.0)) return 0.0;          // near standstill, curvature is noise: go straight
  const double k = p.yaw_rate / p.speed;
  if (std::fabs(k) < 1e-6) return 0.0;       // straight road
  const double R = 1.0 / k;
  if (std::fabs(x) >= std::fabs(R)) return 0.5 * k * x * x;  // past a quarter turn: approximate
  return R - std::copysign(std::sqrt(R * R - x * x), R);
}

// "In my lane?" The object overlaps the corridor our car will sweep, plus a
// margin that grows with distance, because a small yaw-rate error grows as x^2.
bool in_path(const PathModel& p, const Obj& o, double ego_half_width,
             double margin0, double margin_per_m) {
  if (!(o.x > 0.0) || o.x > 150.0) return false;  // behind us, or past the range we trust
  const double offset = std::fabs(o.y - path_y(p, o.x));
  const double corridor = ego_half_width + o.half_width + margin0 + margin_per_m * o.x;
  return offset < corridor;
}

The tests reproduce the curve: path_y(60) = 3.613 m; the next-lane car is out of the corridor with the arc and in it with a straight line; our own stopped car is the reverse. Near standstill the code refuses to divide a noisy yaw rate by a tiny speed and assumes straight ahead.

The false-positive budget

How rare must ghosts be? Teams express this as a false-positive budget: a target number of false activations per distance driven, set separately for each stage. A warning may be allowed more often than a full brake. Here is an illustrative calculation, not any real requirement.

ghost candidates about 1 per km (gantries, bridges, metal in the road) budget for full braking 1 per 1,000,000 km (an illustrative team target) allowed per candidate 1 / 1,000,000 = 0.000001 radar alone fooled 1 in 1,000 (illustrative) camera alone fooled 1 in 1,000 (illustrative) both, if independent 0.001 × 0.001 = 0.000001

Now scale it. A fleet of 100,000 cars driving 15,000 km a year covers 1.5 billion km. Even at one false full brake per million km, that is 1,500 events a year. This is why the budget is so strict, and why no single sensor is enough. The independence in that last line is an assumption that must be checked: rain can hurt both sensors at once.

Failure mode: phantom brakes on every gentle curve

Field reports: warnings and brakes for cars in the next lane, always on long gentle curves, mostly to one side. That pattern points at the path prediction. Check two things in the logs. First, the yaw rate while the car stands still: it should read zero, and a steady offset is a sensor bias. Second, compare the path predicted at each moment with the path the car actually drove, which you know a few seconds later. A one-sided growing gap is a bias or a wrong sign.

The fixes: estimate the yaw-rate bias whenever the car stands still, widen the corridor margin with distance (as the listing does), and treat far objects with less confidence than near ones.

An interviewer asks: "On gentle curves your layer warns for cars in the next lane. What is the likely cause, and how do you confirm it?"

Chapter 6

A track you can trust

Demand repeated, agreeing evidence before full braking, and price every cycle of waiting in metres

Rain on the highway. The radar reports a stopped object at 60 m in one cycle, then nothing, then the object again. Is it a stopped car half hidden by spray, or the spray itself? The layer cannot know from one cycle. It can wait for more evidence, but every cycle of waiting costs road.

The layer keeps its own small tracker for this. A track is its running estimate of one object, built from many detections, each one measurement from one sensor in one cycle. Why not just use the main stack's tracks? Because the last line must not share the main stack's failures (Chapter 8), and because a tiny tracker is easy to check. The full method lives in the multi-target tracking lesson, with the Kalman filter inside each track. Here we need three ideas from it.

Idea one: confirmation counts

A track is confirmed once it has M detections in its last N cycles: M-of-N logic. A real object, detected with probability pD each cycle, passes easily. A random ghost, which shows up with a small probability pF in any one cycle, rarely does.

real object, pD = 0.9, confirmed within 3 cycles: 2 of 3: 3 × 0.9² × 0.1 + 0.9³ = 0.243 + 0.729 = 0.972 3 of 3: 0.9³ = 0.729 random ghost, pF = 0.05 in each cycle: 2 of 3: 3 × 0.05² × 0.95 + 0.05³ = 0.0073 3 of 3: 0.05³ = 0.000125

The price is time. With 50 ms cycles, 3 of 3 cannot confirm before the third cycle, 100 ms after the first detection. At 25 m/s that is 2.5 m. Compare it with the hero's window: at 72 km/h on a dry road with the sign, the whole safe window was 0.2 s wide. Confirmation can eat half of it.

Idea two: two sensors before full braking

M-of-N only works against ghosts that come and go at random. A sign gantry is a persistent ghost: the radar sees it every cycle, so it passes any M-of-N. What stops it is the second sensor, which fails differently (Chapter 5). So the layer grades its evidence. One sensor confirmed may drive a warning or partial braking. Both sensors confirmed is required for full braking.

Idea three: coasting

In the middle of an emergency stop, one sensor misses one cycle. Without care, the evidence drops, the stage drops, and the brakes release for 50 ms. Coasting holds the evidence level through a short gap, for example 2 cycles, while the track's prediction carries on. A coast limit stops it from braking for an object that has really gone, the failure mode of Chapter 4.

When may we brake fully?

Each column is one 50 ms cycle; the rows are radar and camera detections. The bars below show the evidence level the rule grants. Pick a scenario and a rule, then run a thousand draws.

Toy: 20 cycles of 50 ms at 25 m/s closing; the object becomes visible at cycle 2. Independent detections each cycle. The sign is seen by radar with probability 0.9 per cycle and by the camera with 0.01. Coast limit 2 cycles. Illustrative probabilities.

Run the stopped car with 2 of 3: full braking usually comes at cycle 3 or 4 (cycle 3.4 on average over 1,000 draws). Switch to 3 of 3 and it slips about two cycles later on average (cycle 5.6), and sometimes much later, because one miss restarts the count. Now pick the sign. With "both sensors" on, full braking never comes, whatever M-of-N you choose; turn it off and the sign brakes the car almost every time.

Here is the evidence logic in C++: two 8-bit histories, a count, and a coast counter. It is the same pattern as the tracking lesson's M-of-N, kept small enough to verify by hand.

#include <cstdint>

enum class Evidence : std::uint8_t { None = 0, One = 1, Both = 2 };

// One candidate threat, updated once per cycle. Fixed size, no heap.
struct ThreatTrack {
  std::uint8_t radar_hits = 0;    // the last 8 cycles as bits, newest in bit 0
  std::uint8_t camera_hits = 0;
  std::uint8_t short_for = 0;     // cycles in a row with evidence below the held level
  Evidence level = Evidence::None;
};

inline int hits_in_last(std::uint8_t bits, int n) {   // n <= 8
  int c = 0;
  for (int i = 0; i < n; ++i) c += (bits >> i) & 1;
  return c;
}

struct ConfirmRule { int m; int n; int max_coast; };   // M of N per sensor; coast limit

// Evidence::One may drive a warning or partial braking.
// Evidence::Both (each sensor M of N) is required for full braking.
Evidence update_threat(ThreatTrack& t, bool radar, bool camera, const ConfirmRule& r) {
  t.radar_hits  = static_cast<std::uint8_t>((unsigned{t.radar_hits}  << 1u) | (radar  ? 1u : 0u));
  t.camera_hits = static_cast<std::uint8_t>((unsigned{t.camera_hits} << 1u) | (camera ? 1u : 0u));

  const bool r_ok = hits_in_last(t.radar_hits, r.n)  >= r.m;
  const bool c_ok = hits_in_last(t.camera_hits, r.n) >= r.m;
  const Evidence now = (r_ok && c_ok) ? Evidence::Both
                     : (r_ok || c_ok) ? Evidence::One : Evidence::None;

  if (now >= t.level) { t.level = now; t.short_for = 0; }   // evidence may rise at once
  else if (++t.short_for > r.max_coast) {                   // short for too long: drop
    t.level = now; t.short_for = 0;
  }
  // Otherwise coast: hold the level through a short gap, so one missed
  // detection in the middle of an emergency stop does not release the brakes.
  return t.level;
}

The tests walk one track cycle by cycle: no evidence after one radar hit; Evidence::One when radar reaches 3 of 3; Evidence::Both a cycle later; held through two missed cycles; dropped on the third. A camera that dies for good drops the level to One after the coast limit, so full braking stops being allowed while warnings continue.

Failure mode: no full braking in fog

A real stopped car appears in thick fog. The radar sees it clearly; the camera sees almost nothing. "Full braking needs both" never becomes true. The layer warns and brakes partially, but never fully, and the car hits at a reduced speed.

The log shows it plainly if you record, every cycle, the evidence level and the two hit histories: radar 11111111, camera 00000000. This is a design choice, not a bug, but it must be a known and stated choice. The layer must detect that the camera is degraded (Chapter 8), tell the driver (Chapter 9), and the team must decide what one-sensor evidence may do in that mode. Some designs allow stronger radar-only braking when the radar track is long, steady and clearly in path.

An interviewer asks: "Why does M-of-N confirmation not stop phantom braking under a sign gantry, and what does?"

Chapter 7

Collision checking with simple shapes

Move boxes and circles along their predicted paths and find the first time they touch

A child steps off the kerb between two parked cars and walks across our lane. Range and closing speed are not enough now. The child is not ahead of us on a line; the child is crossing it. Whether we hit depends on where each of us is when.

So the layer treats our car and each object as shapes in a flat map seen from above. It predicts where each shape will be at small time steps into the future and checks whether they overlap at any step. The first overlap is the predicted time of contact. Real code uses two simple shapes: boxes and circles.

Boxes: the separating axis test

A car seen from above is close to a rectangle: an oriented box with a centre, a heading, a half length and a half width. When do two boxes overlap? Shine a light along any direction and look at their shadows on a line. If you can find a direction where the shadows do not meet, the boxes cannot touch. That is the separating axis theorem.

For two rectangles you need to try only four directions: the two edge directions of each box. If all four shadows overlap, the boxes overlap. On each axis u, a box's shadow reaches out from its centre by its half length times |cos| of the angle between its long edge and u, plus its half width times |cos| of the angle between its short edge and u.

rA = LA |e1·u| + WA |e2·u|     gap on u  ⇔  |d·u| > rA + rB
rA
how far box A's shadow reaches from its centre along u
LA
box A's half length, in metres
WA
box A's half width, in metres
e1
box A's long-edge direction, a unit vector
e2
box A's short-edge direction, a unit vector
u
the axis being tested: one of the four edge directions
d
the vector from A's centre to B's centre
rB
the same reach for box B

Work one by hand. Our car is box A at the origin, heading along x, half sizes 2.4 by 0.95 m. Another car, box B, sits at (4.4, 2.2), turned 30 degrees, half sizes 2.2 by 0.9 m. So d = (4.4, 2.2), and cos 30° = 0.866, sin 30° = 0.5.

axis r_A r_B |d·u| verdict A long (1, 0) 2.400 2.355 4.400 4.40 < 4.755 overlap A short (0, 1) 0.950 1.879 2.200 2.20 < 2.829 overlap B long (0.866, 0.5) 2.553 2.200 4.911 4.91 > 4.753 gap of 0.16 m B short (−0.5, 0.866) 2.023 0.900 0.295 overlap result: no contact. Move B to (3.6, 1.8): the B-long shadow is 4.02 < 4.75, all four overlap, contact.

Notice the trap. Our own two axes both say "overlap". A lazy check that tests only our car's axes, or that puts axis-aligned boxes around both cars, reports a collision that is not there. That is a ghost made by geometry.

Circles: cheaper and more cautious

A circle has no heading, so two circles touch when the distance between centres is less than the sum of the radii. One comparison, no sine or cosine. Cover our car with three circles along its length. Each covers a third of the length, 1.6 m, and the full width. Its radius must reach the corners of its section: √(0.8² + 0.95²) = 1.24 m.

The price: the circles bulge 1.24 − 0.95 = 0.29 m past each side. Circles are conservative: they never miss a contact that boxes would find, but they find some that boxes would not. A common pattern uses circles as a fast first pass and boxes only for the pairs the circles flag.

Sweeping along the path

To find when shapes touch, step them forward. Move our box along its predicted path (Chapter 5's arc), move the object by its tracked velocity, and test at each step. The set of places the box visits is its swept volume. Enlarge the shapes by a margin for position uncertainty, for example two standard deviations of the track's position error.

Will our paths meet?

Our car moves right along its predicted path; the pedestrian walks up across the lane. Faint copies show each step of the sweep. The first overlapping pair turns red. Change the timing, the shapes, the margin and the step size.

4.0 m
0.20 m
straight
0.05 s

Our car at 15 m/s, box 4.8 by 1.9 m. Pedestrian 0.6 m square, walking up at 1.5 m/s from x = 30 m. 4 s horizon. Same geometry as the C++ test below.

With the defaults the first overlap comes at 1.85 s, when our car has travelled 15 × 1.85 = 27.75 m. Check it by hand. Our front, enlarged by the margin, reaches the pedestrian's near edge at x = 29.7 when 2.6 + 15t = 29.7, so t = 1.81 s. The pedestrian enters our widened corridor (1.15 + 0.3 = 1.45 m from the centre line) when −4 + 1.5t > −1.45, so t > 1.70 s. Both hold from 1.81 s; the first 0.05 s step after that is 1.85 s.

Now raise the time step to 0.5 s and move the pedestrian start lower. At some settings the overlap falls between two steps and the sweep sees nothing. That is tunnelling. The rule of thumb: the step times the relative speed must stay below the sum of the two shapes' sizes along the motion. Our car plus a pedestrian is 5.4 m long; at 30 m/s of relative speed the step must stay under 5.4 / 30 = 0.18 s.

#include <cmath>

struct Box { double cx, cy, heading, half_len, half_wid; };  // centre (m), rad, half sizes (m)

// Separating axis test for two rectangles. They overlap unless one of the four
// edge directions separates their shadows (projections).
bool boxes_overlap(const Box& a, const Box& b) {
  const double ca = std::cos(a.heading), sa = std::sin(a.heading);
  const double cb = std::cos(b.heading), sb = std::sin(b.heading);
  const double axes[4][2] = {{ca, sa}, {-sa, ca}, {cb, sb}, {-sb, cb}};
  const double dx = b.cx - a.cx, dy = b.cy - a.cy;
  for (const auto& u : axes) {
    // Half the shadow of each box on u: each half size times |cos| of its edge to u.
    const double ra = a.half_len * std::fabs(ca * u[0] + sa * u[1])
                    + a.half_wid * std::fabs(-sa * u[0] + ca * u[1]);
    const double rb = b.half_len * std::fabs(cb * u[0] + sb * u[1])
                    + b.half_wid * std::fabs(-sb * u[0] + cb * u[1]);
    if (std::fabs(dx * u[0] + dy * u[1]) > ra + rb) return false;   // a gap: no overlap
  }
  return true;                                // no separating axis among the four
}

// Swept check: step both boxes along their predicted motion and return the first
// time they overlap, or -1. A fixed step count keeps the work bounded.
double first_contact(Box ego, double ego_v, double ego_yaw_rate,
                     Box obj, double obj_vx, double obj_vy,
                     double inflate, double horizon_s, int steps) {
  ego.half_len += inflate; ego.half_wid += inflate;  // a margin for our own uncertainty
  const double dt = horizon_s / steps;
  for (int i = 0; i <= steps; ++i) {
    if (boxes_overlap(ego, obj)) return i * dt;
    ego.cx += ego_v * std::cos(ego.heading) * dt;
    ego.cy += ego_v * std::sin(ego.heading) * dt;
    ego.heading += ego_yaw_rate * dt;
    obj.cx += obj_vx * dt;
    obj.cy += obj_vy * dt;
  }
  return -1.0;
}

The tests check four cases. The worked pair at (4.4, 2.2) does not overlap, and the pair at (3.6, 1.8) does. A box always overlaps a box at its own centre. The crossing pedestrian gives first contact at 1.85 s, and a pedestrian who starts 9 m below is never hit inside the horizon. The loop runs exactly steps + 1 times, so its worst-case time is known before the car leaves the factory.

Failure mode: the box turned sideways

A car waits at a junction to our right. Its track's heading flips by 90 degrees for a few cycles, because its detections are noisy at that angle. The box now pokes 2.2 m into our lane instead of 0.9 m. The sweep reports contact and the layer warns for a car that is standing still beside the road.

To diagnose it, draw the boxes from the logged tracks over the camera image, cycle by cycle. A box that spins while the car in the picture does not is a heading problem upstream. The fixes: use circles (no heading) for slow or stationary objects, smooth the heading over several cycles, and refuse full braking on a contact that appears only because a heading jumped.

An interviewer asks: "Your sweep checks overlap every 0.5 s. Why might it miss a collision with a crossing car, and how do you fix it?"

Chapter 8

Staying independent

Keep the last line from sharing the failures of the stack it backs up, and decide what it does when its own inputs go bad

Night, on a motorway. The main computer hits a software fault and restarts. For eight seconds there is no perception model, no planner and no object list. Traffic ahead is slowing. This is the moment the last line exists for, and it only helps if it did not restart too.

A common cause failure is one fault that takes out two things at once: the main stack and its backup. Shared power, a shared computer, a shared clock, shared code or a shared sensor are all common causes. An independent layer avoids as many of them as it reasonably can.

Why independence is worth so much

Here is an illustrative calculation. Say the main stack fails to handle a hazard with probability 1 in 10,000 per hour of driving, and so does the layer. If their failures were fully independent, both would fail together with probability 10−4 × 10−4 = 10−8.

Now suppose 10% of each one's failures come from a cause they share (engineers call this fraction β). Then the shared part alone fails both with probability 0.1 × 10−4 = 10−5. The independent remainder adds (0.9 × 10−4)² = 8.1 × 10−9.

P(both fail) ≈ β λ + ((1 − β) λ)² = 10−5 + 8.1 × 10−9 ≈ 1.0 × 10−5  ·  1,000 times worse than independent

A tenth of shared cause wipes out three orders of magnitude. That is why architects fight over a shared power rail or a shared library. The numbers are illustrative; the lesson is not.

The four separations

  1. A separate sensor path, where possible. The layer reads radar detections straight from the radar's own processor, and a simple camera detection stream, not the main perception model's output.
  2. Separate compute. A safety microcontroller, or at least a separate core and memory partition that the main stack cannot write to. The general idea is freedom from interference: nothing else can corrupt the layer's memory, steal its time or block its messages.
  3. Simple, different code. A few hundred lines with no shared middleware. Two copies of the same complex code share its bugs; a simple, different design does not.
  4. Its own monitors. The layer checks every input before it trusts it: how old it is, whether its counter advanced, whether its values are physically possible.

The safety-critical architecture lesson covers these patterns in depth, including watchdogs and end-to-end message protection. The runtime monitors lesson covers checking a learned model's output.

Pull a wire

The diagram shows the parts of the car's stack. A stopped car is ahead. Choose an architecture, inject faults, and see which parts fail and whether anything still brakes.

A logical toy, not a real architecture. "Independent" here means: its own controller and power supply, radar read directly, a simple camera stream, and its own clock check. Outcomes assume the layer's rules from Chapters 4 and 6.

Start with the shared design and freeze the main computer: everything goes dark, and nothing brakes. Switch to independent: the layer still sees the radar and the camera stream, and brakes fully. Now blind the camera too. The layer is down to one sensor, so by its own rules it warns and brakes partially. That is degraded, but it is not silent.

What the layer does when its inputs are bad

The layer's monitors can say an input is bad. Then what? Two rules drive the design.

Between "available" and "unavailable" sits degraded: one sensor is good, the other is not. A common choice is warnings and partial braking only, as in Chapter 6. The availability state is part of the safety design, not an afterthought: a layer that is often unavailable protects nobody.

#include <cmath>
#include <cstdint>

struct InputMsg {
  std::uint64_t stamp_us;    // capture time, on the shared vehicle clock
  std::uint16_t counter;     // +1 per message; wraps at 65535
  float range_m, range_rate_ms;
  bool valid_flag;           // the sender's own opinion of its data
};

enum class Avail : std::uint8_t { Available, Degraded, Unavailable };

struct InputMonitor {
  std::uint16_t last_counter = 0;
  bool seen = false;
  std::uint8_t bad_in_row = 0;

  // now_us: our own clock. max_age_us: the oldest data we will act on.
  bool check(const InputMsg& m, std::uint64_t now_us, std::uint64_t max_age_us) {
    bool ok = m.valid_flag;
    ok = ok && m.stamp_us <= now_us && now_us - m.stamp_us <= max_age_us;   // fresh, not future
    ok = ok && (!seen || static_cast<std::uint16_t>(m.counter - last_counter) == 1);  // no repeat, no gap
    ok = ok && std::isfinite(m.range_m) && m.range_m >= 0.0f && m.range_m < 300.0f;
    ok = ok && std::isfinite(m.range_rate_ms) && std::fabs(m.range_rate_ms) < 100.0f;
    last_counter = m.counter;
    seen = true;
    if (ok) bad_in_row = 0; else if (bad_in_row < 255) ++bad_in_row;
    return ok;
  }
};

// Two inputs to one availability state. Bad data must never cause braking.
Avail availability(const InputMonitor& radar, const InputMonitor& camera, std::uint8_t tolerate) {
  const bool r = radar.bad_in_row <= tolerate, c = camera.bad_in_row <= tolerate;
  if (r && c) return Avail::Available;
  if (r || c) return Avail::Degraded;      // for example: warnings only, no full braking
  return Avail::Unavailable;               // tell the driver, and stand down
}

The tests feed the monitor good messages, a repeated counter, a stale timestamp and a NaN range, and check that only the good ones pass. A counter that wraps from 65535 to 0 counts as the next message, because the subtraction is done in 16 bits. Two good inputs give Available, one gives Degraded, none gives Unavailable.

Failure mode: every input goes stale at once

Field report: the layer declared itself unavailable for two seconds, on a sunny day, with every sensor healthy. The log shows radar and camera messages failing the age check in the same cycle. When every input goes stale at the same instant, suspect the clock, not the sensors.

Here, the vehicle's shared time service had corrected itself by jumping forward, so all message timestamps suddenly looked old. The fixes: measure message age with a local monotonic clock that never jumps (the time since the message arrived), cross-check the shared clock against it, and treat a clock jump as its own fault with its own response. The Shared clock jumps toggle in the device shows the difference this makes.

An interviewer asks: "Your layer runs as a process on the main computer and reads the perception model's object list. What is wrong with that?"

Chapter 9

What the driver sees

Show the driver the same truth the system acts on, with a delay you can bound

A chime sounds. The driver looks at the screen. It shows the car ahead a few metres further away than it really is, because the picture is a moment old. Or worse, it shows no car at all, while the brakes fire. The driver now distrusts both the screen and the brake.

The display and warning path is called the HMI, the human-machine interface. It is deterministic software too, and it has one job beyond looking clear: what the driver sees must match what the system believes, and it must be fresh enough to act on.

Rule one: one snapshot, two readers

Every cycle the layer forms a belief: the tracks it used, the stage it chose, and the time its data was captured. The decision and the display must read the same snapshot. If the display grabs a newer object list, it can show a car the decision has not seen yet, or hide one the decision is braking for. Give each snapshot a sequence number and log it on every displayed frame.

Rule two: a bounded delay

The picture always lags the world. Here is an illustrative budget for the display path, on top of the sensing stages of Chapter 3.

belief waits for the next display frame up to 1 cycle, ~25 ms on average render the frame (60 Hz) 16.7 ms compose with the rest of the screen 16.7 ms scan out to the panel ~8 ms on average panel response ~8 ms total, typical ~75 ms (illustrative)

At 20 m/s of closing, 75 ms puts the car on screen 1.5 m behind where the system believes it is. At 150 ms the gap is 3.0 m. A team sets a budget for this delay and checks it the same way as the brake chain. The multimodal driving fusion lesson shows where these snapshots come from in a full stack.

Rule three: stale must look stale

If the data behind the picture gets older than the budget, the display must not freeze on the last picture. A frozen picture of an empty road is a lie. It greys out the scene and shows that the assist is unavailable. That is the display side of Chapter 8's rule: old data is not an empty road.

Belief against picture

The top lane is the system's belief: the lead car slows and speeds up. The lower lane is the driver's screen, drawn from delayed snapshots. Delay the display, freeze its feed, and watch the mismatch and the stale check.

150 ms
250 ms

Toy: we drive at 20 m/s; the lead car's speed swings between 12 and 28 m/s, so the gap breathes between about 17 and 33 m. The layer warns while the TTC is under 3.5 s. The display keeps a ring of past snapshots and shows the one that is "delay" old.

Warnings: timing against a human

A warning only helps if a person can act on it in time. A driver needs a reaction time, typically about 1 to 1.5 s and longer when distracted, and then braking time. Say the driver reacts in 1.2 s and brakes at a firm 6 m/s² (both illustrative). Closing at 20 m/s, the warning must come at least this early:

Twarn ≥ 1.2 + 20 / (2 × 6) = 1.2 + 1.67 = 2.87 s  ·  that is 57 m of range

Compare that with the full-brake trigger of 1.55 s from Chapter 1. The warning must come more than a second earlier than the machine needs to brake, which is exactly why warnings tolerate more false alarms than braking does. The listing adds two more rules. A warning stays up for a minimum time, so a flickering threat does not flash it for 50 ms. And partial and full braking show the same symbol, because the driver needs to know "the car is braking", not which stage.

#include <cstdint>

struct Belief {             // what the decision used this cycle: one snapshot
  std::uint32_t seq;        // cycle number
  std::uint64_t stamp_us;   // capture time of the sensor data it rests on
  float range_m;
  std::uint8_t stage;       // 0 none, 1 warn, 2 partial, 3 full
  bool available;
};

enum class Icon : std::uint8_t { None, Car, CarWarn, CarBrake, Unavailable, Stale };
struct DisplayFrame { std::uint32_t seq; Icon icon; float range_m; };

// A warning must stay up long enough to be seen, even if the threat flickers.
struct WarnHold {
  std::uint64_t on_since_us = 0;
  bool on = false;
  bool step(bool want, std::uint64_t now_us, std::uint64_t min_on_us) {
    if (want && !on) { on = true; on_since_us = now_us; }
    else if (!want && on && now_us - on_since_us >= min_on_us) on = false;
    return on;
  }
};

// Build the frame from the SAME snapshot the decision used, never a newer or
// older copy, so what the driver sees is what the system believed.
DisplayFrame build_frame(const Belief& b, WarnHold& hold, std::uint64_t now_us,
                         std::uint64_t max_age_us, std::uint64_t min_on_us) {
  DisplayFrame f{b.seq, Icon::None, 0.0f};
  if (now_us < b.stamp_us || now_us - b.stamp_us > max_age_us) { f.icon = Icon::Stale; return f; }
  if (!b.available) { f.icon = Icon::Unavailable; return f; }
  f.range_m = b.range_m;
  const bool warn = hold.step(b.stage >= 1, now_us, min_on_us);
  if (b.stage >= 2) f.icon = Icon::CarBrake;          // partial and full look the same
  else if (warn) f.icon = Icon::CarWarn;              // includes the minimum on-time
  else f.icon = (b.range_m > 0.0f) ? Icon::Car : Icon::None;
  return f;
}

The tests: a warning appears and stays up for its minimum second even after the stage drops; old data shows the stale icon, never the last picture; an unavailable layer shows that it is unavailable. The frame always carries the snapshot's sequence number, which makes the mismatch measurable in a log.

Failure mode: the screen and the brake disagree

Drivers report a hard brake with "no car on the screen". The log shows the decision used snapshot 4,812, while the frame on screen at that moment came from snapshot 4,809, because the renderer had stalled for 150 ms on a font load. To diagnose: log the snapshot number on every frame and the decision's snapshot number on every command, and compare them on the same clock.

The fixes come in three parts. Preload everything the renderer needs at start-up. Run the safety symbols on a simple path that cannot stall behind the rest of the screen. And apply the staleness check from the listing, so a stalled frame becomes a visible stale state instead of a quiet lie.

An interviewer asks: "Your display renderer stalls. What should the driver see, and why?"

Chapter 10

Testing it

Sweep the scenarios, replay the drives, and work out how many kilometres prove a rare event is rare

Your layer has driven 50,000 km of test routes without a single phantom brake. A manager asks: "So it never brakes for nothing?" What can you honestly say? Less than the manager hopes, and more than nothing. This chapter makes the answer precise.

Testing an active-safety layer has two halves. It must brake when it should, in every kind of hazard: that is tested with scenarios. And it must almost never brake when it should not: that is tested by counting false activations over long drives. Consumer test programmes and regulations exist for automatic emergency braking in several regions, and teams test against them. This lesson stays with the general method.

The scenario catalogue

A scenario catalogue lists the situations the layer must handle, each with parameters to vary. In general terms it covers:

Each scenario is then swept: run across a grid of closing speeds, overlaps, grips, timings and lighting. A single passing run says little. A grid shows where the edges are, and a sharp edge, a cliff, is where to look first.

Sweep the closing speed

Each cell is one run of the hero's stopped car. Across: closing speed. Down: road grip. Green stops short; warm hits at a reduced speed; red hits with little speed shed. Move the trigger and the latency and watch the edge move.

1.6 s
0.30 s

The hero's toy kinematics in every cell. "Little speed shed" means the impact speed is above 70% of the closing speed. Tap a cell to read it.

With a fixed 1.6 s trigger, the green region is a triangle: low speed and high grip. The edge follows Chapter 1's formula, T = tL + v / (2a). Every point on the edge is a scenario the catalogue must contain, because that is where a small error flips the outcome.

Three ways to run a scenario

MethodStrengthWeakness
Track test: a real car, a soft target on a test trackreal sensors, real brakes, real physicsslow and costly; dozens of runs, not millions
Simulation: sensors and physics modelled in softwaremillions of runs, every corner of the sweep, perfect repeatabilitythe sensor models may not fail the way real sensors fail
Replay: recorded sensor data fed through new codereal sensor data, including real ghosts; every new version re-runs every kilometreopen loop: the recorded car cannot react to the new decision

The three cover each other's gaps. Replay is the workhorse for false activations: record a very large number of ordinary kilometres once, then replay them through every new software version and count the activations. Because the layer is deterministic, the same version on the same log gives the same count every time.

How rare is rare? The rule of three

Suppose false activations happen at some unknown rate λ per km, independently. In n km the count of events follows a Poisson distribution. The chance of seeing zero events is e−λn. If we saw zero, which rates are still believable? Those for which zero events was not too unlikely, say at least 5% likely.

P(0 events) = e−λ n ≥ α   ⇒   λ ≤ −ln(α) / n = 3.0 / n   for α = 0.05
λ
the true false-activation rate, events per km, which we never observe directly
n
the kilometres driven (or replayed) with the same software
α
one minus the confidence; 0.05 for 95% confidence, and −ln(0.05) = 2.996

That is the rule of three: after zero events in n km, the rate is below about 3 / n with 95% confidence. Work the manager's question. Zero phantom brakes in 50,000 km gives a rate below 3 / 50,000 = 6 per 100,000 km. To support "below 1 per million km" with zero events, you need 3.0 million km. With one event the factor rises to 4.74, with two to 6.30.

State the assumptions with the number. Events must be independent; the kilometres must represent the roads, weather and traffic where the car will drive; the event must have a clear definition; and every kilometre must run the same software. Replay helps with the last one: when the code changes, replay all the kilometres again.

How many kilometres?

The curve is the upper bound on the event rate after the events you saw, against kilometres driven. The dashed line is your target. Where the curve drops under the target, the claim is supported.

50,000
0
1 per 1M

Exact one-sided Poisson upper bounds, computed by the same bisection as the C++ below. Targets are illustrative, not any real requirement.

#include <cmath>

// P(X <= k) for a Poisson count with mean mu, summed term by term so that no
// factorial ever overflows. Fine for the small k that safety testing sees.
double poisson_cdf(int k, double mu) {
  double term = std::exp(-mu), sum = term;
  for (int i = 1; i <= k; ++i) { term *= mu / i; sum += term; }
  return sum;
}

// One-sided upper confidence bound on an event rate (per km) after k events in
// `km` kilometres: the largest rate under which "k or fewer" is still at least
// (1 - confidence) likely. Bisection with a fixed count: deterministic.
double rate_upper_bound(int k, double km, double confidence) {
  const double alpha = 1.0 - confidence;
  double lo = 0.0, hi = 10.0 + 10.0 * k;        // brackets mu = rate * km
  for (int it = 0; it < 100; ++it) {
    const double mid = 0.5 * (lo + hi);
    if (poisson_cdf(k, mid) > alpha) lo = mid; else hi = mid;
  }
  return 0.5 * (lo + hi) / km;
}
// k = 0 gives mu = -ln(alpha): 3.00 at 95%, the "rule of three".
// Kilometres needed with zero events: km = -ln(alpha) / target_rate.
double km_needed_zero_events(double target_rate_per_km, double confidence) {
  return -std::log(1.0 - confidence) / target_rate_per_km;
}

The tests reproduce the factors 2.996 (zero events), 4.744 (one) and 6.296 (two) at 95%, and 2,995,732 km for a target of one per million km with zero events. The bisection runs exactly 100 times, so it is deterministic and bounded like everything else in the layer.

Failure mode: passing the catalogue, failing the road

The layer passes every catalogue scenario. On the road it misses a pedestrian who crosses a little faster than any catalogue case, from behind a van rather than a car. The catalogue was a list of points; the road is a space between them.

To diagnose it, sweep randomly around each scenario instead of on its fixed values, and look for cliffs, where a small change flips the outcome. Then add the cliff to the catalogue. Add every field incident to the replay set too, so a fixed bug stays fixed. The bench in the next chapter runs this kind of randomised sweep.

An interviewer asks: "You replayed 1 million km with zero phantom brakes. What rate can you claim, and under what assumptions?"

Chapter 11

The active-safety bench

Run the whole layer on five scenarios and hundreds of random runs, then break it on purpose

Every piece is built. Now put them together and test them the way Chapter 10 says: many randomised runs of each scenario, with the counts that matter. This bench runs a toy version of the whole layer: noisy radar and camera detections, M-of-N evidence with coasting, the in-path test, areq, the three-stage decider with hysteresis and a latch, latency, and the brakes.

Each batch runs 200 randomised versions of one scenario: different gaps, timings, speeds of the other road user, and sensor noise. The results panel counts four outcomes. Avoided: no contact. Mitigated: contact, but after braking began, with the mean impact speed. Missed: contact with no braking at all. False activations: full braking caused by something that was not real. The read-out also counts runs where a ghost caused only partial braking, which one sensor's evidence is allowed to do.

The active-safety bench

Pick a scenario. Play one run to watch it from above; the band under the road shows the stage each moment. Then run a batch of 200 and read the counts. Change one knob at a time.

–avoided
–mitigated
–missed
–false activations
72 km/h
0.30 s
8.0 m/s²
6.00
1.0×
2%

Toy simulation, 10 ms physics, 50 ms layer cycle, straight road. Radar: range noise 0.25 m, closing noise 0.15 m/s, detects cars with pD 0.95 and pedestrians with 0.7. Camera: range noise 3% plus 0.2 m, pD 0.95 for cars and 0.9 for pedestrians, blind behind the parked cars. The sign fools the radar until 30 to 45 m. Partial braking 4 m/s², warning and partial at 50% and 75% of the full threshold. Batches use fixed seeds, so the same knobs give the same counts. Illustrative throughout.

Things to try

  1. The baseline. Stopped car at the defaults: all 200 avoided. Raise the speed to 130 km/h: still avoided. areq already contains the speed and the latency, so the layer moves its trigger range out on its own. The hero's fixed TTC could not do that.
  2. Ghosts. Pick the overhead sign. With "needs both", full braking for the sign stays at zero. Switch to "either sensor" and the sign brakes the car fully in most runs. That is Chapter 6 in one click. Now read the small print of the result: even with "needs both", the sign causes partial braking in every run, because one sensor may drive partial braking. That is the price of the rule, and some designs allow only a warning on one sensor.
  3. Clutter. Raise clutter to 20% a cycle with 1 of 1. False activations climb (152 of 200 runs on the stopped car). Switch to 2 of 3 (68), then 3 of 3 (0), and watch them fall while the stopped car's results do not move.
  4. The braking lead. Turn off "Use lead acceleration". The layer now believes the lead keeps its speed, as plain TTC does, and brakes late. Count the extra mitigated runs: Chapter 2's lie, in numbers.
  5. The pedestrian. The camera is blind until the pedestrian clears the parked cars, so there is little time. Here, latency is everything: drop it from 0.3 to 0.15 s and count the difference.
  6. Wet road. Set grip to 4.5 m/s² but leave the threshold at 6. The decider asks for more than the tyres can give. Chapter 1's failure mode: the trigger must know the grip.

Every knob is a trade. A lower threshold catches more hazards and brakes for more ghosts. A stricter rule rejects ghosts and reacts later. The bench lets you feel the frontier, the line where you cannot improve one count without hurting another. A team's job is to choose a point on it on purpose, and to write down why.

One cycle of the real thing

Here is the cycle of the layer in C++, assembled from the earlier listings. It runs every slot every cycle, so its time does not depend on how many objects there are. It caps one-sensor evidence below full braking, and it never lets an unavailable input brake.

// One cycle of the active-safety layer. Fixed order, fixed capacity, no heap.
// Uses ttc_cv (Ch 2), required_decel and Decider (Ch 4), in_path (Ch 5),
// update_threat (Ch 6) and Avail (Ch 8).
constexpr int kMaxThreats = 16;

struct Candidate { double range, closing, y, half_width; bool radar, camera; };
struct Command { Stage stage; double decel; double ttc; };
struct Config { Thresholds th; ConfirmRule rule; double t_lat, margin, grip, partial_decel; };

struct Layer {
  ThreatTrack tracks[kMaxThreats];          // slot i follows candidate i (association upstream)
  Decider decider;

  Command cycle(const Candidate (&c)[kMaxThreats], int n, const PathModel& path,
                Avail avail, bool ego_stopped, const Config& cfg) {
    double worst_a = 0.0, worst_ttc = kNoCollision;
    bool have = false;
    for (int i = 0; i < kMaxThreats; ++i) {                 // every slot, every cycle: fixed work
      const bool live = i < n;
      const Evidence e = update_threat(tracks[i], live && c[i].radar, live && c[i].camera, cfg.rule);
      if (!live || e == Evidence::None) continue;
      if (!in_path(path, Obj{c[i].range, c[i].y, c[i].half_width}, 0.95, 0.2, 0.005)) continue;
      double a = required_decel(c[i].range, c[i].closing, cfg.t_lat, cfg.margin);
      if (e != Evidence::Both && a > cfg.th.enter[2])      // one sensor alone: cap below full
        a = cfg.th.enter[2] - 1e-3;
      if (a > worst_a) { worst_a = a; worst_ttc = ttc_cv(c[i].range, c[i].closing); have = true; }
    }
    if (avail == Avail::Unavailable) have = false;          // bad inputs never brake
    if (avail == Avail::Degraded && worst_a > cfg.th.enter[1])
      worst_a = cfg.th.enter[1] - 1e-3;                     // degraded: warnings only
    const Stage s = decider.step(worst_a, have, ego_stopped, cfg.th);
    const double decel = (s == Stage::Full) ? cfg.grip
                       : (s == Stage::Partial) ? cfg.partial_decel : 0.0;
    return Command{s, decel, worst_ttc};
  }
};

The tests drive the layer toward a stopped car at 20 m/s. With both sensors, full braking starts at 40.0 m, a TTC of 2.00 s, which matches the worked threshold of Chapter 4 (40.3 m, met on the first 50 ms cycle past it). With radar alone it never reaches full braking. With inputs marked unavailable it does nothing at all.

Failure mode: the batch that looked perfect

A tuning session reaches 200 avoided out of 200, with zero false activations. Then a fresh set of seeds gives 191 and 6. The settings were tuned to the particular random draws, not to the scenario. To catch this, press New seeds after tuning: a robust setting barely moves. It is the same rule as Chapter 10: tune on one set, test on another.

An interviewer asks: "You lower the full-brake threshold to stop more often at high speed. What else must you check, and why?"

Chapter 12

Interview arsenal

Gather the numbers, the design frames, the drills and the debugging stories in one place

Here is the lesson in one paragraph. Stopping distance is speed times delay plus speed squared over twice the deceleration, so the latest safe trigger is tL + v / (2a). Time to collision turns range and closing speed into seconds; it lies when the lead brakes, so add relative acceleration. Every stage from photon to brake pressure costs metres, and the actuator often costs the most.

The decision compares the deceleration needed with the grip available, in three stages, with hysteresis and a latch. Ghosts come from sensors that fail in different ways, so the in-path test, confirmation and two-sensor agreement guard full braking. Shapes and sweeps handle crossing objects. Independence keeps the last line alive when the main stack fails. The display shows the same snapshot, fresh or visibly stale. And rare events are proven with many kilometres and honest bounds.

From symptom to cause

Pick a symptom from a field report. The pipeline lights the stages to check first, in order, and the read-out says what to log.

A study aid: real incidents can have several causes. Always confirm with a replay of the logged data.

Cheat sheet

IdeaOne lineNumber to remember
Stopping distancev treact + v² / (2a)50 km/h: 32.9 m; 100 km/h: 89.9 m (human 1.5 s, 8 m/s²)
Latest triggerT ≥ tL + v / (2a)72 km/h, 0.3 s, dry: 1.55 s; wet: 2.30 s
Time to collisionR / vc, only when vc > 040 m at 10 m/s: 4.0 s
Enhanced TTCsmallest positive root of R − vct + ½arelt² = 0lead braking at 6: 4.0 s becomes 2.35 s
Latency costmetres = speed × delay1 ms at 100 km/h = 2.8 cm; 267 ms = 7.4 m
Brake rampcounts as half its lengtherror a Tr² / 24: 1 cm for 0.18 s
Required decelerationvc² / (2 (R − vctL − dm))40 m, 20 m/s, 0.3 s, 1 m: 6.06 m/s²
Hysteresisenter high, leave low, after a holdnoisy readings: 11 changes become 1
Path offsety ≈ x² / (2Rc)500 m curve, 60 m ahead: 3.6 m, a whole lane
M-of-Nconfirm with M hits in the last N cycles2 of 3: real 0.972, random ghost 0.0073
Box overlapfour separating axes for two rectangles(4.4, 2.2) at 30°: gap 0.16 m on B's long axis
Common causeβ λ dominatesβ = 0.1: 10−5 instead of 10−8
Driver warningreaction + braking time1.2 + 20 / 12 = 2.87 s
Rule of threezero events in n km: rate < 3 / n at 95%1 per million km needs 3.0 million km

Three system design prompts

1. Design the automatic emergency braking layer for a passenger car

Front radar and a front camera, a main driver-assistance computer, and a safety controller. Highway and city speeds.

  1. Clarify: speeds, sensors and their rates, the brake actuator's latency, what the main stack already does, and how false activations are budgeted per stage.
  2. Independence: run on the safety controller with radar read directly and a simple camera stream; own monitors on age, counters and ranges.
  3. Pipeline: small tracker with M-of-N and coasting; in-path test on the yaw-rate arc; enhanced TTC and areq; three stages with hysteresis and a latch; full braking only on two-sensor evidence.
  4. Latency: write the budget down, check it at build time, measure the tail on the target.
  5. HMI: one snapshot for decision and display, a staleness check, warnings early enough for a human.
  6. Validation: scenario sweeps, track tests, replay of large drive logs for false activations, and rule-of-three bounds stated with their assumptions.

2. Add pedestrian braking to an existing car-following layer

  1. What changes: pedestrians cross instead of following; radar sees them weakly; they appear late from behind parked cars.
  2. Geometry: move from range along a line to swept shapes in 2D; circles for pedestrians, because they have no reliable heading.
  3. Evidence: camera-led confirmation with radar support where available; a faster confirmation path for objects already inside the corridor.
  4. Latency: the time from first visibility is short, so every millisecond matters more; check the camera-to-decision path first.
  5. Tests: crossing speed, start offset, occlusion and lighting sweeps; ghost scenes with pedestrian-like shapes.

3. The ML team offers a learned collision-risk model. How do you use it?

  1. Measure on the same footing: the same scenarios, replays and false-activation counts as the classical layer.
  2. Keep the checkable floor: the classical TTC and areq layer stays as the last line; the learned model can raise a warning earlier or add evidence, not bypass the checks.
  3. Bound it: runtime monitors on its outputs, as in the runtime monitors lesson; worst-case time measured on the target.
  4. Name a formal reference: Responsibility-Sensitive Safety is a published formal model that defines safe following distances from assumed worst-case braking; it is a useful way to state what "safe" means.

Three coding drills

  1. TTC with guards. Write ttc_accel(range, closing, a_rel). Test zero closing, a receding target, a braking lead (2.35 s), an accelerating lead (no collision), and arel = 10−7 in float.
  2. A staged decider. Implement three stages with enter and exit levels, a hold count and a full-brake latch. Write the test with twelve noisy readings around one threshold and count the changes.
  3. Lead acceleration. Estimate the lead car's acceleration from its speed history without amplifying noise. One answer follows.

Here is one answer to the third drill. The point an interviewer looks for is the noise. Differencing two samples 50 ms apart turns 0.1 m/s of speed noise into about 2.8 m/s² of fake acceleration. The difference of two noisy samples has √2 × 0.1 = 0.14 m/s of noise, and we divide it by 0.05 s. A least-squares slope over a window averages it down.

#include <cstdint>

// Estimate the lead car's acceleration from its last N speed samples with a
// least-squares slope. Differencing two samples would amplify the noise:
// 0.1 m/s of noise over a 50 ms cycle is already 2.8 m/s^2 of fake acceleration.
template <int N>
struct SlopeWindow {
  static_assert(N >= 3 && N <= 64, "window size");
  float v[N] = {};           // ring buffer of speeds (m/s)
  int head = 0, count = 0;

  void push(float speed) {
    v[head] = speed;
    head = (head + 1) % N;
    if (count < N) ++count;
  }
  // dt: cycle time (s). Returns 0 until the window is full: no guess from 2 points.
  float accel(float dt) const {
    if (count < N || !(dt > 0.0f)) return 0.0f;
    const float tm = 0.5f * static_cast<float>(N - 1);  // mean sample index
    float num = 0.0f, den = 0.0f;
    for (int i = 0; i < N; ++i) {                    // i = 0 is the oldest sample
      const float d = static_cast<float>(i) - tm;  // distance from the mean index
      num += d * v[(head + i) % N];
      den += d * d;
    }
    return num / (den * dt);                         // slope per sample, per second
  }
};

The test feeds eight samples of a car braking at 6 m/s² and gets −6.000 back; a window that is not yet full returns zero rather than a guess from two points.

Three debugging scenarios

  1. "Phantom brakes under one particular bridge." Radar sees the bridge as a stationary object in path. Check: the per-sensor hit histories at that spot, and whether the camera agreed. Fix: two-sensor agreement for full braking, radar elevation if available, and add the bridge to the replay set.
  2. "Brakes late, but only in rain." The trigger assumes dry grip. Check: commanded against achieved deceleration in the log. Fix: a conservative grip estimate (wipers, temperature, slip) that moves the trigger earlier.
  3. "The replay result changed, but the code did not." Something is not deterministic: an uninitialised variable, iteration over an unordered container, a thread race, or a reading of the wall clock. Check: run the same replay twice on the same build and diff every cycle's output. The real-time deterministic C++ lesson lists the usual suspects.

Classical and learned

Classical layer (this lesson)Learned risk model
DecisionTTC and areq against thresholdsa predicted risk score from many inputs
Behaviour off the datadegrades by known physicscan fail in ways the training set never showed
Worst-case timefixed and smalldepends on model size; must be measured
Strengthcheckable, explainable, independentsees intent and context: a child running toward the road
Best usethe last lineearlier warnings and extra evidence, monitored

Reading list

Keep going on this site

The takeaway. Know how much time is left and how much braking needs, act in stages, ask two different sensors before the hardest action, never act on data you cannot trust, keep the whole thing small and independent, and prove its rare failures with honest numbers.

Now press Present or Teach and explain, from memory, why the latest safe trigger is tL + v / (2a), and why an earlier trigger brakes for the overhead sign. Then go back to the road, set 100 km/h with the sign on, and find whether any trigger does both jobs. If none does, say which chapter's tool you would reach for.

An interviewer asks: "In one sentence, what makes the active-safety layer trustworthy as the last line?"
The Deterministic Active-Safety Layer
Onboard perception software lead · Multi-target tracking · Back to Gleams