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.
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
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.
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.
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.
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.
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.
| Domain | Learned part | Deterministic layer | Last-resort function |
|---|---|---|---|
| Driver assistance | camera detector, lane network | tracker, camera and radar fusion, monitors | emergency braking, driver warnings |
| Delivery robot | person and obstacle detector | tracker, depth cross-check, speed limits by zone | protective stop |
| Drone | obstacle segmentation | tracker on a small CPU, geofence checks | hover, climb, or land |
| Aircraft | runway or traffic detection aids | plausibility against navigation data, strict timing | alert the crew; revert to the certified function |
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.
Here is the road. Each chapter builds one part of the hero and one part of the interview.
Chapter 1
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.
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.
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.
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.
std::unordered_map keeps no stable order. Its iteration order can change between builds or library versions. If two detections tie for the same track, the one visited first wins. A different order gives different track IDs.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.
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.
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.
| Symptom | Likely cause | What reveals it | What to turn |
|---|---|---|---|
| Replay diverges after a few minutes | a tie broken by unordered iteration | the first differing cycle and field | sort with a unique tie-break; ordered containers |
| Outputs differ only when the CPU is busy | a data race between threads | thread sanitizer; a stress run with extra load | one writer per datum; a fixed hand-off order |
| One cycle in 10,000 misses its deadline | heap allocation or a first-touch page fault | the tail of the cycle-time histogram; an allocation hook in tests | reserve everything at start-up; lock memory |
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.
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.
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.
Chapter 2
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.
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.
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.
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.
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.
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.
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.
| Symptom | Likely cause | What reveals it | What to turn |
|---|---|---|---|
| The estimate lags every manoeuvre | Q too small, or a motion model too simple | NIS spikes at braking and turns | raise Q, or switch models (IMM, Chapter 3 lesson) |
| The estimate jitters like the raw readings | Q too large or R too small | estimate variance close to the raw variance | lower Q; measure R from data |
| Every prediction is slightly behind | nominal time step used instead of the real gap | a histogram of timestamp gaps | compute the time step from capture times |
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.
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.
Chapter 3
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.
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.
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.
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.
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.
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.
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.
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.
| Symptom | Likely cause | What reveals it | What to turn |
|---|---|---|---|
| ID switches where objects cross | no prediction, a loose gate, or greedy order | ID switches per kilometre, located on a map | predict first; Mahalanobis gate; joint assignment |
| One object gets several short tracks | the coast is shorter than real occlusions | track count per object in labelled logs | a longer, doubt-aware coast |
| Cycle time rises in rain or near guard rails | radar clutter spawns tentative tracks | tentative track count per cycle | a clutter map, a cap on tentative tracks, counted overflow |
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.
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.
Chapter 4
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.
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.
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.
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.
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.
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.
Where in the pipeline do you combine sensors? There are three common answers.
| Style | What gets combined | Strength | Weakness |
|---|---|---|---|
| Early fusion | raw data (pixels, radar points) before detection | the network sees everything; best accuracy | one sensor's fault corrupts the whole input; hard to monitor |
| Mid-level fusion | learned features, for example in a bird's-eye-view grid | strong modern results | still inside the network; the layer sees only the output |
| Late fusion | object lists or tracks from each sensor | each sensor checkable on its own; graceful when one fails | throws 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.
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.
| Symptom | Likely cause | What reveals it | What to turn |
|---|---|---|---|
| Twins appear at long range only | a calibration angle error (yaw or pitch) | camera minus radar offset plotted against range | recalibrate; add an online calibration monitor |
| Twins appear only while turning or braking | a time offset between sensors | the same offset plotted against yaw rate and acceleration | align to capture time; fix driver timestamping |
| Boxes float above or sink into the road | pitch error or a sloped road | ground-contact residual per frame | use a road model; down-weight camera range on slopes |
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.
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.
Chapter 5
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.
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.
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.
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.
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).
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.
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.
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.
| Symptom | Likely cause | What reveals it | What to turn |
|---|---|---|---|
| A monitor fires far more after a model release | thresholds tuned for the old model | reject rate per reason bit per model version | retune on labelled logs; put the statistic in the contract |
| A monitor never fires in fault-injection tests | it shares a failure path with the doer | a fault-injection test per monitor | feed it independent inputs (other sensors, raw timestamps) |
| The system flickers between modes | no debouncing or hysteresis | mode changes per hour | debounce entry; a stricter threshold to leave |
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.
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.
Chapter 6
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.
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.
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.
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.
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.
| Symptom | Likely cause | What reveals it | What to turn |
|---|---|---|---|
| Rare long cycles in an otherwise fast task | allocation, page faults, a held lock | traces of the slow cycles only | preallocate; lock memory; avoid locks on the hot path |
| Overruns creep up release by release | a slower model or more tracks, unmeasured | the 99.99th percentile per release, on the same logs | a timing budget per module, checked in CI |
| Jitter appears when another app runs | shared cores and caches | a scheduler trace showing preemption | core isolation; real-time priorities; memory bandwidth limits |
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.
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)
Chapter 7
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.
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.
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)
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.
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.
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.
| Symptom | Likely cause | What reveals it | What to turn |
|---|---|---|---|
| Modes flicker under normal jitter | watchdog limits tighter than real timing | missed-beat counts on healthy drives | set limits from measured jitter; add hysteresis |
| A fault took far longer than planned to detect | the check read the wrong field | a fault-injection test with a stopwatch | check counters the producer advances; compute the worst case by hand |
| The system reports faults at every start-up | the watchdog starts before its producers | fault timestamps clustered at boot | an explicit start-up phase with a grace period |
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.
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.
Chapter 8
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?
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.
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.
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.
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.
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.
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.
| Symptom | Likely cause | What reveals it | What to turn |
|---|---|---|---|
| A phantom brake on an empty road | a ghost track reached the decision | the deciding track: age, status, sensors, reason bits | require independent support for full braking |
| Braking under overhead signs or bridges | stationary radar returns treated as in-path objects | elevation and history of the deciding return | stationary-object handling; camera confirmation |
| A late brake for a crossing pedestrian | the track was outside the predicted path corridor | TTC, path prediction and corridor per cycle before the event | predict lateral motion; widen the corridor with doubt |
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.
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.
Chapter 9
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.
| Level | What it runs | What it catches | Speed |
|---|---|---|---|
| Unit tests | one function, hand-made inputs | wrong maths, boundary cases (zero, negative, full arrays) | milliseconds |
| Property tests | one function, thousands of generated inputs | rules that must always hold ("a coasting track's doubt never shrinks") | seconds |
| Replay (log) tests | the whole layer on recorded drives | behaviour changes, regressions, determinism breaks | minutes to hours |
| Software in the loop (SIL) | the layer plus simulated sensors and vehicle | closed-loop effects, rare scenarios made on purpose | hours |
| Hardware in the loop (HIL) | the real computer, fed recorded or simulated signals | timing, bus loads, the real compiler and chip | real time |
| Fault injection | any of the above, with faults added | monitors that do not fire, or fire too late | varies |
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.
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.
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.
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?
| Symptom | Likely cause | What reveals it | What to turn |
|---|---|---|---|
| The replay test is flaky | undefined behaviour or non-determinism | the same build replayed twice gives different bytes | sanitizers; zero padding; remove clock reads |
| All tests pass, yet the field fails | the log set lacks that scenario | scenario coverage against the operating domain | add every incident log; mine logs for rare scenes |
| The nightly replay takes too long | one machine, serial logs | wall time per log | shard logs across machines; replay is embarrassingly parallel |
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.
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.
Chapter 10
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.
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.
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.
Read the "why" line. It holds two numbers measured on the same logs. That is what turns an opinion into a decision.
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.
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 }
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.
| Symptom | Likely cause | What reveals it | What to turn |
|---|---|---|---|
| Standards are written but ignored | nothing checks them | review comments repeating the same rule | turn each rule into a CI check or lint |
| Only one person can change the tracker | a knowledge silo | review load and on-call pages by person | pair on changes; rotate ownership; write ADRs |
| Each model release breaks a tuning | the contract has no statistics or versioning | regressions that line up with model versions | contract tests on both sides; versioned statistics |
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.
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.
| Day | Main work | Output |
|---|---|---|
| Monday | triage field reports by replaying their logs | owners and severities for each issue |
| Tuesday | design review of a new monitor; an ADR | an accepted or revised design |
| Wednesday | code review on the hot path; pairing with a new hire | merged changes; a mentoring note |
| Thursday | contract sync with the ML team on the next model | updated statistics and a test plan |
| Friday | release gate: nightly bench, timing tail, open risks | ship, hold, or ship with a limit |
Chapter 11
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.
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.
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.
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.
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 = 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.
Chapter 12
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.
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.
| Concept | 30-second version | Key equation or rule | Tool | Classic reference | Modern direction |
|---|---|---|---|---|---|
| Determinism | same input and state give same output, within a bounded time | y, s' = f(x, s); C ≤ WCET ≤ D | replay harness, sanitizers | real-time systems practice | bit-exact CI on every change |
| State estimation | predict, then move part way to the reading by the gain | K = P⁻ / (P⁻ + R) | Eigen fixed-size, hand-written 2×2 | Kalman, 1960 | learned motion models as inputs |
| Gating | reject matches beyond the expected spread | d² = νᵀS⁻¹ν < 9.21 (2-D, 99%) | chi-square table | Bar-Shalom and Fortmann | learned association costs |
| Assignment | pick the best pairing over all tracks at once | minimise total cost | Hungarian, greedy by cost | Kuhn, 1955 | SORT, ByteTrack, end-to-end trackers |
| Track life cycle | tentative, confirmed, coasting, deleted | confirm at M of N; delete after K misses | state machine | radar tracking practice | confidence-aware track management |
| Fusion geometry | same frame, same moment, then compare | Z = h / tan(θ); Δx ≈ Z tan(ψ) | calibration targets | Hartley and Zisserman | BEV fusion networks, online calibration |
| Monitors | simple independent checks that bound the model | PFA versus PFR along the ROC | reason bitmasks | Simplex architecture | conformal prediction, OOD scores |
| Latency | add every stage; plan on the worst case | d = v · Σli | histograms, tracing | rate-monotonic scheduling | accelerators with timed hand-offs |
| Safety architecture | detect and react inside the FTTI | tdetect + treact ≤ FTTI | watchdog, mode table | ISO 26262, IEC 61508 | SOTIF for learned functions |
| Active safety | time to collision and required deceleration | a = v² / (2(r − v tL)) | staged warn and brake | AEB practice | junction and crossing AEB, RSS |
| Testing | replay real drives and diff bit for bit | n = ln(1 − P) / ln(1 − p) | GoogleTest, SIL, HIL | regression testing | scenario generation, re-simulation |
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; } };
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; } };
decide function in Chapter 8 is the answer; write it from memory.| Symptom | Likely root cause | What reveals it | Fix |
|---|---|---|---|
| Phantom brakes under bridges after a model update | new model emits short-lived high-confidence ghosts; confirmation passes them | replay with old and new model; monitor reason bits; radar support on the braking track | require radar support for close in-path confirmation; add ghost rate to shared metrics |
| Objects split into twins only while turning | timestamp offset between camera and radar | camera-minus-radar offset plotted against yaw rate | predict tracks to each capture time; fix the driver's timestamping |
| A one-in-10,000 cycle overrun, only in the city | a container grows when track count peaks, allocating on the hot path | trace slow cycles only; allocation hook in tests | fixed capacity sized for the worst case; count overflow as a fault |
| Task | Classical, deterministic | Learned | When to use which |
|---|---|---|---|
| Detection | radar clustering, geometric rules | neural detectors | learned for seeing; classical as an independent check |
| Tracking | Kalman filter plus assignment | end-to-end trackers | classical where you must bound behaviour; learned features to improve association |
| Fusion | late fusion of tracks | early or BEV fusion | learned for accuracy; late fusion for the checkable safety path |
| Prediction | constant velocity or turn models | learned trajectory prediction | learned for intent; classical for a conservative envelope |
| Safety decision | TTC, required deceleration, rules | end-to-end planning | the last-resort brake stays simple and provable |
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
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.