Day in the Life: Onboard Perception Software Lead

A learned detector is right on almost every frame. At 30 frames a second, "almost" still means invented and missed objects every hour. Around the model sits a layer of plain, deterministic C++ that catches them on time, every time. This lesson is about the people who build that layer.

Pick a fault and watch the drive. Then switch the deterministic layer off and run the same fault again. See what reaches the brake and the driver's screen. Then we build every box of the pipeline from zero, and practise the interview for each one.

You need high-school algebra and some C++ or another typed language. We build the rest from zero.

Break the pipeline

Ready

The car drives at 60 km/h. A pedestrian is about to cross.

A toy, built to make each fault visible. One camera and one radar at 10 cycles a second, a pedestrian crossing at 1.4 m/s, braking at 7 m/s² (typical for a dry road) after 0.2 s of actuator delay, and a brake trigger at a time to collision of 1.8 s. Real systems use more sensors, faster cameras and many more checks.

Chapter 0

The layer nobody demos

See why a very good model still needs plain software around it

A car drives down a city street at 60 km/h. The sun is low. A bridge throws a sharp shadow across the lane. For three frames, the camera's neural network looks at that shadow and reports a box: "object, 12 m ahead".

Nothing is there. If that box goes straight to the brake, the car stops hard in traffic for nothing. The driver behind does not expect it. This is a phantom brake: the car brakes for an object that does not exist.

Now flip the error. A child in a dark coat steps off the curb at dusk. The same network misses the child for eight frames in a row. If the brake only reacts to what the network sees right now, it does nothing for those eight frames. At 60 km/h, eight frames at 10 a second is 0.8 s, or 13 m of road.

Neither failure means the network is bad. A modern detector can be right on 99.99% of frames. The trouble is scale. A camera makes tens of frames a second, and a fleet drives millions of hours. Rare errors become routine.

A rare error, at scale

The strip is one hour of driving, minute by minute. Each purple mark is a frame where the model invents an object. Red marks reach the brake. Warm marks are caught by checks. Move the sliders.

1/10,000
30
0%

Toy arithmetic. The error rates are illustrative, not measured for any model. Real errors cluster in time (a shadow lasts several frames), so they are not independent. Chapter 5 shows why clustering matters for the checks.

Work the default by hand. A camera at 30 frames a second makes 30 × 3,600 = 108,000 frames an hour. If 1 frame in 10,000 holds an invented object, that is 108,000 / 10,000 = 10.8 invented objects an hour.

30 frames/s × 3,600 s × 1/10,000 = 10.8 invented objects per hour, per camera

Suppose checks stop 99% of them. Then 10.8 × 0.01 = 0.108 get through: about one every 9 hours. Stop 99.9% and it becomes one every 93 hours. The model did not change. The software around it did.

What sits around the model

Picture the whole chain from light to brake. Each stage takes one kind of data and makes another. The deterministic layer is the part in the middle that is not learned. It is ordinary C++ with fixed rules. Given the same input, it gives the same output, in the same time, every time.

  1. Sensors. Cameras make images; radar makes range and speed readings. Out: raw frames with timestamps.
  2. Learned detector. A neural network finds objects in each frame. Out: detections, one per object per frame, each with a box, a class and a confidence.
  3. Tracker. Joins detections across frames into tracks: one per real object, with position, velocity and an honest doubt. It keeps a track alive through short misses.
  4. Fusion. Puts camera and radar into one frame of reference and one moment in time, so they agree or visibly disagree.
  5. Monitors. Check the model and the sensors against physics and against each other. They reject ghosts and flag stale or late data.
  6. Active-safety check. The last line. It computes time to collision and commands a brake if a crash is close.
  7. Outputs. The driver display shows what the system believes. The brake acts on it.

The warm stages are this role's territory. They are where the hero's faults get caught. Go back to the hero and try each fault with the layer off. The model is the same in both runs. Only the warm stages change.

The job title varies. It might say perception onboard software, perception systems, or classical perception. The shape is the same in cars, delivery robots, drones and aircraft.

You design that warm layer. You set the engineering rules for it. You lead the people who write it. And you sit between the classical team and the machine learning team, so that each knows what the other promises.

The same shape shows up wherever a learned model drives a machine that can hurt someone. The names change; the layer does not.

DomainLearned partDeterministic layerLast-resort function
Driver assistancecamera detector, lane networktracker, camera and radar fusion, monitorsemergency braking, driver warnings
Delivery robotperson and obstacle detectortracker, depth cross-check, speed limits by zoneprotective stop
Droneobstacle segmentationtracker on a small CPU, geofence checkshover, climb, or land
Aircraftrunway or traffic detection aidsplausibility against navigation data, strict timingalert the crew; revert to the certified function

The contract between the two halves

Everything starts with the message the detector hands to the layer. A lead cares about this message more than almost anything else. It is the line where two teams meet. Here it is in C++, the way a real-time system would write it.

c++
// The contract: what the learned detector promises the deterministic layer.
// Fixed size, no pointers, no heap: it can be copied, logged and replayed.
#include <array>
#include <cstdint>

enum class ObjClass : uint8_t { Unknown, Car, Truck, Pedestrian, Cyclist };

struct Detection {
  float x_m, y_m;          // position in the vehicle frame (x forward, y left)
  float var_x, var_y;      // the model's own doubt, as a variance in m^2
  float length_m, width_m;
  ObjClass cls;
  float confidence;        // 0..1; must be calibrated, see chapter 5
};

struct DetectionFrame {
  uint64_t capture_ns;     // when the light hit the sensor, not when we got it
  uint32_t sensor_id;
  uint32_t sequence;       // +1 every frame: a stuck counter means a frozen camera
  uint32_t model_version;  // which network produced this; logged for every run
  uint16_t count;          // how many entries below are valid
  std::array<Detection, 64> dets;  // fixed capacity: overflow is a counted fault
};
static_assert(std::is_trivially_copyable_v<DetectionFrame>, "must be memcpy-safe");

Look at what the comments carry. The capture time, the sequence counter and the model version are not decoration. The hero's "late frame" fault is caught by capture_ns. The "camera freezes" fault is caught by sequence. A lead fights for those fields in design review, because without them no monitor can work.

Interview tip. When asked "why not let the network do everything?", do not argue that networks are unreliable. Say: the network is good on average, the layer is what makes the worst case bounded and testable. Then give the arithmetic: frames per hour times error rate.

Here is the road. Each chapter builds one part of the hero and one part of the interview.

  1. What "deterministic" means: same input, same output, same time. The hero's master switch.
  2. State estimation in ten minutes: belief, predict, update, and doubt you can trust.
  3. Tracking many things: which detection belongs to which track. This is how the missed walker survives.
  4. Sensor fusion and spatial reasoning: frames, transforms, time alignment and geometric checks.
  5. Guardrails around a learned model: monitors and the threshold trade. This is how the ghost is rejected.
  6. The real-time budget: photon to brake, worked in milliseconds. This is the late frame.
  7. Safety architecture in plain words: hazards, faults and degraded modes. This is the frozen camera.
  8. The active-safety layer and the display: time to collision, braking and what the driver sees.
  9. Testing a deterministic layer: replay a drive and diff it bit for bit.
  10. Leading the team: standards, reviews, decisions, hiring, and the line between ML and classical.
  11. The full pipeline bench: every knob at once, run over 150 drives.
  12. Interview arsenal: cheat sheet, design prompts, drills and a reading list.
The five interview dimensions, for this chapter
Concept
"What does the onboard perception layer do that the network does not?" Joins frames over time, checks the model against physics and other sensors, bounds time and memory, and runs the last-resort safety check.
Design
"Draw the pipeline from photon to brake." Sensors, detector, tracker, fusion, monitors, active safety, display and brake. Name the message between each pair.
Code
"Write the detector-to-tracker message." Fixed size, capture time, sequence counter, model version, calibrated confidence.
Debug
"Customers report phantom braking under bridges." Find the logs, replay them, check which stage let the box through, and whether radar disagreed.
Frontier
"Will end-to-end networks remove this layer?" They move more work into the model, but a checkable layer still bounds the worst case. Chapter 12 has the honest version.
Interview question: "Our detector is right on 99.99% of frames. Why do we still need a deterministic layer?"

Chapter 1

What "deterministic" means

Make the same input give the same output, in the same time

A test driver reports a strange brake on Tuesday at 14:02. You pull the log of that drive and replay it on your desk. The brake does not happen. You replay it again. This time it does. Now you have two problems: the bug, and a system you cannot reproduce.

That is what non-deterministic software costs. A deterministic system gives the same output for the same input, every time. For a real-time system there is a second half: it also takes a bounded time, every time. Both halves matter.

Why does a perception lead care so much? Three reasons, in order of how often they bite.

  1. Debugging. You can only fix what you can reproduce. A replay that differs from the drive hides the bug.
  2. Testing. A regression test compares today's output with yesterday's. If the output wobbles by itself, every test is noisy and people learn to ignore failures.
  3. Safety arguments. A safety case claims "this check always fires within 300 ms". You cannot claim "always" about code whose behaviour depends on thread timing.

The cleanest way to get determinism is a shape, not a trick. Write every module as a step function: it takes this cycle's inputs and its own saved state, and returns outputs plus the new state. Nothing else goes in. No clock reads, no global variables, no random numbers without a logged seed.

yk, sk+1 = f( xk, sk )   and   Ck ≤ WCET ≤ D
yk
the outputs of cycle k: tracks, flags, a brake request
sk+1
the state saved for the next cycle, such as the list of tracks
f
the step function: pure code, no hidden inputs
xk
the inputs of cycle k: detection frames, radar scans, the vehicle's own speed, each with a timestamp
sk
the state saved by the previous cycle
Ck
how long cycle k actually took to compute
WCET
worst-case execution time: the longest any cycle can take, measured and bounded
D
the deadline: when the outputs must be ready, for example 20 ms after the cycle starts

The left half is "same output". If you log every x and the first s, you can replay any drive and get the same y, bit for bit. The right half is "same time". The average cycle time does not matter much. The worst one does, because the brake cannot wait for a lucky cycle.

Run it twice

The same recorded input runs twice, as run A and run B. The top rows compare their outputs cycle by cycle. The bars below are run A's cycle times against a 20 ms deadline. Turn on a source of trouble.

Toy. The rates at which each source causes a difference, and the size of the allocation spikes, are illustrative. The mechanisms are real: iteration order of hash containers, data races, floating-point reassociation and heap allocation latency.

Each toggle is a real way that C++ code loses determinism. Here is what each one does.

The float case is worth doing by hand once, because people do not believe it. A 32-bit float has 24 bits of precision. Near 100,000,000 the gap between neighbouring floats is 8. So 100,000,000 + 1 rounds back to 100,000,000.

(1e8f + 1f) − 1e8f = 1e8f − 1e8f = 0  ·  (1e8f − 1e8f) + 1f = 0 + 1f = 1

Same three numbers, different order, different answer. A real tracker never adds numbers that far apart on purpose. But a long sum of covariance terms can lose low bits in a similar way, and a parallel reduction picks a different order on each run.

The design: a step function, called on a clock

A real system ties the step function to a fixed clock. Every 50 or 100 ms (typical values) the scheduler wakes the perception task. It collects whatever inputs have arrived, calls the step, and publishes outputs. This is called time-triggered design. The opposite, event-triggered design, runs whenever a message arrives.

Event-triggered code is simpler to write. It is also why the hero's naive pipeline stalls on a late frame: it waits for the next message, and the brake waits with it. Time-triggered code never waits for a message. If data is missing, it predicts, flags the gap and moves on.

c++
// One cycle of the layer as a pure step function.
// Everything it reads is in `in` or `st`; everything it writes is in `out` or `st`.
struct Inputs  { DetectionFrame cam; RadarScan radar; float ego_speed; uint64_t now_ns; };
struct Outputs { TrackList tracks; HealthFlags health; BrakeRequest brake; };

void step(const Inputs& in, State& st, Outputs& out) {
  // 1. Sort detections by a stable key before any loop that can tie.
  //    std::sort is not stable, so the key must be unique: add the index.
  std::array<uint16_t, 64> order;
  for (uint16_t i = 0; i < in.cam.count; ++i) order[i] = i;
  std::sort(order.begin(), order.begin() + in.cam.count,
            [&](uint16_t a, uint16_t b) {
              const auto& da = in.cam.dets[a]; const auto& db = in.cam.dets[b];
              if (da.x_m != db.x_m) return da.x_m < db.x_m;
              return a < b;                    // unique tie-break: total order
            });
  // 2. All memory was reserved at start-up: st.tracks is a fixed array.
  predict(st.tracks, in.now_ns);         // uses the timestamp, never a clock read
  associate(st.tracks, in.cam, order);   // single thread, fixed order
  check_health(in, st, out.health);      // stale and late data, see chapters 5 and 7
  out.tracks = st.tracks;
  out.brake  = active_safety(st.tracks, in.ego_speed);
}

Read the two comments marked 1 and 2. Sorting with a unique tie-break gives a total order, so ties always break the same way. Fixed arrays mean no allocation after start-up. The step reads time from in.now_ns, which was logged, so a replay sees the same time.

When it breaks

The classic failure is a replay that diverges after a few minutes. The first differing cycle is the clue. Diff the two runs field by field and find the first cycle where any output differs. Then look at what that cycle did that others did not: a tie, a new track, a thread hand-off.

SymptomLikely causeWhat reveals itWhat to turn
Replay diverges after a few minutesa tie broken by unordered iterationthe first differing cycle and fieldsort with a unique tie-break; ordered containers
Outputs differ only when the CPU is busya data race between threadsthread sanitizer; a stress run with extra loadone writer per datum; a fixed hand-off order
One cycle in 10,000 misses its deadlineheap allocation or a first-touch page faultthe tail of the cycle-time histogram; an allocation hook in testsreserve everything at start-up; lock memory
Debugging tip. If a replay differs only in the last bits of a float, look for a reordered sum or a compiler flag such as fast-math. If it differs in which track got which ID, look for unordered iteration. If it differs only sometimes, under load, look for a data race and run the thread sanitizer.

The frontier here is less about new papers and more about tools. Deterministic replay frameworks record every input with its timestamp. Compilers and sanitizers catch races and undefined behaviour. Some teams run the same build twice in continuous integration and fail it if the outputs differ. The real-time deterministic C++ lesson goes deep on all of this.

Sizing it: what one cycle touches

Determinism is easier when everything a cycle touches is small and fixed. Count the bytes for the contract from Chapter 0. One Detection holds six floats, a one-byte class padded to four, and a float: 8 × 4 = 32 bytes. A frame of 64 is 2,048 bytes plus a small header.

input DetectionFrame 64 x 32 B + 24 B header = 2.1 KB input RadarScan 128 x 16 B = 2.0 KB state TrackList 64 x 96 B = 6.1 KB # position, velocity, 4x4 doubt, status scratch cost matrix 64 x 64 x 4 B = 16.4 KB total about 27 KB, all reserved at start-up # fits in a typical L2 cache

27 KB is tiny. The point is not saving memory. It is that the same 27 KB are used every cycle, at fixed addresses, so the cache behaves the same way every cycle and the timing stays tight.

The five interview dimensions, for this chapter
Concept
"Define determinism for a real-time system." Same inputs and state give the same outputs, and every cycle finishes within a bounded worst case.
Design
"Time-triggered or event-triggered?" Time-triggered for the layer: it never waits for a message, so a late or missing input degrades one cycle instead of stalling the brake.
Code
"Make this loop deterministic." Stable sort with a unique tie-break, fixed arrays, no clock reads inside the step, one thread or a fixed hand-off order.
Debug
"Replay differs from the drive." Find the first differing cycle; check unordered iteration, races (thread sanitizer), float reordering, uninitialised memory.
Frontier
"How do you keep a GPU model deterministic?" Many GPU kernels are not bit-exact across runs by default; fix the algorithm choice and log the model version, and keep the layer itself bit-exact.
Interview question: "Our replay matches the drive for ten minutes, then track IDs start to differ. Where do you look first?"

Chapter 2

State estimation in ten minutes

Turn noisy readings into a belief that knows how wrong it might be

You follow a truck on a wet road. Your radar says it is 38.4 m ahead. A tenth of a second later it says 39.1 m. Then 38.2 m. The truck did not jump around.

The radar did. So how far away is the truck, really?

You can do better than trusting the last number. You know the truck moves smoothly. You know roughly how noisy the radar is. Put those two facts together and you get a state estimate: your best guess of the truck's range and speed, plus how unsure you are.

The state is the small set of numbers that describes the object right now. For a car ahead it might be range and closing speed. The belief is your best guess of the state together with your doubt. The doubt is a variance: the expected squared error. Its square root, the standard deviation, is in metres, which is easier to picture.

Every cycle does two things. First it predicts: move the belief forward in time using a motion model, and grow the doubt, because the world may have changed. Then it updates: compare the new reading with the prediction, and move part of the way toward the reading. How far it moves is set by the Kalman gain. Think of the gain as a trust slider between the prediction and the sensor.

x̂− = x̂ + v·Δt    P− = P + Q    K = P− / (P− + R)    x̂ ← x̂− + K(z − x̂−)    P ← (1 − K) P−
x̂
the estimate of the range, in metres
x̂−
the predicted range, before this cycle's reading
v
the estimated rate of change of the range, in m/s
Δt
the time since the last cycle, from timestamps, for example 0.1 s
P
the variance of the estimate: the honest doubt, in m²
P−
the doubt after predicting: always larger than before
Q
process noise: how much the world can surprise us in one cycle
R
measurement noise: the sensor's variance, in m²
K
the Kalman gain, between 0 (ignore the sensor) and 1 (trust it fully)
z
this cycle's reading from the sensor

This is the one-number version, with the speed treated as known. The full filter tracks range and speed together, with a 2 × 2 matrix for the doubt. The idea does not change. Work one cycle with real numbers.

Start with an estimate of 40.0 m and a doubt P = 1.0 m². The truck closes at 2 m/s, so v = −2, and Δt = 0.1 s. Take Q = 0.1 and a radar with R = 1.0 m². The radar now reads 40.6 m.

  1. Predict: x̂− = 40.0 + (−2)(0.1) = 39.8 m. P− = 1.0 + 0.1 = 1.1.
  2. Gain: K = 1.1 / (1.1 + 1.0) = 1.1 / 2.1 = 0.524.
  3. Surprise: z − x̂− = 40.6 − 39.8 = 0.8 m. This is the innovation.
  4. Update: x̂ = 39.8 + 0.524 × 0.8 = 39.8 + 0.419 = 40.22 m.
  5. Doubt: P = (1 − 0.524) × 1.1 = 0.476 × 1.1 = 0.524 m².

x̂ = 39.8 + 0.524 × 0.8 = 40.22 m,   P = 0.476 × 1.1 = 0.52 m² (standard deviation 0.72 m)

The estimate moved about half way to the reading. The doubt fell from 1.1 to 0.52. That is the whole trick, repeated ten times a second. The Kalman filter lesson derives why this gain is the best possible for linear models with Gaussian noise.

Follow the truck

Green is the truck's true range. Blue dots are radar readings. The warm line is the filter's estimate and the band is two standard deviations. At 5 s the truck brakes. Tune the noise and cut the radar.

1.0 m
10

Toy. A two-state filter (range and closing speed) with a constant-velocity model, run at 10 Hz on simulated readings. Q here scales the assumed acceleration noise.

Try three things. Set Q very small: the filter trusts its model so much that it lags when the truck brakes, and the truth leaves the band. Set Q large: the estimate jitters almost as much as the radar. Cut the radar: the band grows every cycle, because prediction alone adds doubt.

That growing band is the most important thing on this page for a safety engineer. A track that has not been seen for a second is still useful, but it must say so. Downstream code can then decide how much to trust it. This is the honest doubt that the hero's coasting track carries through the missed frames.

The code, fixed size and allocation free

c++
// A constant-velocity Kalman filter on range r and range rate v.
// 2x2 covariance written out by hand: no heap, no library, easy to review.
struct RangeTrack { float r, v; float P00, P01, P11; };

void predict(RangeTrack& t, float dt, float q) {
  t.r += t.v * dt;                                  // motion model
  // P = F P F^T + Q, with F = [[1, dt], [0, 1]] and white acceleration noise q
  float P00 = t.P00 + dt * (2 * t.P01 + dt * t.P11) + q * dt*dt*dt*dt / 4;
  float P01 = t.P01 + dt * t.P11 + q * dt*dt*dt / 2;
  float P11 = t.P11 + q * dt*dt;
  t.P00 = P00; t.P01 = P01; t.P11 = P11;
}

// Returns the normalised innovation squared, used to gate and to check health.
float update(RangeTrack& t, float z, float R) {
  float nu = z - t.r;                              // innovation: the surprise
  float S  = t.P00 + R;                            // its expected variance
  float K0 = t.P00 / S, K1 = t.P01 / S;            // gain for r and for v
  t.r += K0 * nu;  t.v += K1 * nu;
  float P00 = (1 - K0) * t.P00;
  float P01 = (1 - K0) * t.P01;
  float P11 = t.P11 - K1 * t.P01;
  t.P00 = P00; t.P01 = P01; t.P11 = P11;
  return nu * nu / S;                              // about 1 on average if R and Q are right
}

The last line returns the normalised innovation squared (NIS): the surprise divided by how surprised the filter expected to be. If the filter is honest, its average is close to 1 for a one-number reading. If it averages 5, the filter is overconfident. That one number is a cheap runtime monitor for the filter itself.

Design and failure

In a real layer, the filter is not one object. It runs inside every track. A system with 64 tracks runs 64 small filters each cycle. That is why it is written allocation free and branch light. With 4 states and fixed arrays, it costs microseconds.

The common failures are three. A wrong motion model: a turning car tracked with a straight-line model lags in every turn. A wrong time step: using the nominal 100 ms when the real gap was 140 ms puts every prediction behind. Wrong noise values: tuned on the highway and shipped to the city.

SymptomLikely causeWhat reveals itWhat to turn
The estimate lags every manoeuvreQ too small, or a motion model too simpleNIS spikes at braking and turnsraise Q, or switch models (IMM, Chapter 3 lesson)
The estimate jitters like the raw readingsQ too large or R too smallestimate variance close to the raw variancelower Q; measure R from data
Every prediction is slightly behindnominal time step used instead of the real gapa histogram of timestamp gapscompute the time step from capture times
Debugging tip. If the average NIS is far above 1, the filter is too sure of itself: raise Q or R, or fix the motion model. If it is far below 1, it is too timid. Plot NIS over a drive; spikes line up with manoeuvres the model does not cover. The filter consistency lesson shows the full test.

On the frontier, learned motion models predict where a pedestrian will walk better than a constant-velocity model. They usually feed the layer as an extra input, not a replacement. The filter stays because its doubt is honest and its cost is bounded. For non-linear sensors, the extended and unscented Kalman filters carry the same idea. For where doubt comes from in learned models, see uncertainty in robot perception.

Sizing it: one filter per track

A 2-D track with position and velocity has 4 states and a 4 × 4 covariance: 4 + 16 = 20 floats, or 80 bytes. The predict step multiplies 4 × 4 matrices, about 2 × 4³ = 128 multiply-adds, plus the noise term.

64 tracks × ~150 operations = ~10,000 operations per cycle → a few microseconds on a modern core

So the filter is never the time problem. The lead's worry is elsewhere: noise values tuned on one model and one road, and timestamps that lie. Those are what the failure table below is about.

The five interview dimensions, for this chapter
Concept
"Explain the Kalman gain to a new graduate." A trust slider: the share of the surprise you believe. It is large when the prediction is unsure and small when the sensor is noisy.
Design
"What state would you track for a car ahead, and why?" Position and velocity at least; add acceleration or heading rate for manoeuvres, but each state costs tuning and test effort.
Code
"Write predict and update for a 1-D constant-velocity filter." The code above, in under 30 lines, with the innovation returned.
Debug
"The track lags every time the lead car brakes." Q too small or the motion model too simple; check NIS spikes at braking events.
Frontier
"Where do learned models help estimation?" Motion prediction and measurement models; the filter keeps bounded cost and honest doubt.
Interview question: "A track has not been updated for 0.8 s. What should its covariance be doing, and why does it matter downstream?"

Chapter 3

Tracking many things

Decide which detection belongs to which track, every cycle

Two people cross a street from opposite sides. They pass close to each other in the middle. Each frame, the detector reports two boxes. It does not say which box is which person. It only says "pedestrian here, pedestrian there".

The tracker must decide. If it gets it wrong in the middle, it swaps their names. Track 1 now follows the person who started on the right. Their velocities flip. A prediction that said "walking away from the lane" now says "walking into it". This is an identity swap, and it can trigger a brake for no reason or hide a real threat.

Matching detections to tracks is called data association. It has three parts. First, predict where each track should be now. Second, rule out matches that are too far away; this is gating. Third, choose the best set of matches over all tracks at once.

Keep their names straight

Green lines are the two people's true paths. Purple dots are detections. The warm numbers are the tracker's track IDs. A red mark shows a swap. Choose a method and add noise.

0.25 m

Toy. Two walkers at 1.4 m/s, one detection each per frame at 10 Hz, 10% of detections missed at random, an alpha-beta tracker. The two "nearest" methods take the closest detection within 1.5 m, track 1 first. "Best overall" gates by the walkers' noise and checks both possible pairings, picking the lower total distance.

Run each method a few times. "Nearest to last seen" swaps often, because when two people are close, the nearest detection to where track 1 was may belong to the other person. "Predict, then nearest" helps: each track looks where its person should be now. "Best overall" helps again, because a greedy choice for track 1 can steal track 2's detection.

The gate: how far is too far?

A distance in metres is a poor gate. A track that was seen a moment ago has a tight prediction. A track that has been coasting for a second is unsure in every direction. The gate should scale with that doubt. The Mahalanobis distance does exactly that: it measures the surprise in units of expected spread.

d² = νT S−1 ν    accept if   d² < γ
d²
the squared Mahalanobis distance: the surprise, measured in standard deviations, squared
ν
the innovation vector: detection minus predicted position, for example (Δx, Δy)
S
the innovation covariance: the track's predicted doubt plus the detector's noise
γ
the gate threshold, taken from the chi-square table; 9.21 keeps 99% of true matches for a 2-D position

Work one by hand. Take a diagonal S with standard deviations of 0.5 m in both directions, so each variance is 0.25 m². A detection lands 0.6 m ahead and 0.3 m to the left of the prediction.

d² = 0.6²/0.25 + 0.3²/0.25 = 0.36/0.25 + 0.09/0.25 = 1.44 + 0.36 = 1.80 < 9.21 → inside the gate

Now the same 0.6 m and 0.3 m offset, but the track is fresh, with a standard deviation of 0.15 m (variance 0.0225). Then d² = 0.36/0.0225 + 0.09/0.0225 = 16 + 4 = 20. That is outside the gate. The same offset is fine for an unsure track and impossible for a sure one.

A track's life

Detections come and go, so tracks need rules for birth and death. A common scheme is the M-of-N rule: a new track is tentative until it is matched in M of its last N cycles, then it is confirmed. A confirmed track that misses a cycle is coasting: it predicts, its doubt grows, and it stays alive for a while. After too many misses it is deleted.

  1. Tentative. Born from an unmatched detection. Not shown to the driver. Not used by the brake.
  2. Confirmed. Matched in, say, 3 of the last 4 cycles. Now it counts.
  3. Coasting. Missed this cycle. Predicts forward with growing doubt. This is how the hero's missed walker stays on the map.
  4. Deleted. Missed for too long, for example 10 cycles, or moved out of range.

Each rule is a trade. A high M rejects ghosts that last one or two frames but confirms real objects later. A long coast keeps a real object through a miss but keeps a vanished object alive too. The showcase in Chapter 11 lets you feel both.

c++
// Gate, then a greedy global assignment on a fixed-size cost matrix.
// Greedy-by-cost is a common real-time choice; the Hungarian algorithm
// gives the optimal pairing in O(n^3) when the matrix is small enough.
constexpr int MAXT = 64, MAXD = 64;
constexpr float GATE = 9.21f;                  // chi-square, 2 dof, 99%

int associate(const Track* trk, int nt, const Detection* det, int nd,
              int8_t match[MAXT]) {
  struct Pair { float d2; int8_t t, d; };
  std::array<Pair, MAXT * MAXD> pairs; int np = 0;    // stack, not heap
  for (int t = 0; t < nt; ++t)
    for (int d = 0; d < nd; ++d) {
      float dx = det[d].x_m - trk[t].px, dy = det[d].y_m - trk[t].py;
      float sx = trk[t].Pxx + det[d].var_x, sy = trk[t].Pyy + det[d].var_y;
      float d2 = dx*dx / sx + dy*dy / sy;            // diagonal S for brevity
      if (d2 < GATE) pairs[np++] = {d2, (int8_t)t, (int8_t)d};
    }
  // Cheapest pairs first; ties broken by index so the result is deterministic.
  std::sort(pairs.begin(), pairs.begin() + np, [](const Pair& a, const Pair& b) {
    return a.d2 != b.d2 ? a.d2 < b.d2 : (a.t != b.t ? a.t < b.t : a.d < b.d); });
  bool usedD[MAXD] = {}; int nm = 0;
  for (int t = 0; t < nt; ++t) match[t] = -1;
  for (int i = 0; i < np; ++i) {
    auto& p = pairs[i];
    if (match[p.t] < 0 && !usedD[p.d]) { match[p.t] = p.d; usedD[p.d] = true; ++nm; }
  }
  return nm;                // unmatched detections become tentative tracks
}

The cost matrix lives on the stack and has a fixed upper size. That bounds memory. The two loops are bounded by 64 × 64, which bounds time. The sort has a total order, which bounds surprise. For 64 tracks the 4,096 pairs fit easily in a few kilobytes.

When it breaks, and the frontier

Three failures show up again and again. Identity swaps at crossings, which you measure with an ID-switch count. Track fragmentation, where one object gets several short tracks because the coast is too short. And clutter, where radar reflections from guard rails spawn tentative tracks every cycle and eat the budget.

SymptomLikely causeWhat reveals itWhat to turn
ID switches where objects crossno prediction, a loose gate, or greedy orderID switches per kilometre, located on a mappredict first; Mahalanobis gate; joint assignment
One object gets several short tracksthe coast is shorter than real occlusionstrack count per object in labelled logsa longer, doubt-aware coast
Cycle time rises in rain or near guard railsradar clutter spawns tentative trackstentative track count per cyclea clutter map, a cap on tentative tracks, counted overflow
Debugging tip. If ID switches cluster where objects cross, the motion model or the gate is too loose. If they cluster after occlusions, the coast is too short. Count switches per kilometre on a fixed set of logs and track that number per release.

The field has moved fast here. SORT (2016) showed that a Kalman filter plus the Hungarian algorithm on good detections is a strong baseline. DeepSORT (2017) added appearance features from a network. ByteTrack (2021) kept low-confidence detections for a second round of matching, which recovers occluded objects.

AB3DMOT (2020) carried the same recipe to 3-D. End-to-end trackers learn association inside the network. The multi-target tracking lesson covers JPDA, MHT, IMM motion models and the metrics. The data association lesson works the gating and assignment in depth.

Sizing it: the assignment

With 64 tracks and 64 detections the cost matrix has 64 × 64 = 4,096 entries. Gating usually leaves only a few per row. The Hungarian algorithm costs on the order of n³: 64³ = 262,144 steps at worst, still well under a millisecond. Greedy by cost sorts the gated pairs: with 200 pairs that is about 200 × log₂200 ≈ 1,500 comparisons.

The real time risk is the number of detections, not the algorithm. Rain clutter can turn 64 into 600, and 600³ is 216 million. That is why the capacity is fixed and overflow is counted, never silently grown.

The five interview dimensions, for this chapter
Concept
"Why gate with Mahalanobis distance instead of metres?" It scales with each track's doubt: a fresh track gets a tight gate, a coasting one a wide gate.
Design
"Design the track life cycle for a highway system." Tentative, confirmed with M of N, coasting with a doubt-aware limit, deleted; name the trade for each number.
Code
"Implement gating plus assignment with no heap." Fixed arrays, chi-square gate, sorted pairs with a total-order tie-break, greedy or Hungarian.
Debug
"ID switches doubled after a model update." Compare detection jitter and confidence before and after; the tracker's noise settings were tuned for the old model.
Frontier
"SORT versus ByteTrack versus end-to-end." Same backbone of predict and assign; ByteTrack reuses weak detections; end-to-end learns association but is harder to bound.
Interview question: "Two pedestrians cross and our tracker swaps their IDs. What is the first fix you try?"

Chapter 4

Sensor fusion and spatial reasoning

Put every sensor in one frame and one moment before you compare them

A car is stopped 40 m ahead at a red light. Your radar sees it at 40.0 m. Your camera sees it too. But after a pothole knocked the camera bracket by half a degree, the camera says 53 m. Are those one car or two?

If the layer decides "two", it shows a phantom second car on the display. If it decides "one" but trusts the camera's range, it brakes late. Either way the problem is not the camera's network. It is geometry: where each sensor sits, which way it points, and when it took its reading.

Sensor fusion means combining readings from different sensors into one belief. Before you can combine anything, two things must hold. The readings must be in the same frame of reference, meaning the same origin and axes. And they must describe the same moment.

Frames and transforms

Each sensor measures in its own frame. The camera's frame has its origin at the lens. The radar's is at the radar's face. The layer works in the vehicle frame, often with the origin at the rear axle, x forward and y left. A transform moves a point from one frame to another: a rotation, then a shift.

The numbers inside each transform are the extrinsic calibration: the sensor's position and angles on the vehicle. They are measured at the factory and can drift with heat, vibration and knocks. A tiny angle error grows with range. At 40 m, a 1° yaw error moves a point sideways by 40 × tan(1°) = 40 × 0.01746 = 0.70 m. That is half a lane.

Range from a single camera

A single camera does not measure distance. One classic trick is the ground plane: assume the road is flat, and the object stands on it. Then the image row of the object's bottom edge gives the angle below the horizon, and the camera's height gives the range.

Z = h / tan(θ)
Z
the range to the object along the road, in metres
h
the camera's height above the road, for example 1.4 m
θ
the angle from the horizon down to the object's contact point, read from the image row and the camera's pitch

Work it at 40 m with h = 1.4 m. The true angle is θ = atan(1.4 / 40) = atan(0.035) = 2.00°. Now suppose the camera's pitch is wrong by 0.5°, so the code thinks the angle is 1.50°.

Z = 1.4 / tan(1.50°) = 1.4 / 0.02619 = 53.5 m  instead of 40.0 m: a 34% error from half a degree

Tilt the other way and θ becomes 2.50°: Z = 1.4 / 0.04366 = 32.1 m. The error is not symmetric, and it explodes at long range, where the angle is small. A slope in the road does the same as a pitch error. This is why camera-only range is checked against radar or stereo, and why calibration has its own monitors.

Line up two sensors

Top-down view. Blue is the radar's reading of the stopped car; purple is the camera's. The warm circle is the association gate. Push the calibration and timing errors until the layer sees two cars.

0.0°
0.00°
0 ms

Toy geometry. A car stopped 40 m ahead, our car closing at 20 m/s, a camera 1.4 m above a flat road, a fixed 2.5 m gate. Real systems gate with the Mahalanobis distance from Chapter 3.

The time offset needs one more line of arithmetic. Our car closes at 20 m/s. If the camera frame is 100 ms older than the radar scan, the camera saw the car 20 × 0.1 = 2.0 m further away. Nothing is wrong with either sensor. They simply describe different moments.

The fix is time alignment. Every reading carries its capture time. Before comparing, the layer predicts each track to the reading's capture time, using the filter from Chapter 2. Turn on "Align timestamps" in the device and the time error disappears. Calibration errors do not: no software trick removes a bent bracket. Only a calibration check finds it.

Early, late and in between

Where in the pipeline do you combine sensors? There are three common answers.

StyleWhat gets combinedStrengthWeakness
Early fusionraw data (pixels, radar points) before detectionthe network sees everything; best accuracyone sensor's fault corrupts the whole input; hard to monitor
Mid-level fusionlearned features, for example in a bird's-eye-view gridstrong modern resultsstill inside the network; the layer sees only the output
Late fusionobject lists or tracks from each sensoreach sensor checkable on its own; graceful when one failsthrows away information; needs good association

Many production stacks use a learned early or mid-level fusion for the main perception, plus a late-fusion path in the deterministic layer for checking. The second path is simpler and independent, which is exactly what a monitor needs. The fusion architectures lesson compares them in depth.

Geometric checks you can prove

Geometry gives the layer cheap, provable checks on the model. Three are common.

c++
// Move a radar point into the vehicle frame, then into the camera image,
// and check it lands in the camera's box. All matrices fixed size.
struct Pose { float R[3][3]; float t[3]; };   // extrinsic calibration
struct Intr { float fx, fy, cx, cy; };          // pinhole intrinsics

inline void apply(const Pose& T, const float p[3], float out[3]) {
  for (int i = 0; i < 3; ++i)
    out[i] = T.R[i][0]*p[0] + T.R[i][1]*p[1] + T.R[i][2]*p[2] + T.t[i];
}

// radar_to_veh and veh_to_cam come from calibration; the camera frame has z forward.
bool reprojects_into_box(const float radar_pt[3], const Pose& radar_to_veh,
                         const Pose& veh_to_cam, const Intr& K,
                         const Box2D& box, float margin_px) {
  float pv[3], pc[3];
  apply(radar_to_veh, radar_pt, pv);       // radar frame -> vehicle frame
  apply(veh_to_cam, pv, pc);               // vehicle frame -> camera frame
  if (pc[2] < 0.5f) return false;         // behind or too close to the lens
  float u = K.fx * pc[0] / pc[2] + K.cx;  // perspective divide
  float v = K.fy * pc[1] / pc[2] + K.cy;
  return u > box.u0 - margin_px && u < box.u1 + margin_px &&
         v > box.v0 - margin_px && v < box.v1 + margin_px;
}

This function is a monitor in 20 lines. Count how often it fails per hour per sensor pair. A slow rise means the calibration is drifting. A sudden jump after a known pothole means the bracket moved. Both deserve an alert long before the tracker starts splitting cars.

When it breaks, and the frontier

SymptomLikely causeWhat reveals itWhat to turn
Twins appear at long range onlya calibration angle error (yaw or pitch)camera minus radar offset plotted against rangerecalibrate; add an online calibration monitor
Twins appear only while turning or brakinga time offset between sensorsthe same offset plotted against yaw rate and accelerationalign to capture time; fix driver timestamping
Boxes float above or sink into the roadpitch error or a sloped roadground-contact residual per frameuse a road model; down-weight camera range on slopes
Debugging tip. If objects split into twins at long range but not short range, suspect an angle error (yaw or pitch). If they split only when the car turns or brakes, suspect a time offset: the error grows with motion, not with range. Plot the camera-minus-radar offset against range and against yaw rate.

On the frontier, bird's-eye-view networks such as BEVFusion (2022) fuse cameras and lidar inside the model and lead many benchmarks. Online calibration estimates extrinsics while driving. Neither removes the need for a checkable late path: when the learned fusion is wrong, the geometry monitors are how you find out. See why fuse at all, calibration and time sync, calibration for robot perception, camera geometry and multi-view geometry.

Sizing it: the data flow of one fused reading

radar point (range, azimuth, range rate, t_capture) # radar frame ↓ extrinsics radar→vehicle (3x3 rotation + shift, per vehicle, versioned) vehicle point (x, y, v_radial, t_capture) # vehicle frame ↓ predict every track to t_capture (Chapter 2) gate d² against each predicted track (Chapter 3) ↓ project into the image with veh→cam + intrinsics check does it land in the camera box? (reprojection monitor)

Each arrow is a place where a wrong number hides. A good design logs the calibration version with every frame, so a replay uses the same numbers the car used.

The five interview dimensions, for this chapter
Concept
"Why does a 0.5 degree pitch error matter?" Ground-plane range is h / tan(θ); at 40 m the angle is only 2 degrees, so half a degree is a 34% range error.
Design
"Early or late fusion for the safety path?" Late: each sensor stays checkable alone and the system degrades gracefully when one fails.
Code
"Project a radar point into an image." Two rigid transforms, a perspective divide, a box test, and a guard for points behind the lens.
Debug
"Objects split into twins when we brake." A timestamp offset between sensors; align by predicting tracks to each capture time.
Frontier
"BEV fusion networks: do they replace this?" They improve perception; the layer still needs an independent geometric path to check them.
Interview question: "Camera and radar agree on a stopped car at 10 m but disagree by several metres at 60 m. The disagreement does not change when we brake. What is the likely cause?"

Chapter 5

Guardrails around a learned model

Check the model with rules simple enough to prove

Back to the bridge shadow. The network says "object, 12 m ahead, confidence 0.71". The radar sees nothing there. The object appeared from nowhere, already inside 15 m, with no history. Three separate clues say it is not real. A runtime monitor is code that reads those clues and decides.

A monitor does not try to be a better detector. It asks narrower questions that have provable answers. Could a real object do this? Do the other sensors agree? Is the input healthy? Each question is simple enough to test completely and to argue about on paper.

Kinds of check

Doer and checker

The pattern behind all of this is doer and checker. The doer is the complex component that does the work: the network. The checker is a simple component that watches the doer and can veto it. The checker must be much simpler than the doer, or you have only moved the problem.

The Simplex architecture, from Lui Sha and colleagues, makes this formal for control. A complex, high-performance controller runs normally. A simple, verified safety controller takes over when the system nears the edge of a known-safe region. The same shape works for perception: a learned path does the seeing, a simple deterministic path decides whether to believe it.

Set the threshold

Each object gets a plausibility score. Green is the spread of scores for real objects; purple for ghosts. Objects below the warm line are rejected. Slide the line, then add checks and watch the two hills separate.

0.62

Toy. Scores are drawn from two normal distributions with illustrative means and a spread of 0.12. Each check moves the ghost scores down by an illustrative amount. Real monitors are tuned on recorded drives with labelled ghosts and real objects.

With only the model's confidence, the two hills overlap heavily. Every threshold rejects some real objects or passes some ghosts. Add checks and the ghost hill slides left, because each check is independent evidence. The overlap shrinks, and one threshold can do both jobs well.

The threshold is a trade

Two errors fight. A false accept lets a ghost through: a phantom brake. A false reject discards a real object: a missed brake. Moving the threshold trades one for the other. The curve of all those trades is the ROC curve (receiver operating characteristic).

PFA = 1 − Φ( (τ − μg) / σ )    PFR = Φ( (τ − μr) / σ )
PFA
chance a ghost scores above the threshold and is accepted
PFR
chance a real object scores below the threshold and is rejected
Φ
the standard normal cumulative distribution: the share of a bell curve below a point
τ
the threshold
μg
the mean score of ghosts
μr
the mean score of real objects
σ
the spread of scores, the same for both here

Work the device's starting numbers: real objects at μr = 0.80, ghosts at μg = 0.62, σ = 0.12, and a threshold of 0.70.

PFR = Φ((0.70 − 0.80)/0.12) = Φ(−0.83) = 0.20  ·  PFA = 1 − Φ((0.70 − 0.62)/0.12) = 1 − Φ(0.67) = 0.25

One real object in five rejected and one ghost in four accepted is useless. The cure is not a cleverer threshold. It is more independent evidence, which moves the hills apart. That is why monitors stack several simple checks.

What a monitor may do

A monitor's output is not just "true or false". It has a small menu, and the choice depends on the hazard. It can flag an object as low trust, so the display shows it and the brake ignores it. It can degrade the system: limit speed, warn the driver, widen margins. It can fall back: hand control to a simpler path, or ask the driver to take over.

Monitors also need debouncing: one bad frame should not flip a system-wide mode. And they need hysteresis: the threshold to enter a degraded mode is stricter than the threshold to leave it, so the system does not flicker in and out.

c++
// A plausibility monitor: returns a bitmask of reasons, not a single bool,
// so logs say WHY an object was rejected and tests can check each reason.
enum Reason : uint16_t {
  OK = 0, TOO_FAST = 1, JUMPED = 2, NO_RADAR = 4, OFF_GROUND = 8,
  TOO_YOUNG = 16, BAD_SIZE = 32
};

struct Limits { float vmax, amax, size_min, size_max; };   // per class, reviewed

uint16_t plausibility(const Track& t, const Limits& L, bool radar_support,
                      float ground_err_m, float dt) {
  uint16_t why = OK;
  float speed = std::hypot(t.vx, t.vy);
  if (speed > L.vmax) why |= TOO_FAST;
  float jump = std::hypot(t.px - t.prev_px, t.py - t.prev_py);
  if (jump > L.vmax * dt + 0.5f * L.amax * dt * dt + 3.0f * std::sqrt(t.Pxx + t.Pyy))
    why |= JUMPED;                                // teleported further than physics allows
  bool close_in_path = t.px < 40.0f && std::fabs(t.py) < 2.0f;
  if (close_in_path && !radar_support) why |= NO_RADAR;
  if (std::fabs(ground_err_m) > 0.7f) why |= OFF_GROUND;
  if (t.hits_in_last4 < 3) why |= TOO_YOUNG;
  if (t.length < L.size_min || t.length > L.size_max) why |= BAD_SIZE;
  return why;                                     // caller decides: flag, degrade or reject
}

Notice the jump test. It allows the furthest an object of this class could move in one cycle, plus three standard deviations of the track's own doubt. A rule like "reject if it moved more than 2 m" would reject a fast car on a long cycle. The physics-plus-doubt form scales correctly.

When it breaks, and the frontier

Monitors fail in two quiet ways. They can be correlated with the thing they check: a radar check that uses the camera's position to look for the radar return inherits the camera's calibration error. And they can rot: tuned for last year's model, they fire too often on the new one, so someone raises the threshold and the check stops checking.

SymptomLikely causeWhat reveals itWhat to turn
A monitor fires far more after a model releasethresholds tuned for the old modelreject rate per reason bit per model versionretune on labelled logs; put the statistic in the contract
A monitor never fires in fault-injection testsit shares a failure path with the doera fault-injection test per monitorfeed it independent inputs (other sensors, raw timestamps)
The system flickers between modesno debouncing or hysteresismode changes per hourdebounce entry; a stricter threshold to leave
Debugging tip. Log every monitor decision with its reason bits. Then plot reject rate per reason per model version. A reason whose rate jumps after a model release is either catching a real regression or is mis-tuned. Both are worth a meeting before shipping.

On the frontier, calibrated confidence and conformal prediction give learned outputs error bars with stated coverage. Out-of-distribution detectors flag inputs unlike the training set. Responsibility-Sensitive Safety (2017) writes driving safety as checkable rules about distances. All of these feed the monitor; none replaces a simple, independent check. The runtime monitors lesson builds every check here in depth. For guardrails around language models, a different topic with the same spirit, see AI safety guardrails.

Sizing it: from reason bits to actions

A monitor's reason bits feed a small, reviewed table. Each row names the action and who signed it off. Keep it as data, not code, so a reviewer can read every case on one page.

reason scope action # illustrative NO_RADAR close, in path reject before confirmation JUMPED any reset the track, flag one cycle OFF_GROUND any flag low trust; display only TOO_FAST any reject; count per class cam_stale sensor degrade: radar only, warn driver contract model degrade; alert the ML on-call
The five interview dimensions, for this chapter
Concept
"What is the doer and checker pattern?" A complex doer does the work; a much simpler checker can veto it. The checker's simplicity is what makes it provable.
Design
"Design monitors for a camera pedestrian detector." Physics, persistence, radar agreement, ground contact, input health; for each, the action: flag, degrade or fall back.
Code
"Write a plausibility check." Return reason bits, scale the jump limit with physics and the track's doubt, keep limits per class and reviewed.
Debug
"Phantom braking went down but missed pedestrians went up after a monitor change." The threshold moved along the ROC curve; measure both error rates on the same labelled logs.
Frontier
"Can uncertainty estimates replace monitors?" They are useful inputs but they are models too; a simple independent check is still the guarantee.
Interview question: "Our ghost-rejection threshold cannot be set to give both few phantom brakes and few missed objects. What do you do?"

Chapter 6

The real-time budget

Add up every millisecond from photon to brake, then plan for the worst one

A pedestrian steps out. Light from their coat reaches the camera. From that instant, a clock is running. The image must be exposed, read out, sent, processed by the network, tracked, checked, decided on, sent to the brake, and turned into hydraulic pressure. Only then does the car slow down.

That chain is the latency: the time from an event in the world to the system's response. Every millisecond is road. At 100 km/h, a car covers 27.8 m every second, so 100 ms of latency costs 2.8 m.

A latency budget splits the total allowed time among the stages. Each team owns its slice and must prove it stays inside. This is the lead's main tool for real-time design: it turns "make it fast" into numbers each team can test.

Spend the budget

Each block is one stage of the chain, in milliseconds. The car below travels while the clock runs. Choose a cycle period, set the network's time and the speed, then show the worst case.

35 ms
100 km/h

Illustrative stage times, not from any product: exposure and readout 20 ms (worst 33), transfer and image processing 8 (15), waiting for the next cycle half a period on average (a full period at worst), the network as set (worst 1.4×), tracking and fusion 3 (6), monitors 1 (2), decision 1 (2), bus to the brake 5 (10), brake pressure build-up 150 (250).

Two blocks surprise people. The first is the wait for the next cycle. A time-triggered layer runs every 50 ms. An image that arrives just after a cycle starts waits up to 50 ms for the next one. On average it waits half the period. A faster cycle shrinks this block, but costs more CPU.

The second is the brake itself. Building hydraulic pressure takes a few hundred milliseconds in a typical system. It often dwarfs the software. That is why the layer's job is not to be infinitely fast. It is to be predictable, so the total is known and the trigger thresholds can account for it.

L = Σ li    d = v · L
L
total latency from photon to brake force, in seconds
li
the time spent in stage i
d
the distance the car travels before the brake acts, in metres
v
the car's speed, in m/s (km/h divided by 3.6)

Work the device's default: a 50 ms cycle, a 35 ms network, 100 km/h. The typical total is 20 + 8 + 25 + 35 + 3 + 1 + 1 + 5 + 150 = 248 ms. The speed is 100 / 3.6 = 27.8 m/s.

d = 27.8 m/s × 0.248 s = 6.9 m before the brake acts, on a typical cycle

Now the worst case. Each stage at its worst: 33 + 15 + 50 + 49 + 6 + 2 + 2 + 10 + 250 = 417 ms, which is 27.8 × 0.417 = 11.6 m. The worst case is 4.7 m longer than the typical one. A safety argument must use the worst case. That is why a lead asks for tail latency (the slowest 0.1% or 0.01% of cycles) rather than the average.

Deadlines, jitter and the cycle

Inside the layer, the unit of time is the cycle. Each cycle has a deadline: the moment its outputs must be ready. Jitter is how much the start or end of a cycle wanders from its ideal time. A cycle that finishes late is an overrun. One overrun is a fault to count. A run of them is a fault to act on.

What makes a cycle slow? Heap allocation, page faults, cache misses on badly laid-out data, lock contention, priority inversion, and other processes stealing the core. The real-time C++ lesson covers each. The real-time Linux lesson covers the operating system side: priorities, core isolation and locking memory.

c++
// A periodic task on Linux: wake at absolute times, so delays never accumulate.
// Assumes the thread already runs with a real-time priority and locked memory.
#include <time.h>

constexpr long PERIOD_NS = 50'000'000;            // 50 ms cycle
constexpr long DEADLINE_NS = 20'000'000;          // outputs due 20 ms after start

static void add_ns(timespec& t, long ns) {
  t.tv_nsec += ns;
  while (t.tv_nsec >= 1'000'000'000) { t.tv_nsec -= 1'000'000'000; ++t.tv_sec; }
}
static long diff_ns(const timespec& a, const timespec& b) {
  return (a.tv_sec - b.tv_sec) * 1'000'000'000L + (a.tv_nsec - b.tv_nsec);
}

void run(State& st, Stats& stats) {
  timespec next; clock_gettime(CLOCK_MONOTONIC, &next);
  for (;;) {
    add_ns(next, PERIOD_NS);
    clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, nullptr);
    timespec start; clock_gettime(CLOCK_MONOTONIC, &start);
    Inputs in = collect_latest(start);    // newest data; never block waiting
    Outputs out; step(in, st, out);       // the pure step from chapter 1
    publish(out);
    timespec end; clock_gettime(CLOCK_MONOTONIC, &end);
    long used = diff_ns(end, start);
    stats.record(used);                   // keep a histogram, not just a mean
    if (used > DEADLINE_NS) stats.overruns++;   // a counted fault, see chapter 7
  }
}

Two details carry the design. TIMER_ABSTIME wakes at an absolute time, so a slow cycle does not push every later cycle back. And collect_latest never blocks: if a frame is late, this cycle runs without it, which is how the hero's layer survives the late frame.

When it breaks, and the frontier

SymptomLikely causeWhat reveals itWhat to turn
Rare long cycles in an otherwise fast taskallocation, page faults, a held locktraces of the slow cycles onlypreallocate; lock memory; avoid locks on the hot path
Overruns creep up release by releasea slower model or more tracks, unmeasuredthe 99.99th percentile per release, on the same logsa timing budget per module, checked in CI
Jitter appears when another app runsshared cores and cachesa scheduler trace showing preemptioncore isolation; real-time priorities; memory bandwidth limits
Debugging tip. If the average cycle is 8 ms but one in 10,000 takes 40 ms, look for things that happen rarely: an allocation when a container grows, a log flush, a page fault on memory touched for the first time, a lower-priority thread holding a lock. Trace the slow cycles only; the average hides them.

On the frontier, perception networks move to dedicated accelerators with their own timing. That makes the network's slice more predictable but adds a hand-off between chips, which needs its own timestamps and timeouts. Mixed-criticality scheduling runs safety and non-safety tasks on one chip with guaranteed separation. See embedded RTOS, embedded real-time systems and robot real-time performance.

Sizing it: how busy is the core?

If the layer takes 8 ms of a 50 ms cycle, the core is 8 / 50 = 16% busy with it. That leaves room for jitter. At 40 ms of 50 ms, 80% busy, a single slow cycle overruns. A common design keeps two threads: an input thread that copies each arriving frame into a lock-free ring, and the time-triggered perception thread that reads the newest entry.

utilisation = 8 ms / 50 ms = 16%  ·  worst case 14 ms / 50 ms = 28% (illustrative)

The five interview dimensions, for this chapter
Concept
"Why does worst-case latency matter more than average?" The safety argument must hold on every cycle; the brake cannot rely on a typical one.
Design
"Allocate a 300 ms photon-to-brake budget." List every stage, give each a typical and worst value, include cycle wait and actuator build-up, and leave margin.
Code
"Write a periodic loop that does not drift." Absolute-time sleep, non-blocking input collection, a histogram of cycle times, counted overruns.
Debug
"Rare 40 ms spikes in a 10 ms task." Allocation, page faults, lock contention or priority inversion; trace only the slow cycles.
Frontier
"Moving the network to an accelerator: what changes?" More predictable inference, a new cross-chip hand-off that needs timestamps, sequence numbers and timeouts.
Interview question: "We need 30 ms back in the photon-to-brake chain. The network takes 35 ms. Where do you look first?"

Chapter 7

Safety architecture in plain words

Turn "what could hurt someone" into rules the software must keep

A camera cable works loose on a bumpy road. The camera keeps sending frames, but they are all the same frame. The network finds the same pedestrian in the same place, over and over. Nothing in the image says "I am frozen". Who notices, how fast, and what happens next?

Those three questions are the core of safety architecture. It is the part of the design that decides how the system detects its own faults and what it does about them. It starts long before any code, with a list of ways the system could hurt someone.

From hazard to requirement

  1. Hazard. A situation that could cause harm. "The car does not brake for a pedestrian in its path."
  2. Risk assessment. How bad, how often, how controllable by the driver. In road vehicles this gives an integrity level from ASIL A (lowest) to D (highest), under the ISO 26262 standard.
  3. Safety goal. A top-level rule. "Detect loss of camera input and react before it can cause harm."
  4. Safety requirement. A testable rule for a part. "The perception layer shall flag a camera whose frame counter stops for 2 cycles."
  5. Design and test. The code that does it, the test that proves it, and the record that links them.

The key time in this chain is the fault-tolerant time interval (FTTI): how long a fault can exist before it can cause harm. The system must detect the fault and reach a safe state inside it. Its value comes from the hazard analysis, not from the software team.

tdetect + treact ≤ FTTI
tdetect
the worst-case time from the fault starting to the system knowing about it
treact
the worst-case time from knowing to being in a safe state (warned, degraded or stopped)
FTTI
the fault-tolerant time interval, set by the hazard analysis

Work an illustrative case. A monitor checks the camera's frame counter every 50 ms cycle and flags it after 2 stuck cycles. The fault can start just after a check, so detection takes up to 50 + 2 × 50 = 150 ms. Switching to radar-only and warning the driver takes one more cycle, 50 ms. The total is 200 ms.

tdetect + treact = 150 + 50 = 200 ms  must be at most the FTTI from the hazard analysis (illustrative numbers)

Pull a wire

The boxes are the system's modes. The strip below shows heartbeats from each part, one tick per 50 ms cycle. Break a part and watch the watchdog count missed beats, then move the system to a safe mode.

Illustrative. A 50 ms cycle, a watchdog that acts after 2 missed heartbeats, and a 1 s healthy period before returning to full mode. Real values come from each system's own hazard analysis.

The device shows three ideas. A heartbeat is a small "I am alive" message each part sends every cycle, with a counter. A watchdog is an independent checker that expects those heartbeats and acts when they stop. And degraded modes form a state machine: each mode says what still works and what the system may do.

Fail-safe or fail-operational?

When a part fails, the system can do one of two things. Fail-safe means go to a state where nothing bad can happen, such as handing control back to a driver who is ready. Fail-operational means keep working, at least for a while, because there is no safe state to fall into. A highway system with no driver attending, or an aircraft in flight, must be fail-operational.

Fail-operational is much harder. It needs redundancy: a second sensor, a second computer, a second power supply. And it needs freedom from interference: a fault in one part must not be able to corrupt the other. Two copies of the same software on the same chip, sharing memory, are not independent.

The standards, in a lead's words

A lead does not need to quote clauses. A lead does need to speak the language. ISO 26262 covers functional safety for road vehicles: faults in electronics and software. SOTIF (ISO 21448) covers safety of the intended function. That is harm that comes when nothing is broken, but the function is not good enough, such as a detector missing a rare kind of object. Learned perception lives largely in SOTIF territory.

For aircraft software, DO-178C plays a similar role. IEC 61508 is the general functional-safety standard that many others grew from. Coding rules such as MISRA C++ and the AUTOSAR C++14 guidelines restrict the language to a safer subset. Many projects add no dynamic memory after start-up, no exceptions on safety paths, and checked conversions.

c++
// Degraded modes as an explicit table: every transition is visible,
// reviewable and unit-testable. No mode change hides inside an if-statement.
enum class Mode : uint8_t { Full, RadarOnly, CameraOnly, MinimalRisk };

struct Health { bool cam_ok, radar_ok, tracker_ok; };

struct Watchdog {
  uint32_t last_seq = 0; uint8_t missed = 0;
  bool alive(uint32_t seq, uint8_t limit) {   // call once per cycle
    missed = (seq == last_seq) ? missed + 1 : 0;  // counter must advance
    last_seq = seq;
    return missed < limit;
  }
};

Mode next_mode(Mode m, const Health& h, uint32_t& healthy_cycles) {
  if (!h.tracker_ok || (!h.cam_ok && !h.radar_ok)) return Mode::MinimalRisk;
  Mode want = h.cam_ok && h.radar_ok ? Mode::Full
            : h.radar_ok ? Mode::RadarOnly : Mode::CameraOnly;
  if (want == Mode::Full && m != Mode::Full) {        // hysteresis: earn your way back
    if (++healthy_cycles < 20) return m;               // 20 x 50 ms = 1 s healthy
  } else healthy_cycles = 0;
  if (m == Mode::MinimalRisk) return m;                 // leaving needs a driver or a reset
  return want;
}

The code is short on purpose. Every state and transition fits on a whiteboard. A reviewer can list every input combination and check the output. That is what "the monitor must be simpler than the thing it monitors" looks like in practice.

When it breaks, and the frontier

SymptomLikely causeWhat reveals itWhat to turn
Modes flicker under normal jitterwatchdog limits tighter than real timingmissed-beat counts on healthy drivesset limits from measured jitter; add hysteresis
A fault took far longer than planned to detectthe check read the wrong fielda fault-injection test with a stopwatchcheck counters the producer advances; compute the worst case by hand
The system reports faults at every start-upthe watchdog starts before its producersfault timestamps clustered at bootan explicit start-up phase with a grace period
Debugging tip. If the system flickers between modes, the watchdog has no hysteresis or the limits are too tight for normal jitter. If a fault took too long to detect, compute the worst case by hand: check period, plus the limit times the period, plus the reaction. The measured time should never beat the hand number by luck alone.

On the frontier, the open problem is the safety argument for learned components. How do you show a network is good enough when you cannot list its failure modes? Current practice combines large scenario-based test campaigns, runtime monitors with simple and arguable logic, and SOTIF's method of hunting for unknown unsafe scenarios. The safety-critical architecture lesson goes deep, and fail-safe and functional safety covers the firmware side.

Sizing it: one row of a hazard log

Every requirement traces back to a hazard. The record that holds the trace is usually a table. Here is one illustrative row, written the way a lead would review it.

hazard H-07 no braking for a pedestrian in path cause camera input frozen; detector repeats a stale object goal detect frozen camera input and react within the FTTI req SR-31 flag camera stale after 2 cycles with a stuck counter verify fault-injection test Monitors.FrozenCamera*; HIL timing run owner perception layer lead # illustrative example
The five interview dimensions, for this chapter
Concept
"ISO 26262 versus SOTIF, in two sentences." 26262: harm from faults in hardware and software. SOTIF: harm when nothing is broken but the function is not good enough, which covers most perception misses.
Design
"Design the degraded modes for camera plus radar." Full, radar-only, camera-only, minimal risk; for each, what still works, what is limited, and how you return.
Code
"Write a watchdog." A sequence counter that must advance, a missed-beat limit, hysteresis on recovery, a transition table.
Debug
"The camera froze and nobody noticed for 2 s." The frame had a fresh timestamp but a stuck sequence counter or identical content; the monitor checked the wrong field.
Frontier
"How do you argue safety for a neural network?" Scenario coverage, measured error rates on held-out data, and simple runtime monitors that bound the consequences.
Interview question: "Our camera driver stamps each frame with the time it was received, and a frozen camera keeps sending the last frame. Which check catches it?"

Chapter 8

The active-safety layer and the display

Decide when to warn and when to brake, and show the driver the same truth

The driver looks down at the radio for two seconds. Ahead, traffic stops. The car closes on a stopped hatchback at 72 km/h. Every other part of the stack can be fine and this is still the moment that matters. The active-safety layer is the deterministic code that decides, right now, whether to warn and whether to brake.

The best-known active-safety function is automatic emergency braking (AEB). It is deliberately simple. It reads the tracks, picks the most dangerous one in the car's path, and asks one question: how soon will we hit it?

Time to collision

The time to collision (TTC) is the range divided by the closing speed. It answers "if nobody changes anything, how many seconds until contact?" It is simple, it needs only two numbers from the track, and those two numbers come straight from the filter of Chapter 2.

TTC = r / vc    areq = vc² / (2 (r − vc tL))
TTC
time to collision, in seconds, if neither car changes speed
r
range to the object, in metres, from the track
vc
closing speed, in m/s: how fast the range shrinks
areq
the steady deceleration needed to stop just at the object, in m/s²
tL
the latency before braking starts, from Chapter 6; the car keeps closing during it

Work one by hand. We close on a stopped car at 20 m/s (72 km/h) from 40 m. TTC = 40 / 20 = 2.0 s. With no latency, the deceleration to stop exactly at the car is 20² / (2 × 40) = 400 / 80 = 5.0 m/s². That is firm braking, well inside what a dry road allows.

with tL = 0.3 s: areq = 20² / (2 (40 − 20 × 0.3)) = 400 / 68 = 5.9 m/s²

The 0.3 s of latency cost 6 m and raised the needed braking by 18%. Wait another second and the range is 20 m. Then areq = 400 / (2 × 14) = 14.3 m/s². That is beyond what tyres on a dry road can give (typically about 7 to 9 m/s²), so the crash is now certain. That is the whole design problem in one line: brake early enough to stop, but not so early that the car brakes for things a driver would handle.

Brake in time

Our car approaches a stopped car. The top lane shows positions; the lower plot shows speed against distance. The pink row is what the driver's display shows, after its own delay. Set the speed, trigger and delays.

20 m/s
2.0 s
300 ms
7.0 m/s²
150 ms

Toy kinematics: constant deceleration once braking starts, no partial-brake stage, a warning at 1.7 times the brake TTC. 7 to 9 m/s² is typical on a dry road; wet roads give less. Trigger values here are illustrative, not from any product or test protocol.

Real systems stage the response. First a warning: a sound and a symbol, early enough for an attentive driver to act. Then partial braking, which also gets the driver's attention and builds brake pressure. Then full braking if the threat remains. Each stage has its own trigger, and each must be argued against the cost of false activations.

The false-positive budget

A phantom full brake on a highway can cause the very crash it means to prevent. So active safety lives with a strict false-positive budget: a target for how rarely it may brake without cause, set per stage. Warnings get a looser budget than full braking. This is why the layer's monitors from Chapter 5 matter so much here. Every ghost that reaches this function spends that budget.

What the driver sees

The driver display (the HMI, human-machine interface) has one hard rule: what it shows must match what the system believes, with a bounded delay. If the car brakes for a pedestrian that the screen never showed, the driver loses trust. If the screen shows a car that the brake ignores, the driver relies on something that is not there.

So the display is fed from the same track list as the brake, in the same cycle, with a timestamp. It is a real-time pipeline in its own right. Its frames must not show stale data without saying so. In the device, raise the display delay and see the warning appear on screen only after the brake has started.

c++
// Active-safety decision for one cycle. Guards first, then the physics.
enum class Act : uint8_t { None, Warn, PartialBrake, FullBrake };

struct AebParams { float ttc_warn, ttc_partial, ttc_full, latency_s, a_max; };

Act decide(const Track* trk, int n, float ego_v, const AebParams& p) {
  Act act = Act::None;
  for (int i = 0; i < n; ++i) {
    const Track& t = trk[i];
    if (t.status != Confirmed && t.status != Coasting) continue;  // never tentative
    if (!in_path(t)) continue;               // predicted corridor, chapter 3
    float r  = t.range_m;
    float vc = ego_v - t.v_along;              // closing speed
    if (r <= 0.f || vc <= 0.1f) continue;    // opening or touching: no divide
    float ttc = r / vc;
    float r_eff = r - vc * p.latency_s;       // range left when brakes bite
    float a_req = r_eff > 0.f ? vc * vc / (2.f * r_eff) : 1e9f;
    Act a = Act::None;
    if (ttc < p.ttc_full || a_req > 0.8f * p.a_max) a = Act::FullBrake;
    else if (ttc < p.ttc_partial)                    a = Act::PartialBrake;
    else if (ttc < p.ttc_warn)                       a = Act::Warn;
    if (t.status == Coasting && a == Act::FullBrake)  // doubt-aware: a coasting track
      a = t.coast_cycles <= 5 ? a : Act::PartialBrake;  // earns less authority
    if (a > act) act = a;                       // most severe wins
  }
  return act;
}

Look at the coasting rule near the end. A track that has not been seen for a few cycles is real enough to keep, as Chapter 3 argued. But its authority is reduced: it can trigger partial braking but not full braking after five missed cycles. That one rule joins tracking, honest doubt and the false-positive budget.

When it breaks, and the frontier

SymptomLikely causeWhat reveals itWhat to turn
A phantom brake on an empty roada ghost track reached the decisionthe deciding track: age, status, sensors, reason bitsrequire independent support for full braking
Braking under overhead signs or bridgesstationary radar returns treated as in-path objectselevation and history of the deciding returnstationary-object handling; camera confirmation
A late brake for a crossing pedestrianthe track was outside the predicted path corridorTTC, path prediction and corridor per cycle before the eventpredict lateral motion; widen the corridor with doubt
Debugging tip. For a phantom brake, replay the log and print the track that drove the decision: its age, status, sensors that supported it and its monitor reason bits. For a late brake, print TTC and areq each cycle before the event, and check whether the track existed but was out of the path corridor.

On the frontier, AEB expands from cars ahead to pedestrians, cyclists, crossing traffic and turns at junctions. Each new scenario needs path prediction, which pulls in learned prediction models, which in turn need monitors. Rules such as Responsibility-Sensitive Safety try to state safe distances formally. The active-safety layer lesson builds the full warning and braking timeline, collision checks with simple shapes, and the display pipeline.

Sizing it: the false-positive budget, in numbers

Budgets are set per stage and per distance driven. Suppose a team targets at most one unwanted full brake per 1,000,000 km (an illustrative figure, not a standard). A fleet of 10,000 cars driving 40 km a day covers 400,000 km a day. The budget then allows one unwanted full brake every 2.5 days across the whole fleet.

10,000 cars × 40 km = 400,000 km/day → 1,000,000 / 400,000 = 2.5 days per allowed event, fleet-wide

That is why one ghost slipping through per car per week is not a small problem. At fleet scale it is a crisis.

The five interview dimensions, for this chapter
Concept
"Derive the deceleration needed to stop before an object." From v² = 2ad: a = v² / (2d), with d reduced by the distance covered during latency.
Design
"Design the staged response." Warn, partial, full; each with a trigger, a false-positive budget, and a rule for track confidence.
Code
"Write the TTC check." Skip tentative tracks, guard divide by zero and opening objects, include latency, most severe action wins.
Debug
"The car braked but the display showed nothing." The display read a different source or a delayed copy; feed both from one timestamped track list.
Frontier
"Junction and turning AEB: what is hard?" Path prediction for crossing objects, which brings learned predictors and new monitor needs.
Interview question: "We close on a stopped car at 20 m/s from 40 m, with 0.3 s of system latency. What steady deceleration do we need, and is it achievable on a dry road?"

Chapter 9

Testing a deterministic layer

Replay real drives and prove that nothing changed that should not have

An engineer refactors the tracker. It is cleaner, faster and passes every unit test. Two weeks later a test driver reports that cyclists flicker on the display at one junction. Nobody can say whether the refactor did it. The team spends a week finding out.

Determinism makes a better answer possible. If the layer gives the same output for the same input, you can replay thousands of recorded drives through the old build and the new build. Then you compare outputs bit for bit. A refactor should change nothing. If anything changes, the test tells you the first cycle and the exact field.

The layers of testing

LevelWhat it runsWhat it catchesSpeed
Unit testsone function, hand-made inputswrong maths, boundary cases (zero, negative, full arrays)milliseconds
Property testsone function, thousands of generated inputsrules that must always hold ("a coasting track's doubt never shrinks")seconds
Replay (log) teststhe whole layer on recorded drivesbehaviour changes, regressions, determinism breaksminutes to hours
Software in the loop (SIL)the layer plus simulated sensors and vehicleclosed-loop effects, rare scenarios made on purposehours
Hardware in the loop (HIL)the real computer, fed recorded or simulated signalstiming, bus loads, the real compiler and chipreal time
Fault injectionany of the above, with faults addedmonitors that do not fire, or fire too latevaries

Replay and diff

Each column is one cycle of a recorded drive. Each row is one output field. Green cells match the baseline build bit for bit; red cells differ. Pick what changed in the candidate build, then replay.

Toy. A 60-cycle log, six output fields. Which cycles differ for each change is illustrative, but each pattern is the real signature of its cause: none for a refactor, tiny float drift that may grow, random garbage, and a logic change that starts where the new threshold matters.

Each change leaves a different fingerprint. A pure refactor leaves nothing: all green. A reordered float sum changes the last bits of a position, and usually stays tiny, but it can flip a later threshold decision. An uninitialised field gives random differences that can change from run to run. A changed gate gives a clean, explainable difference that starts at the first cycle where the new threshold matters.

The fault toggle shows the other half. With a camera freeze injected at cycle 30, the test does not compare against the baseline. It checks a property: the "camera stale" flag must be set by cycle 32. A property test like this is how you prove that a monitor works, not just that it compiles.

How big does the test set need to be?

Rare events need many drives. Say a bug shows up once every 200 hours of driving. How many hours of replay give a 95% chance of seeing it at least once? The chance of missing it in one hour is 1 − 1/200 = 0.995.

P(seen) = 1 − (1 − p)n
P(seen)
the chance the bug appears at least once in the test set
p
the chance per hour of driving, here 1/200
n
the number of hours replayed

1 − 0.995n = 0.95 → n = ln(0.05) / ln(0.995) = −2.996 / −0.005013 = 598 hours

So a 600-hour replay set gives a 95% chance to see a 1-in-200-hour bug. A 50-hour set gives 1 − 0.99550 = 22%. That is why teams keep large curated log libraries, run them on many machines in parallel every night, and add every incident's log to the set.

c++
// A golden replay test and a fault-injection property test, in GoogleTest style.
#include <gtest/gtest.h>

TEST(Replay, MatchesBaselineBitForBit) {
  for (const auto& log : load_log_set("nightly")) {      // recorded drives
    State st = log.initial_state;
    for (std::size_t k = 0; k < log.cycles.size(); ++k) {
      Outputs out; step(log.cycles[k].in, st, out);
      // Compare bytes, not values: catches 1-ULP float drift and padding garbage.
      const Outputs& ref = log.cycles[k].baseline_out;
      ASSERT_EQ(0, std::memcmp(&out, &ref, sizeof(Outputs)))
          << log.name << " first diff at cycle " << k << ": " << describe_diff(out, ref);
    }
  }
}

TEST(Monitors, FrozenCameraFlaggedWithinTwoCycles) {
  auto log = load_log("urban_crossing_042");
  freeze_camera_from(log, /*cycle=*/30);     // same sequence number from cycle 30 on
  State st = log.initial_state;
  for (std::size_t k = 0; k <= 32; ++k) {
    Outputs out; step(log.cycles[k].in, st, out);
    if (k < 30)  EXPECT_FALSE(out.health.cam_stale) << "false alarm at " << k;
    if (k == 32) EXPECT_TRUE(out.health.cam_stale)  << "missed the freeze";
  }
}

The byte comparison is strict on purpose, and it has a cost. Padding bytes inside a struct must be zeroed, or the test flags garbage. That strictness is a feature: it catches uninitialised memory, one of the hardest bugs to find any other way.

Coverage, and when it breaks

Code coverage says which lines ran. Safety work often asks for more: every branch taken both ways, and for high integrity levels, each condition shown to affect its decision (a criterion called MC/DC). Scenario coverage asks a different question: did the logs include night, rain, tunnels, crowds, and the hero's ghost under a bridge?

SymptomLikely causeWhat reveals itWhat to turn
The replay test is flakyundefined behaviour or non-determinismthe same build replayed twice gives different bytessanitizers; zero padding; remove clock reads
All tests pass, yet the field failsthe log set lacks that scenarioscenario coverage against the operating domainadd every incident log; mine logs for rare scenes
The nightly replay takes too longone machine, serial logswall time per logshard logs across machines; replay is embarrassingly parallel
Debugging tip. If a replay test fails only on some machines, suspect uninitialised memory or a different compiler flag such as fast-math. If it fails at the same cycle every time, read the diff at that cycle: the first changed field names the module to look at.

On the frontier, teams use simulation and generative models to create rare scenarios that logs rarely contain. Re-simulation runs recorded sensor data through a closed loop by synthesising what the sensors would have seen. These widen coverage, but the bit-exact replay on real logs stays the backbone. See debugging filter consistency for a test you can run on every track.

Sizing it: what a replay log holds

header vehicle id, calibration version, model version, build hash per cycle inputs every message with capture time and sequence number ego speed, yaw rate, gear outputs tracks, health flags, action, display list # the baseline labels offline annotation for scoring (Chapter 11) size about 6 KB per cycle at 20 Hz = 0.43 GB per hour, inputs only after detection

Logging after the detector, not raw images, keeps the layer's replay cheap: 6 KB × 20 × 3,600 = 432 MB an hour. Raw camera logs are far larger and live in a separate store for the ML team.

The five interview dimensions, for this chapter
Concept
"Why does determinism make testing cheaper?" Same input gives same output, so any difference in replay is a real change you can locate to one cycle and field.
Design
"Design the test strategy for the layer." Unit, property, nightly replay on a growing log set, SIL scenarios, HIL timing, fault injection for every monitor.
Code
"Write a replay test." Loop over logs and cycles, compare bytes, report the first differing cycle and field.
Debug
"The replay test is flaky." Non-determinism: uninitialised memory, races, unordered iteration, or a clock read inside the step.
Frontier
"Can simulation replace road logs?" It adds rare scenarios cheaply; the gap between simulated and real sensors means real logs stay the reference.
Interview question: "A refactor changes the last bits of track positions on a few cycles. The team says it is harmless rounding. What do you ask for?"

Chapter 10

Leading the team

Set the rules, review the work, and own the line between ML and classical

Monday, 9:00. A new model drops from the ML team. It is 4% better on the benchmark. By Wednesday, test drivers report more phantom brakes under bridges.

The ML team says the model is better. Your team says the tracker did not change. Both are right. Nobody owns the gap between them.

Owning that gap is the lead's job.

The technical chapters were about what the layer does. This one is about the people and the agreements that keep it working. A lead in this role spends the week on a handful of things, and each one can be done well or badly.

Set engineering standards

A standard is a rule the whole team follows without debate each time. Good standards are short, checkable by a tool or a reviewer, and come with a reason. Here is a starting set for a deterministic perception layer.

  1. No heap allocation after start-up on the cycle path. Checked by a custom allocator that aborts in tests if called after init.
  2. Every module is a step function. Inputs and state in, outputs and state out. No clock reads, no globals.
  3. Every loop has a fixed upper bound. No "while not converged" without a maximum iteration count.
  4. Every threshold has an owner, a reason and a test. Written next to it in the code, linked to the requirement.
  5. Every message carries capture time, sequence number and producer version.
  6. Every change passes the bit-exact replay, or comes with an explained, reviewed diff.
  7. Timing is measured, not assumed. Each module publishes a cycle-time histogram; the 99.99th percentile is reviewed per release.

Review design and code

Code review in this layer has a different checklist from web code. A reviewer asks: can this allocate? Can this loop run long? Is there a tie that breaks by memory order? What happens when the input is late, missing, duplicated or garbage? Is there a test that injects each of those?

Design review happens earlier and matters more. Large decisions get an architecture decision record (ADR): a one-page note of the context, the options, the choice, and the consequences. It stops the same argument from happening every six months, and it tells new hires why the system looks the way it does.

ADR-017 Fuse radar into the camera tracker before confirmation status accepted, 2026-03-02 # illustrative example context phantom brakes under bridges: 3 field reports in 2 weeks; replay shows 3-frame ghosts with confidence 0.6 to 0.75 options A. raise camera confidence threshold to 0.8 B. require radar support to confirm in-path tracks under 40 m C. ask ML team to retrain on bridge shadows decision B now, C in the next model cycle; A rejected why A cost 6% recall on dark pedestrians in the replay set; B rejects 100% of the 41 logged ghosts, costs 0.3% recall risk radar misses low-reflectivity objects; mitigated by allowing camera-only confirmation after 5 of 5 cycles tests replay set 'bridges-v3'; property test RadarConfirm.*

Read the "why" line. It holds two numbers measured on the same logs. That is what turns an opinion into a decision.

Who owns this failure?

Each lane is one owner. Pick an incident. The trace shows where the evidence points, which clause of the interface contract was broken, and who owns the fix. Press the button to reveal the root cause.

Composite scenarios for practice, not reports from any company. Each is a common kind of cross-team failure.

The interface contract with the ML team

Most cross-team failures are contract failures. The ML team changed something the layer relied on, and nobody had written it down. A good interface contract covers more than field names. It covers the statistics the layer depends on.

Then agree shared metrics that both teams report on the same logs: ghost rate per hour, missed objects per class, ID switches, phantom brakes. A model is not "better" unless it is better on the metrics the whole system cares about. And agree ownership: a failure is owned by the team whose side of the contract broke. If the contract was silent, the lead owns writing the missing clause.

c++
// The contract, enforced at the boundary. A version check and statistics
// check run every cycle; a violation is a counted fault, not a crash.
struct ModelContract {
  uint32_t major;              // bump = layer must be re-validated
  float max_infer_ms;          // worst case the layer plans for
  float pos_sigma_m[5][4];      // per class x range band; feeds tracker R
};
constexpr ModelContract kContract{3, 45.f, /* ... measured table ... */};

enum Violation : uint8_t { None = 0, WrongMajor = 1, Overrun = 2, BadCount = 4, NonFinite = 8 };

uint8_t check_contract(const DetectionFrame& f, float infer_ms) {
  uint8_t v = None;
  if ((f.model_version >> 16) != kContract.major) v |= WrongMajor;
  if (infer_ms > kContract.max_infer_ms)            v |= Overrun;
  if (f.count > f.dets.size())                       v |= BadCount;
  for (uint16_t i = 0; i < f.count && i < f.dets.size(); ++i) {
    const auto& d = f.dets[i];
    if (!std::isfinite(d.x_m) || !std::isfinite(d.y_m) || !(d.confidence >= 0.f && d.confidence <= 1.f))
      v |= NonFinite;                              // NaN or out-of-range: never trust it
  }
  return v;                                      // the health monitor decides what to do
}

Hiring and mentoring

For this layer, hire for three signals. First, can the candidate reason about the worst case, not just the average? Ask what happens when an input is late or a container fills. Second, do they test before they trust? Ask how they would prove a monitor works.

Third, can they talk to an ML engineer as a peer? Ask them to explain a Kalman filter's noise settings using a detector's error statistics.

Mentoring follows the same lines. Pair a new engineer on a replay-test failure in their first week: it teaches the system faster than any document. Have them write their first ADR for a small decision. Rotate people between the classical and ML sides for a sprint, so the contract stops being abstract.

SymptomLikely causeWhat reveals itWhat to turn
Standards are written but ignorednothing checks themreview comments repeating the same ruleturn each rule into a CI check or lint
Only one person can change the trackera knowledge siloreview load and on-call pages by personpair on changes; rotate ownership; write ADRs
Each model release breaks a tuningthe contract has no statistics or versioningregressions that line up with model versionscontract tests on both sides; versioned statistics
Debugging tip for teams. If two teams argue about whose bug it is, stop and write down the contract clause that would have decided it. If no clause exists, the bug belongs to the gap, and the fix is a clause plus a test on both sides.

On the frontier, the line between teams moves. As models take on tracking and prediction, the layer's job shifts from doing those things to checking them. A lead who understands both sides can move the line on purpose, one clause and one monitor at a time, instead of having it moved by surprise.

A week in the role

Here is a composite week for a lead of six to ten engineers. It is not any one company's schedule, but the shape is common.

DayMain workOutput
Mondaytriage field reports by replaying their logsowners and severities for each issue
Tuesdaydesign review of a new monitor; an ADRan accepted or revised design
Wednesdaycode review on the hot path; pairing with a new hiremerged changes; a mentoring note
Thursdaycontract sync with the ML team on the next modelupdated statistics and a test plan
Fridayrelease gate: nightly bench, timing tail, open risksship, hold, or ship with a limit
The five interview dimensions, for this chapter
Concept
"What makes a good engineering standard?" Short, checkable by a tool or reviewer, and with a stated reason; for this layer: no allocation, step functions, bounded loops, owned thresholds.
Design
"Design the contract between perception ML and the deterministic layer." Fields and frames, calibrated confidence, per-class noise, timing, versioning, shared metrics, ownership.
Code
"Enforce the contract at runtime." Version, count, finiteness and timing checks every cycle, reported as reason bits to the health monitor.
Debug
"Two teams each say the other's change caused a regression." Replay with each change alone; find the broken or missing contract clause; add it and a test on both sides.
Frontier
"How will this team change in three years?" More checking, less doing; the contract and monitors become the core product.
Interview question: "A new detector is better on its benchmark but phantom brakes rose. The ML team says their model is better. How do you lead through this?"

Chapter 11

The full pipeline bench

Turn every knob at once and see what the whole system trades

Every chapter so far tuned one part. In a real system the parts fight. A stricter confirmation rule rejects more ghosts and confirms real people later. A longer coast survives misses and keeps vanished objects alive. A later brake trigger avoids false alarms and runs out of road. This bench lets you feel those fights together.

It runs the hero's toy pipeline 150 times. Each drive has a different speed, a different pedestrian, and random faults at the rates you set: ghosts, misses, frozen cameras and late frames. The bars count what happened across all 150 drives. The small scene replays one drive, the worst one, so you can see why.

Run the bench

Set the faults on the left and the layer's knobs on the right, then run. The bars total 150 drives. The scene replays the worst drive. Try to get zero phantom brakes and zero collisions at once.

3
10
1.8 s
0.20 s

Toy, the same pipeline as the hero. Speeds 43 to 72 km/h, pedestrians at 40 to 60 m walking 1.0 to 1.8 m/s, braking at 7 m/s². Fault rates per cycle: clean none; rough 2% ghosts, 3% misses, 0.2% freezes, 2% late frames; awful twice that. Counts are for this toy only.

Here is what to look for. With the layer off, ghosts become phantom brakes and misses become collisions. Turn the layer on and both fall. Then break it on purpose, one knob at a time.

Notice also the dropped-frame count. On a rough day the layer drops dozens of late frames, and nothing bad happens, because it predicts through them. That counter is a health signal a lead would put on a dashboard: if it doubles after a software update, something upstream got slower.

The bench, as a nightly job

A real team runs something like this bench every night, on real logs instead of a toy. It sweeps a few knobs, replays the whole log set, and reports the same counts. A change that moves any count gets a review. Here is the skeleton.

c++
// Sweep layer settings over a log set; report system-level counts.
struct Knobs  { int confirm_m; int coast_max; float ttc_brake; bool radar_check; };
struct Counts { int phantom = 0, missed = 0, dropped = 0, id_switch = 0; double p9999_ms = 0; };

Counts bench(const LogSet& logs, const Knobs& k) {
  Counts c; LatencyHistogram h;
  for (const auto& log : logs) {
    State st = make_state(k);                    // fixed memory, sized at start-up
    for (const auto& cyc : log.cycles) {
      Outputs out;
      auto t0 = now_ns(); step(cyc.in, st, out); h.add(now_ns() - t0);
      c.dropped += out.health.late_frames;
      // Labels come from offline annotation of the same logs:
      // a brake with no labelled object in path is phantom, a labelled
      // conflict with no brake by its deadline is missed.
      score_against_labels(out, cyc.labels, c);
    }
  }
  c.p9999_ms = h.percentile(99.99) / 1e6;
  return c;
}

Two choices matter in this skeleton. The counts are system-level (phantom brakes, missed conflicts), not module-level (detector recall). And timing is reported as the 99.99th percentile, so the worst cycles are visible every night.

Interview tip. When asked to "tune the tracker", ask first which system-level numbers it should move and what each error costs. Then propose a sweep on logged data with both error counts reported. That answer shows you think in operating points, not in single knobs.

One number worked by hand

Why does switching the radar check off bring phantom brakes back so fast? Count the ghosts. On a rough day a ghost burst starts in 2% of cycles. A drive lasts 6 s at 10 cycles a second, so 60 cycles.

Npass = g · n · P(L ≥ M)
Npass
ghost bursts per drive that last long enough to pass the M-of-N rule alone
g
the chance a ghost burst starts in a cycle, here 0.02
n
cycles per drive, here 60
P(L ≥ M)
the share of bursts at least M frames long; in this toy a burst lasts 1 to 4 frames with equal chance, so for M = 3 it is 2/4

Npass = 0.02 × 60 × 0.5 = 0.6 long ghosts per drive, about 90 over 150 drives

Only the ghosts that land in the car's path and close enough to trigger the brake become phantom brakes, so the bench shows fewer than 90. But the order of size explains the jump. Persistence alone cannot stop a ghost that persists. An independent sensor can.

The five interview dimensions, for this chapter
Concept
"What is an operating point?" The set of knob values chosen together, judged by system-level error counts and their costs, not module scores.
Design
"How do you choose the confirmation and coast settings?" Sweep them on labelled logs; report phantom brakes and missed conflicts together; pick against stated costs; re-run when any stage changes.
Code
"Write the nightly bench." Replay the log set per setting, score against labels, report counts and the 99.99th percentile cycle time.
Debug
"Collisions rose after we shortened the coast." Misses now delete tracks; reacquired objects must re-confirm, which delays the brake.
Frontier
"Can we learn the knobs?" Yes, as offline optimisation over logs; the chosen values still ship as fixed, reviewed numbers.
Interview question: "Turning off the radar check brings phantom brakes back even with a 3-of-4 confirmation rule. Why?"

Chapter 12

Interview arsenal

Carry the whole layer into the room on one page

You have built the layer piece by piece. It has a contract, a step function, a filter, a tracker, fusion, monitors, a budget, safe modes, a safety check, tests and a team. An interview for this role will probe each piece in five ways. This chapter packs it all for the room.

Draw a question

Rows are the topics; columns are the five dimensions. Tap a cell for a practice question and a short answer frame. Or press the button for a random draw, and answer aloud before you read the frame.

Practice prompts written for this lesson. They reflect common themes in interviews for this kind of role, not any company's question bank.

1. Cheat sheet

Concept30-second versionKey equation or ruleToolClassic referenceModern direction
Determinismsame input and state give same output, within a bounded timey, s' = f(x, s); C ≤ WCET ≤ Dreplay harness, sanitizersreal-time systems practicebit-exact CI on every change
State estimationpredict, then move part way to the reading by the gainK = P⁻ / (P⁻ + R)Eigen fixed-size, hand-written 2×2Kalman, 1960learned motion models as inputs
Gatingreject matches beyond the expected spreadd² = νᵀS⁻¹ν < 9.21 (2-D, 99%)chi-square tableBar-Shalom and Fortmannlearned association costs
Assignmentpick the best pairing over all tracks at onceminimise total costHungarian, greedy by costKuhn, 1955SORT, ByteTrack, end-to-end trackers
Track life cycletentative, confirmed, coasting, deletedconfirm at M of N; delete after K missesstate machineradar tracking practiceconfidence-aware track management
Fusion geometrysame frame, same moment, then compareZ = h / tan(θ); Δx ≈ Z tan(ψ)calibration targetsHartley and ZissermanBEV fusion networks, online calibration
Monitorssimple independent checks that bound the modelPFA versus PFR along the ROCreason bitmasksSimplex architectureconformal prediction, OOD scores
Latencyadd every stage; plan on the worst cased = v · Σlihistograms, tracingrate-monotonic schedulingaccelerators with timed hand-offs
Safety architecturedetect and react inside the FTTItdetect + treact ≤ FTTIwatchdog, mode tableISO 26262, IEC 61508SOTIF for learned functions
Active safetytime to collision and required decelerationa = v² / (2(r − v tL))staged warn and brakeAEB practicejunction and crossing AEB, RSS
Testingreplay real drives and diff bit for bitn = ln(1 − P) / ln(1 − p)GoogleTest, SIL, HILregression testingscenario generation, re-simulation

2. System design prompts

"Design the onboard perception layer for a camera and radar driver-assistance system."

  • Clarify: sensors and rates, compute, functions served (display, AEB, lane keeping), speed range, integrity level.
  • Data flow: timestamped frames, detector, time-triggered layer at a fixed cycle, tracker, late fusion, monitors, active safety, display.
  • Contracts: the detection message, calibrated confidence, per-class noise, timing.
  • Budget: photon to brake, typical and worst, with cycle wait and actuator.
  • Faults: stale, late, frozen, missing sensor; degraded modes and how you return.
  • Proof: bit-exact replay, fault injection for each monitor, HIL timing.

"Design runtime monitors for a learned pedestrian detector on a delivery robot."

  • Hazards first: missed person in path (worst), phantom stop (costly), late stop.
  • Checks: persistence, physics, depth or lidar agreement, ground contact, input health, model contract.
  • Actions: flag, slow down, stop and wait; with debouncing and hysteresis.
  • Thresholds: chosen on labelled logs with both error rates stated.
  • Independence: no shared failure path between the checker and the doer.

"Our drone's obstacle tracker must run at 50 Hz on a small CPU. Design it."

  • Budget: 20 ms cycle; measure the worst case; pin to a core.
  • Memory: fixed track capacity, arenas, no allocation after start-up.
  • Algorithm: constant-velocity or constant-acceleration filter, Mahalanobis gate, greedy assignment on a bounded matrix.
  • Degradation: if over budget, drop the lowest-priority tracks first, and say so in the output.
  • Test: replay flight logs, inject sensor drop-outs, check the overrun counter.

3. Coding drills

Drill 1: a fixed-capacity track table with stable IDs

  • Talk about: no heap, a free list for slots, IDs that never reuse within a window, deterministic iteration order.
c++
template<int N> struct TrackTable {
  std::array<Track, N> slot; std::array<bool, N> used{}; uint32_t next_id = 1;
  Track* spawn() {                               // O(N), bounded, no allocation
    for (int i = 0; i < N; ++i)
      if (!used[i]) { used[i] = true; slot[i] = Track{}; slot[i].id = next_id++; return &slot[i]; }
    return nullptr;                                // full: caller counts the fault
  }
  void kill(int i) { used[i] = false; }
};

Drill 2: a single-producer, single-consumer ring buffer

  • Talk about: power-of-two size, one writer index and one reader index, acquire and release ordering, no locks, what happens when full (drop newest or oldest, and count it).
c++
template<class T, int N> class Spsc {        // N must be a power of two
  std::array<T, N> buf; std::atomic<uint32_t> w{0}, r{0};
 public:
  bool push(const T& x) {                        // producer thread only
    uint32_t wi = w.load(std::memory_order_relaxed);
    if (wi - r.load(std::memory_order_acquire) == N) return false;   // full
    buf[wi & (N - 1)] = x; w.store(wi + 1, std::memory_order_release); return true;
  }
  bool pop(T& x) {                               // consumer thread only
    uint32_t ri = r.load(std::memory_order_relaxed);
    if (ri == w.load(std::memory_order_acquire)) return false;          // empty
    x = buf[ri & (N - 1)]; r.store(ri + 1, std::memory_order_release); return true;
  }
};

Drill 3: time to collision with every guard

  • Talk about: opening objects, zero range, latency, coasting tracks with less authority, the most severe action winning. The decide function in Chapter 8 is the answer; write it from memory.

4. Debugging scenarios

SymptomLikely root causeWhat reveals itFix
Phantom brakes under bridges after a model updatenew model emits short-lived high-confidence ghosts; confirmation passes themreplay with old and new model; monitor reason bits; radar support on the braking trackrequire radar support for close in-path confirmation; add ghost rate to shared metrics
Objects split into twins only while turningtimestamp offset between camera and radarcamera-minus-radar offset plotted against yaw ratepredict tracks to each capture time; fix the driver's timestamping
A one-in-10,000 cycle overrun, only in the citya container grows when track count peaks, allocating on the hot pathtrace slow cycles only; allocation hook in testsfixed capacity sized for the worst case; count overflow as a fault

5. Classical versus learned

TaskClassical, deterministicLearnedWhen to use which
Detectionradar clustering, geometric rulesneural detectorslearned for seeing; classical as an independent check
TrackingKalman filter plus assignmentend-to-end trackersclassical where you must bound behaviour; learned features to improve association
Fusionlate fusion of tracksearly or BEV fusionlearned for accuracy; late fusion for the checkable safety path
Predictionconstant velocity or turn modelslearned trajectory predictionlearned for intent; classical for a conservative envelope
Safety decisionTTC, required deceleration, rulesend-to-end planningthe last-resort brake stays simple and provable

6. Reading list

The core, as code

c++
// The whole layer in one cycle: every chapter is one line here.
void step(const Inputs& in, State& st, Outputs& out) {     // ch1: pure, time-triggered
  out.health = check_inputs(in, st);                            // ch5, ch7: stale, late, contract
  predict_all(st.tracks, in.now_ns);                            // ch2: predict, doubt grows
  align_to_capture_time(st.tracks, in);                         // ch4: same frame, same moment
  if (out.health.cam_ok) associate_and_update(st.tracks, in.cam);   // ch3: gate + assign
  if (out.health.radar_ok) associate_and_update(st.tracks, in.radar);
  manage_life_cycle(st.tracks);                                 // ch3: tentative ... deleted
  apply_monitors(st.tracks, in, out.reasons);                   // ch5: plausibility, radar support
  st.mode = next_mode(st.mode, out.health, st.healthy_cycles);  // ch7: degraded modes
  out.action = decide(st.tracks, in.ego_speed, params_for(st.mode));  // ch8: TTC, staged
  out.display = render_list(st.tracks, st.mode, in.now_ns);     // ch8: same truth as the brake
}                                                               // ch6: under WCET; ch9: bit-exact on replay
The takeaway. The learned model sees. The deterministic layer decides what to believe, on time, with fixed memory, in a way you can replay and prove. A lead makes that layer simple enough to check, writes down the contract with the model, and measures the whole system on the numbers that matter: phantom brakes, missed objects and the worst cycle.

Now press Present or Teach and explain, from memory, how the layer catches a ghost, a missed walker, a frozen camera and a late frame, and what each catch costs. Then go back to the pipeline, switch the layer off, and say aloud which line of the step function would have saved the drive.

Interview question: "In one sentence, what is the deterministic perception layer for?"
Day in the Life: Onboard Perception Software Lead
Multi-target tracking · Real-time deterministic C++ · Safety-critical architecture · Runtime monitors · Active safety · Back to Gleams