Safety-Critical Software Architecture

A cable works loose. A process hangs. A message arrives garbled. In a moving vehicle each of these will happen one day. The architecture decides whether the vehicle notices in a fifth of a second, or never.

Pull a wire. Freeze perception with no safety mechanisms, and watch the vehicle drive on a picture of the past. Then switch on the watchdog and freeze it again. Try every fault on every architecture. Then we build each mechanism, piece by piece.

You need some C++ and the idea of a program that runs in a loop. We build the rest from zero.

Pull a wire

Ready
The fault strikes 1.04 s into each run.

Choose a fault. It strikes 1.04 s after the run starts.

Toy system, not a real vehicle. Every process runs a 100 ms cycle. Timeouts are 300 ms, the watchdog allows 200 ms, and a check must fail twice in a row to count. You drive at 72 km/h; the car behind starts 30 m back, reacts in 1.0 s and brakes at 6 m/s². All numbers are illustrative. The third architecture also checks each message end to end (Chapter 5) and has a radar-only fallback path (Chapter 6).

Chapter 0

Software that must fail well

See why failure is certain, and why the only question is what happens next

A delivery van drives over a rough road. A camera connector, plugged in a little loose at the factory, shakes. For 80 ms the image stream stops. Then it comes back. Then it stops again.

Nothing in the perception code is wrong. The code that reads the camera waits for the next image, and it keeps the last one in the meantime. So the rest of the system goes on looking at a picture of the road from a moment ago. At 72 km/h, a moment is metres.

That story has three parts, and safety engineers keep them apart. The fault is the cause: the loose connector. The error is the wrong state inside the system: an old image that the planner treats as new. The failure is what the outside world sees: the van does not brake for a pedestrian who stepped out after the image froze.

You cannot remove every fault. Connectors loosen, chips overheat, memory bits flip when a cosmic ray passes, and every large program has bugs. What you can design is the gap between the fault and the failure. The software can notice the error and react before it becomes harm.

Rare faults happen every day

A fault that "almost never" happens is still certain across a fleet. Suppose one vehicle meets a given fault once in 100,000 hours of driving. That is about 11 years of non-stop driving. Now put 100,000 such vehicles on the road for an hour a day.

Rare, every day

Each square is one day of the year for the whole fleet. A filled square had at least one fault. Move the sliders and watch how rare a fault must be before most days stay empty.

100,000 h
100,000
1.0 h

Toy: faults arrive at random and independently (a Poisson process), each day drawn from a seeded generator. The fault rate is illustrative, not a figure for any real part.

The arithmetic is short. The fleet drives N × h hours a day. Divide by the hours between faults, and you get the expected number of faults per day.

m = N · h / T     P(at least one) = 1 − e−m
m
expected faults per day, across the whole fleet
N
the number of vehicles
h
driving hours per vehicle per day
T
mean driving hours between faults, for one vehicle

m = 100,000 × 1 / 100,000 = 1.0 per day  ·  P(≥ 1) = 1 − e−1 = 0.63  ·  per year: 365

The second formula comes from the Poisson distribution, the standard model for rare events that arrive independently. It says a count with mean m is zero with probability e−m. So most days, somewhere in the fleet, this fault happens. Here is the same arithmetic in C++.

// How often does a "rare" fault happen across a fleet?
// Poisson arithmetic: no simulation needed, and no surprises in the field.
#include <cmath>
#include <cstdio>

struct FleetExposure {
  double hoursPerFault;   // mean driving hours between faults, for ONE vehicle
  double vehicles;        // fleet size
  double hoursPerDay;     // driving hours per vehicle per day
};

// Expected faults per day across the fleet: total hours / hours per fault.
double faultsPerDay(const FleetExposure& f) {
  return f.vehicles * f.hoursPerDay / f.hoursPerFault;
}

// A Poisson count with mean m is zero with probability e^-m,
// so the chance of at least one fault is 1 - e^-m.
double pAtLeastOne(double mean) { return 1.0 - std::exp(-mean); }

int main() {
  const FleetExposure f{100000.0, 100000.0, 1.0};
  const double m = faultsPerDay(f);
  std::printf("%.2f faults per day, P(at least one) = %.2f\n", m, pAtLeastOne(m));  // 1.00, 0.63
  std::printf("%.0f faults per year\n", m * 365.0);                                 // 365
  return 0;
}

The test drive that never sees it

Now flip the question. Your team drives 10,000 km of tests at an average of 50 km/h. That is 200 hours. How likely is it that you saw this fault even once?

m = 200 / 100,000 = 0.002  ·  P(≥ 1) = 1 − e−0.002 = 0.2%

So the test drive almost certainly missed it. This is the first failure mode of the whole field: "we drove it a lot and it never happened". The diagnosis is to count exposure hours and compare them with the fault rates you care about. The fix is to stop waiting for faults. You cause them on purpose, with fault injection (Chapter 9), and you design the software so that each one is caught.

The whole lesson in one line. Safety-critical software assumes parts will fail. It finds each failure quickly, by checks that are simpler than the thing they check, and it moves the vehicle to a safe state within the time the physics allows.

A perception onboard software lead at a robotics or vehicle company owns this layer for the classical software around the learned models. In an interview, they will ask you to design it, to defend a number in it, and to say what happens when each part breaks. Here is the road.

  1. From hazard to requirement: how "this could hurt someone" becomes a rated hazard, a safety goal and a number the code must meet.
  2. The time you have: the fault-tolerant time interval, and the budget for detection and reaction. This is the hero's timeline.
  3. Fail-safe or fail-operational: stop, degrade or carry on, and why stopping can be dangerous. This is the hero's "stops hard".
  4. Detecting that something is wrong: heartbeats, watchdogs, timeouts, range checks and frozen data. This is the hero's second architecture.
  5. Trusting a message: checksums, sequence counters and timestamps. This is the hero's corrupt and delay faults.
  6. Redundancy and voting: two out of three, diversity, and the faults that hit every copy at once.
  7. Keeping parts from hurting each other: memory, time and message separation, and why the monitor must be simple.
  8. Degraded modes as a state machine: nominal, degraded, minimal risk and safe stop, with hysteresis. This is the hero's third architecture.
  9. Arguing that it is safe: traceability, the safety case, fault injection, and the standards a lead must speak about.
  10. The fault bench: every mechanism and every fault, with timing knobs and hundreds of random trials.
  11. Interview arsenal: a cheat sheet, design prompts, drills and debugging stories.
An interviewer asks: "Your team drove 10,000 test kilometres with zero camera dropouts. Is the camera dropout problem solved?"

Chapter 1

From hazard to requirement

Turn "this could hurt someone" into a rated hazard, a goal and a number

A driver holds a curve on the highway at 110 km/h. The lane-keeping software has a bug. For half a second it commands a sharp turn of the wheel. Does anybody get hurt?

That depends on three things. How bad the harm could be: at 110 km/h, a swerve into the next lane can kill. How often drivers are in that situation: highway curves are part of most long drives. And whether a normal driver could stop it: a strong, sudden torque in a curve is hard to hold.

Safety work starts here, before any code. The team lists what the vehicle could do that hurts someone. Each item is a hazard: a vehicle behaviour that can cause harm in some situation. "Unintended steering at highway speed" is a hazard. "A bug in the lane model" is not; it is a possible cause.

Three ratings for each hazard

For each hazard and situation, the team rates three things, in plain words.

This step is called hazard analysis and risk assessment. It is done by people, in reviews, with the reason for each rating written down. The ratings combine into an integrity level: a statement of how much rigour the work on that hazard needs.

Rate a hazard

Pick a hazard to load its ratings, or set the three ratings yourself. The meter shows the toy integrity level. The chain below it shows the goal and the kind of requirement that follow.

Severity
Exposure
Controllability

Toy scoring, for learning the shape only: level = S + E + C − 4, floored at 0, and 0 whenever there is no harm. A real programme uses the table in its own standard, applied by its safety engineers. The presets are example ratings, not official ones.

The toy rule in the device is simple on purpose. Each step up in any rating pushes the level up one step. No harm means no special rigour at all.

L = max(0, S + E + C − 4)     and L = 0 if S = 0
L
the toy integrity level: 0 is ordinary quality, 4 is the most demanding
S
severity: 0 none, 1 light, 2 severe, 3 life-threatening
E
exposure: 0 rare, 1 sometimes, 2 often, 3 almost always
C
controllability: 0 easy, 1 usually, 2 hard

sudden steering: 3 + 2 + 2 − 4 = 3  ·  wrong speed on the display: S = 1, E = 3, C = 0 → 1 + 3 + 0 − 4 = 0

The real standards use the same idea with their own scales and their own table. In road vehicles, the four demanding steps are called ASIL A to D (Automotive Safety Integrity Level), with D the strictest. Below A sits QM, "quality management": normal good engineering is enough. Other industries have their own scales: IEC 61508 uses SIL 1 to 4, and airborne software uses levels A to E. Chapter 9 says what these standards are for.

What the level changes

A higher level does not change what the software does. It changes how the team must build and prove it. Higher levels ask for stricter coding rules, more independent review, deeper testing, more evidence that tests cover the code, and stronger separation between parts. That costs time and money, so the level matters a great deal to a project plan.

A useful consequence: if one hazard at a high level can be split between two truly independent parts, each part may carry a lower level. The standards allow this kind of decomposition only under strict independence conditions. "Truly independent" is the hard part, and Chapters 6 and 7 are about it.

From hazard to goal to number

Each serious hazard gets a safety goal: a top-level requirement that says what must not happen, phrased against the hazard. "The system shall not apply steering torque that the driver cannot overcome." The goal inherits the hazard's level.

The goal is then refined into requirements that engineers can build and test. One of them might read: "Detect a steering command above the driver-overridable limit and remove it within 150 ms." The torque limit comes from studies of what drivers can hold. The 150 ms comes from Chapter 2: the time between the fault and the harm.

That last requirement is finally a number the software must meet. It flows down to the design: a monitor task, its period, its timeout, its reaction. Each of those becomes a requirement too, each with a test. The chain from hazard to test is called traceability, and Chapter 9 shows why reviewers care about it so much.

Many teams keep the hazard log as structured data, so tools can check the chain. Here is one row as C++, with the toy rule checked at compile time.

// A hazard log row as data, so a tool can trace it to goals, requirements and tests.
// The ratings are the analyst's judgement; the reason for each lives in the review notes.
#include <cstdint>
#include <string_view>

enum class Severity : std::uint8_t { None, Light, Severe, LifeThreatening };
enum class Exposure : std::uint8_t { Rare, Occasional, Frequent, AlmostAlways };
enum class Control  : std::uint8_t { Easy, Usually, Hard };

// TOY scoring for this lesson only. A real programme uses the table in its
// standard. The shape is the same: worse harm, more exposure and harder
// control each push the required rigour up one step, and no harm means none.
constexpr int toyLevel(Severity s, Exposure e, Control c) {
  if (s == Severity::None) return 0;                    // 0 = ordinary quality
  const int score = int(s) + int(e) + int(c);           // 1 .. 8 with these scales
  return score <= 4 ? 0 : score - 4;                    // 0 .. 4, 4 = most demanding
}

struct HazardRow {
  std::string_view id, situation, hazard, safetyGoal;
  Severity s; Exposure e; Control c;
  int level;
};

constexpr HazardRow kHz07{
    "HZ-07", "highway, 100 to 130 km/h, in a curve", "unintended steering torque",
    "SG-03: prevent steering torque the driver cannot overcome",
    Severity::LifeThreatening, Exposure::Frequent, Control::Hard,
    toyLevel(Severity::LifeThreatening, Exposure::Frequent, Control::Hard)};

static_assert(kHz07.level == 3, "life-threatening, frequent, hard to control: step 3");
static_assert(toyLevel(Severity::Light, Exposure::Rare, Control::Easy) == 0, "minor and rare: ordinary quality");
static_assert(toyLevel(Severity::LifeThreatening, Exposure::AlmostAlways, Control::Hard) == 4, "the worst corner");

When the rating goes wrong

The classic failure mode is rating exposure for the average trip. "Sudden steering only hurts in curves at speed, and most driving is not in curves, so exposure is low." But exposure means the situation where harm is possible. A long highway drive passes through many curves. Rating the trip instead of the situation pulls the level down by a step or two, and the whole design inherits that mistake.

A second classic: rating controllability with expert test drivers. Experts catch a sudden swerve that an ordinary driver would not. The diagnosis for both is the same. Read the written reason for every rating in review, and ask "in which situation, and for which driver?"

An interviewer asks: "What does an integrity level such as ASIL D tell an engineering team?"

Chapter 2

The time you have

Put the fault, the detection, the reaction and the safe state on one timeline

A perception process hangs while the vehicle moves at 108 km/h. That is 30 m/s. Every 100 ms that nobody notices, the vehicle travels 3 m on old information. How long can that go on before it becomes dangerous?

The answer belongs to the hazard and the vehicle, not to the software. If the lane-keeping command freezes, the car drifts. After some time the drift could put it in the next lane. That time is the budget.

Engineers call it the fault-tolerant time interval (FTTI): the time from the moment a fault happens to the moment a hazardous event could happen, if nothing reacts. Inside that interval, two things must happen. The system must notice the fault, and it must reach a safe state: a condition with no unreasonable risk, such as "braking to a stop" or "steering handed back to the driver with a warning".

tdetect + treact ≤ FTTI
tdetect
fault detection time: from the fault until a monitor declares it
treact
fault reaction time: from the declaration until the safe state is reached or held
FTTI
the time from the fault to possible harm, if nothing reacts; set by the hazard and the vehicle

Where detection time comes from

Most detection is a timeout. A monitor expects a fresh message, or a check-in, at least every Tout. The monitor itself runs every Tcheck. Many monitors also want n failed checks in a row before they act, to ignore a one-off glitch. That is a debounce.

Take the worst case. The fault lands just after a good message. The timeout runs out just after a check, so the monitor sees it one check later. Then the debounce needs n more checks.

tdetect, worst = Tout + Tcheck + n · Tcheck
tdetect, worst
the longest the monitor can take to declare the fault
Tout
the timeout: the longest silence the monitor accepts
Tcheck
the period of the monitor task
n
the debounce: extra failed checks needed before the monitor acts

A worked budget

Here is a budget with typical, illustrative numbers. Say the hazard analysis gives an FTTI of 500 ms. The monitor runs every 10 ms, with a 100 ms timeout and a debounce of 2. The reaction is commanded on the next cycle, and the brake takes 150 ms to build pressure in the measured worst case.

tdetect = 100 + 10 + 2 × 10 = 130 ms  ·  treact = 10 + 150 = 160 ms

130 + 160 = 290 ms ≤ 500 ms  ·  margin 210 ms  ·  at 130 km/h (36.1 m/s): 36.1 × 0.29 = 10.5 m before the safe state

The margin matters. Every number in the budget is a model, and the real system has delays the model leaves out: a busy bus, a slow log write, a cold actuator. Teams usually keep a healthy share of the FTTI unspent.

Spend the time budget

The bar runs from the fault (left) to possible harm (the FTTI line). Detection is warm, reaction is yellow, and what is left is green margin. Shorten the FTTI or lengthen the timeout until the bar turns red.

500 ms
100 ms
10 ms
2
150 ms
130 km/h

Illustrative numbers. A real FTTI comes from the hazard analysis and vehicle tests; the actuator time is measured on the target hardware in its worst conditions.

Some teams write the budget into the code, so the build fails if a change breaks it. Every constant is a requirement with an owner.

// The time budget as code: if a change breaks the budget, the build fails.
// Every number is illustrative. A real programme takes the FTTI from its own
// hazard analysis and measures the other numbers on the target hardware.
#include <chrono>
using namespace std::chrono_literals;
using ms = std::chrono::milliseconds;

constexpr ms kFtti      = 500ms;        // fault to hazard, if nothing is done
constexpr ms kCheck     = 10ms;         // the monitor task runs every 10 ms
constexpr ms kTimeout   = 100ms;        // no fresh message for this long means a fault
constexpr int kDebounce = 2;            // two failed checks in a row before we act
constexpr ms kDecide    = kCheck;       // the reaction is commanded on the next cycle
constexpr ms kActuate   = 150ms;        // brake pressure builds (measured worst case)

// Worst case: the fault lands just after a good message, the timeout expires
// just after a check, and the debounce needs kDebounce more checks.
constexpr ms kDetectWorst = kTimeout + kCheck + kDebounce * kCheck;
constexpr ms kReactWorst  = kDecide + kActuate;
constexpr ms kMargin      = kFtti - (kDetectWorst + kReactWorst);

static_assert(kDetectWorst == 130ms && kReactWorst == 160ms, "the worked numbers");
static_assert(kDetectWorst + kReactWorst <= kFtti, "fault reaction misses the FTTI");
static_assert(kMargin >= 100ms, "keep margin for what the model leaves out");

When the budget lies

The usual failure mode: the budget used the average actuator time, measured on a warm bench. In the cold, the brake hydraulics are slower, and the worst case is twice the average. The budget said 290 ms; the vehicle took 440 ms. Diagnose it by measuring the full distribution of each delay on the target, in its worst conditions, and by budgeting the tail, never the mean.

A second failure mode hides in the timeout. Someone raises it from 100 ms to 300 ms to stop false alarms (Chapter 4 shows why that is tempting). Nobody updates the budget. The static assert above exists for exactly that day.

An interviewer asks: "Your monitor has a 100 ms timeout. A colleague wants 300 ms to cut false alarms. What do you check before you agree?"

Chapter 3

Fail-safe or fail-operational

Decide whether the system stops, degrades or carries on, and what each choice costs

A robot arm in a fenced cell loses its position sensor. The right move is easy: cut the motor power and close the brakes. Nobody is inside the fence. The arm stops, and the cell is safe.

Now take a car on the highway at 120 km/h, with a driving system that lets the driver read a book. Its steering computer fails. Cutting power to the steering is not safe at all. The car would drift, and the driver needs many seconds to look up, understand and take the wheel.

Those two cases split safety architecture in two. A system is fail-safe if a safe state exists that it can reach by stopping or switching off. The design only needs to detect the fault and pull the plug. A system is fail-operational if it must keep working, at least in part, for some time after a fault, until it reaches a safe state.

Between them sits fail-degraded: keep a reduced function. Drive on radar only at a lower speed, say, and ask the driver to take over. Inside all of these, one building block helps a lot. A part is fail-silent if, when it is faulty, it says nothing rather than something wrong. A silent part is easy to replace with a backup; a part that lies is not.

Stop, degrade or carry on

Pick a system and a strategy. The timeline starts at the fault. The grey bar is how long something must keep the system under control before it is safe. Green means the strategy covers it; red means a gap.

Illustrative times: the takeover times (4 s for a watching driver, 10 s for a reading one) are round numbers for the toy, not results from a study. Real programmes set them from their own human-factors work.

Why stopping can itself be dangerous

The hero's second architecture stops hard on every detected fault. Look at what the car behind does. You brake at 8 m/s² from 20 m/s. The car behind starts 30 m back, needs 1.0 s to react, and then brakes at 6 m/s².

you: 20² / (2 × 8) = 25 m  ·  behind: 20 × 1.0 + 20² / (2 × 6) = 20 + 33.3 = 53.3 m

gap at the end: 30 + 25 − 53.3 = 1.7 m

Nobody hit anybody, this time. But a slightly slower driver behind would have. A hard stop on a busy road trades one hazard for another. That is why highway systems prefer a gentle, planned stop, or a hand-over, when they can still see enough to do it.

What each strategy needs

A fail-safe design needs one working channel plus a monitor that can force the safe state. A fail-degraded design needs a second, simpler path that still works when the main one does not: in the hero, a radar-only path to the planner. A fail-operational design needs a full second channel, independent enough that one fault does not take both.

The backup only has to survive a short window: the time to reach the safe state. That makes the numbers kind. Suppose a backup channel fails about once in 10,000 hours (illustrative), and it must carry the car for 10 s after the main channel fails.

P(backup fails in the window) ≈ λb · Tneed
λb
the backup's failure rate, in failures per hour
Tneed
how long the backup must work: from the main fault to the safe state

10−4 per hour × 10 / 3600 h = 2.8 × 10−7  ·  at 33 m/s the car covers 333 m on the backup

The approximation holds because λT is tiny: the exact value is 1 − e−λT, which is λT to many digits here. But the number is only true if the two channels fail independently. Chapters 6 and 7 are about that "if".

Here is the choice as code. It is small on purpose: the hard work is in knowing which inputs are true.

// Choose the reaction to a detected fault. Switching off is only a reaction
// if "off" is safe. Otherwise something must keep working until it is.
enum class Reaction { Continue, SwitchOff, Degrade, MinimalRisk };

struct Situation {
  bool primaryFailed;   // the main channel is lost or untrusted
  bool offIsSafe;       // e.g. a robot arm in a fenced cell, a shuttle at walking pace
  bool backupHealthy;   // a second, independent channel still works
};

constexpr Reaction choose(const Situation& s) {
  if (!s.primaryFailed) return Reaction::Continue;   // a spare failed: log it, repair at the depot
  if (s.offIsSafe)      return Reaction::SwitchOff;  // FAIL-SAFE: de-energise, brake, done
  if (s.backupHealthy)  return Reaction::Degrade;    // FAIL-OPERATIONAL: drive on the backup,
                                                     // hand over or reach a stop
  return Reaction::MinimalRisk;                      // nothing left to lean on: stop as gently
                                                     // as the remaining parts allow
}

static_assert(choose({true, true, false})  == Reaction::SwitchOff,   "robot arm");
static_assert(choose({true, false, true})  == Reaction::Degrade,     "highway, radar still fine");
static_assert(choose({true, false, false}) == Reaction::MinimalRisk, "highway, nothing left");
static_assert(choose({false, false, true}) == Reaction::Continue,    "only the spare failed");

When the backup is not a backup

The failure mode that ruins fail-operational designs is a shared resource. Two steering computers that share one power supply are one computer when the supply fails. Two perception paths that read one calibration file are one path when the file is wrong. Diagnose it with a list: for every pair of "independent" channels, write down each thing they share, from power and clocks to network switches, software and sensors. Each line is a way both fail together.

An interviewer asks: "Why can't a hands-off highway pilot simply switch off when its main computer fails?"

Chapter 4

Detecting that something is wrong

Build the checks that notice silence, hangs, impossible values and frozen data

A test vehicle's front camera sends the same image for 40 seconds. Its message counter keeps going up. Its timestamps look fresh. Nothing crashed, and no log shows an error. The image pipeline inside the camera got stuck, and it kept sending its last frame.

That is the hard kind of fault. A crash is loud. A stuck part looks alive. So a safety architecture has many small checks, each looking for one kind of wrongness. Here they are, from the bluntest to the subtlest.

CheckCatchesMisses
Heartbeat, timeouta dead process, an unplugged sensor, a cut cablea live process that sends wrong or stale data
Watchdoga hang, an endless loop, a starved taska task that runs on time and computes nonsense
Windowed watchdogalso a loop that runs too fast and skips its workwrong results computed at the right pace
Range, rateimpossible values, jumps, sign errorswrong values that look possible
Stuck-at, frozen framea sensor or stage that repeats itselfa scene that really is still, if tuned too tight

A watchdog from scratch

Here is a software watchdog. Each task registers a window: it must check in no sooner than minGap and no later than maxGap after its last check-in. It also passes a progress counter, so "checked in, but did no work" is caught. A separate, higher-priority task calls check() on a fixed period.

// A software watchdog: each supervised task must check in inside a time window.
// Too late means hung or starved. Too early means a loop is skipping its work.
#include <array>
#include <chrono>
#include <cstdint>

using Clock = std::chrono::steady_clock;    // monotonic: never jumps when wall time changes

class Watchdog {
 public:
  static constexpr int kMaxTasks = 8;       // fixed size: no allocation after start-up
  int add(Clock::duration minGap, Clock::duration maxGap, Clock::time_point now) {
    if (n_ == kMaxTasks) return -1;
    tasks_[n_] = Task{minGap, maxGap, now, 0, true};
    return n_++;
  }
  // The task calls this at the END of a real work cycle, with its progress counter.
  // A timer thread that kicks "for" a task would keep kicking through a hang.
  bool kick(int id, std::uint32_t seq, Clock::time_point now) {
    Task& t = tasks_[id];
    const bool early = now - t.last < t.minGap;   // windowed: a runaway loop kicks too fast
    const bool stuck = seq == t.lastSeq;          // checked in, but did no new work
    t.last = now;
    t.lastSeq = seq;
    if (early || stuck) t.ok = false;             // latched: a safety fault stays set
    return t.ok;
  }
  // An independent, higher-priority context calls this every check period.
  // Returns the first failed task, or -1 if every task is healthy.
  int check(Clock::time_point now) const {
    for (int i = 0; i < n_; ++i)
      if (!tasks_[i].ok || now - tasks_[i].last > tasks_[i].maxGap) return i;
    return -1;
  }

 private:
  struct Task { Clock::duration minGap, maxGap; Clock::time_point last; std::uint32_t lastSeq; bool ok; };
  std::array<Task, kMaxTasks> tasks_{};
  int n_ = 0;
};

Three design choices are worth saying out loud in an interview. The clock is monotonic: it never jumps when someone sets the wall clock, so a time sync cannot fake a hang. The storage is fixed: no memory is allocated after start-up. And a failure is latched: once a task fails, it stays failed until a deliberate reset. A fault that "healed itself" still needs a look.

The timeout trade

Now the hard part: choosing the timeout. Messages do not arrive exactly every 100 ms. They wobble by a few milliseconds. Once in a long while, the link stalls, because a bus is busy or a process is pre-empted, and then it catches up. A short timeout catches real faults fast but also fires on stalls. A long timeout is quiet but slow.

Tune the timeout

The histogram counts one hour of gaps between messages (log scale). Everything right of the warm line is a false alarm. The curve below shows false alarms per hour for every timeout. Move the timeout and the jitter.

300 ms
8 ms
1

Toy link: a 100 ms period, Gaussian jitter, and rare stalls that add 0 to 400 ms (uniform). One hour is 36,000 gaps. The model and its numbers are illustrative.

The device's curve comes from one line. A false alarm is a gap longer than the timeout. There are 36,000 gaps in an hour at 10 Hz.

FA = 36,000 × [ (1 − ps) · Q((Tout − 100) / σ) + ps · (500 − Tout) / 400 ]
FA
false alarms per hour of driving
ps
the chance that a gap is a stall
Tout
the timeout, in ms (the stall term holds between 100 and 500 ms)
σ
the normal jitter of a gap, in ms; Q is the chance a standard normal value exceeds its argument

Tout = 300: 36,000 × 10−4 × 200 / 400 = 1.8 per hour  ·  450 ms: 0.45  ·  120 ms (z = 2.5, Q = 0.0062): ≈ 227

Look at that 1.8 per hour. If every false alarm stops the vehicle hard, it stops twice an hour for nothing. No product survives that. So there are three honest fixes. Remove the stalls at the source, which is often a scheduling or network fix. Debounce, if the time budget allows. Or make the reaction proportionate: a lost input first triggers a degraded mode, not an emergency stop.

And the worst-case detection time is still Tout plus one monitor period: 310 ms at the default. Chapter 2's budget decides whether that is allowed.

When the watchdog never fires

The classic bug: someone kicks the watchdog from a timer thread, "to keep it happy during long computations". Then the main loop hangs, and the timer thread keeps kicking. The watchdog is healthy and the system is dead. Diagnose it by injecting a hang into the main loop (an endless loop behind a test flag) and checking that the watchdog fires. Fix it by kicking only at the end of real work, with a progress counter, as in the code above.

An interviewer asks: "Your watchdog is kicked by a 50 ms timer thread. What is wrong with that?"

Chapter 5

Trusting a message

Protect each message so the receiver can tell corrupt, lost, repeated and late data

The radar measures the truck ahead at 25.00 m. It sends the number in centimetres, 2500, as two bytes. Somewhere between the radar's software and the planner's software, one bit flips. The planner receives 6596: the truck is now 65.96 m away. The planner sees no reason to brake.

The bit could flip on a noisy cable, in a gateway's buffer, or in a memory chip. It does not matter where. What matters is that the receiver can tell. A message can go wrong in five basic ways.

End-to-end protection answers all five. The sender's software adds a few fields to each message, and the receiver's software checks them. "End to end" means from the software that makes the data to the software that uses it, across every cable, switch and buffer between.

Field the sender addsThe receiver checksCatches
A CRC over the whole messagerecompute it and comparecorruption
A sequence counter, +1 per messageit moved by exactly 1loss, repetition, reordering
A timestamp from a synchronised clockits age is under a limitdelay, stale data
A data ID, often folded into the CRCit matches the signal expectedmisrouting, a valid message from the wrong place

What a CRC is

A CRC (cyclic redundancy check) treats the message bytes as one long binary number and divides it by a fixed binary number, the polynomial. The remainder of that division is the CRC. Change any bit of the message and the remainder changes in a way that is easy to compute and hard to fake by accident.

For a well-chosen 8-bit CRC, the guarantees are concrete. It catches every single-bit error. It catches every burst of errors up to 8 bits long. A message turned into random garbage still passes by chance, with probability about 1 in 256. Wider CRCs, such as 16 or 32 bits, push that chance far lower.

One tiny message, worked by hand

Here is a 7-byte message: data ID 0x12, counter 7, range 2500 cm (0x09C4), timestamp 1000 ms (0x03E8), and the CRC-8 with polynomial 0x07 over those six bytes.

sent: 12 07 09 C4 03 E8 | CC range 0x09C4 = 2500 cm = 25.00 m received: 12 07 19 C4 03 E8 | CC range 0x19C4 = 6596 cm = 65.96 m receiver: CRC of the first six bytes = AB, not CC → reject counters: 06, 07, 07 → repeated: no new data 07, 09 → one message lost age: stamp 1000 ms, received at 1410 ms → 410 ms > 200 ms limit → stale

One flipped bit, in the high byte of the range, moved the truck by almost 41 m. The CRC turned it into a rejected message instead of a missed brake. The order of the checks matters: the CRC goes first, because no other field is trustworthy until it passes.

Tamper with the messages

The sender sends one message every cycle. Pick a fault and press Tamper: it hits the next message. Switch checks off to see which bad messages slip through to the planner.

Toy stream at a 100 ms cycle, slowed down so you can watch it. The CRC is the real CRC-8 (polynomial 0x07) from the code below, computed on each message in your browser. The age limit is 200 ms.

// End-to-end protection for one small message, from sender software to receiver software.
// Frame: [dataId, counter, range hi, range lo, stamp hi, stamp lo, crc]
#include <array>
#include <cstddef>
#include <cstdint>

using Frame = std::array<std::uint8_t, 7>;
enum class E2E { Ok, BadCrc, WrongId, Repeated, OutOfOrder, Stale, Lost };

std::uint8_t crc8(const std::uint8_t* p, std::size_t n) {   // CRC-8, polynomial 0x07
  std::uint8_t c = 0;
  for (std::size_t i = 0; i < n; ++i) {
    c ^= p[i];
    for (int b = 0; b < 8; ++b) c = (c & 0x80) ? std::uint8_t((c << 1) ^ 0x07) : std::uint8_t(c << 1);
  }
  return c;
}

Frame protect(std::uint8_t id, std::uint8_t ctr, std::uint16_t range_cm, std::uint16_t stamp_ms) {
  Frame f{id, ctr, std::uint8_t(range_cm >> 8), std::uint8_t(range_cm & 0xFF),
          std::uint8_t(stamp_ms >> 8), std::uint8_t(stamp_ms & 0xFF), 0};
  f[6] = crc8(f.data(), 6);                                 // the CRC covers every byte before it
  return f;
}

struct RxState { std::uint8_t lastCtr = 0; bool first = true; };

E2E check(const Frame& f, std::uint8_t wantId, RxState& s, std::uint16_t now_ms, std::uint16_t maxAge_ms) {
  if (crc8(f.data(), 6) != f[6]) return E2E::BadCrc;       // first: no other field is trustworthy yet
  if (f[0] != wantId) return E2E::WrongId;                  // a valid message, from the wrong sender
  const std::uint8_t step = std::uint8_t(f[1] - s.lastCtr); // unsigned maths wraps 255 -> 0 correctly
  const bool first = s.first;
  if (!first && step == 0) return E2E::Repeated;            // same data again: a frozen sender or a replay
  if (!first && std::int8_t(step) < 0) return E2E::OutOfOrder;  // went backwards: an old message arrived late
  s.first = false;
  s.lastCtr = f[1];
  const std::uint16_t stamp = std::uint16_t(f[4] << 8 | f[5]);
  if (std::uint16_t(now_ms - stamp) > maxAge_ms) return E2E::Stale;  // needs synchronised clocks
  if (!first && step > 1) return E2E::Lost;                 // fresh and valid, but step - 1 went missing
  return E2E::Ok;
}

Note the unsigned arithmetic. The counter is one byte, so after 255 comes 0. In unsigned maths, 0 − 255 is 1, so the step is still 1 and the wrap is not a false "lost". A late message that arrives after newer ones gives a step that is "negative"; read as a signed byte, it is caught as out of order. The same unsigned trick handles the 16-bit timestamp, which wraps every 65.5 s.

When the protection protects the wrong thing

A real failure mode: the sender computes the CRC on a buffer that is already wrong. A memory overwrite changed the range before protect() ran. The CRC then faithfully protects the wrong number all the way to the planner. End-to-end protection covers only the path after protect(). Diagnose by asking where protect() runs, and move it as close to the producer as you can. Range and rate checks on the receiver catch some of what is left.

A second one: the timestamp check fires all the time after a software update. The cause is not the network. The two computers' clocks drifted apart because the update disabled time synchronisation. A timestamp check is only as good as the clock sync, so monitor the sync too.

An interviewer asks: "Perception froze, but its old output keeps arriving on time with a valid CRC. Which end-to-end field catches it?"

Chapter 6

Redundancy and voting

Use several channels to outvote one bad one, and see when copies fail together

Three sensors measure the gap to the truck ahead. The radar says 25.1 m. The camera says 24.9 m. The lidar says 80.0 m, because its beam went under the truck's raised trailer and hit a sign far beyond. Which number should the brakes believe?

Two of the three agree, so believe them. That is two-out-of-three voting (2oo3): with three channels, any one can be wrong and the majority still wins. For a measured value, the simplest voter is the median: sort the three values and take the middle one. One wild value, high or low, can never be the middle.

Redundancy has a vocabulary. A channel is one complete path from sensing to result. Redundancy means more than one channel for the same job. Diversity means the channels differ in how they do it: radar, camera and lidar use different physics; two teams write two programs; two chips come from two makers.

Outvote the bad channel

Three channels measure a closing gap; the warm line is the voter's output and the dashed line is the truth. Inject a fault. Then try the common-cause fault, where one cause hits two channels the same way.

1.0 m
10%

Toy: a gap closing from 60 m at 4 m/s, sensor noise of 0.15 m to 0.3 m, the fault starting at 2 s. With the voter off, the brakes use the radar alone. The odds line uses an illustrative per-hour failure chance of 10−3 per channel.

The odds, and the catch

If each channel fails with probability p, and the channels fail independently, the voter fails only when at least two fail. There are three ways to pick two, and one way for all three.

P2oo3 = 3p2(1 − p) + p3 = 3p2 − 2p3
P2oo3
the chance that the voted result is wrong
p
the chance that one channel fails, in the same time window

p = 10−3: 3 × 10−6 − 2 × 10−9 = 3.0 × 10−6, about 333 times better than one channel

That is the promise. Now the catch. Some causes hit several channels at once: one power supply, one sun low on the horizon, one calibration file, one bug in a shared library. That is a common-cause failure. A simple model, the beta factor, says a share β of each channel's failures are common to all channels.

P ≈ βp + 3((1 − β)p)2
P
the chance the voted result is wrong, with common causes
β
the share of failures that hit all channels together

β = 0.1, p = 10−3: 10−4 + 3 × (9 × 10−4)2 = 1.0 × 10−4 + 2.4 × 10−6 = 1.02 × 10−4

The common-cause term is 40 times bigger than the independent one. The voter now buys a factor of 10 instead of 333. That is why diversity matters more than the number of copies. Two copies of the same program, fed the same input, compute the same wrong answer at the same moment. Their β for software bugs is 1.

Here is the voter. It also handles the case where one channel is already known bad: with two left, they must agree, or the voter reports a fault.

// Two-out-of-three voting on one measured value, e.g. the gap to the vehicle
// ahead from radar, camera and lidar. The median ignores any ONE wild channel.
#include <algorithm>
#include <array>
#include <cmath>

struct Vote { double value; bool ok; int outvoted; };   // outvoted: a channel index, or -1

Vote vote2oo3(const std::array<double, 3>& x, const std::array<bool, 3>& valid, double tol) {
  std::array<double, 3> v{};
  std::array<int, 3> who{};
  int n = 0;
  for (int i = 0; i < 3; ++i)
    if (valid[i] && std::isfinite(x[i])) { v[n] = x[i]; who[n] = i; ++n; }
  if (n < 2) return {0.0, false, -1};                   // no majority possible: report a fault
  if (n == 2)                                           // two left: they must agree, or we stop trusting
    return std::fabs(v[0] - v[1]) <= tol ? Vote{(v[0] + v[1]) / 2, true, -1} : Vote{0.0, false, -1};
  std::array<double, 3> s = v;
  std::sort(s.begin(), s.end());
  const double med = s[1];                              // the middle value
  int agree = 0, out = -1;
  for (int i = 0; i < 3; ++i) {
    if (std::fabs(v[i] - med) <= tol) ++agree;
    else out = who[i];
  }
  if (agree < 2) return {med, false, -1};               // all three disagree: no majority
  return {med, true, out};                              // the median sits inside the agreeing pair
}

When voting goes wrong

Tune the tolerance in the device and watch two failure modes. Too tight, and normal noise makes the channels "disagree" all the time, so the voter keeps flagging healthy sensors. Too loose, and a slowly drifting channel stays inside the band until it is badly wrong. Diagnose with logs of every disagreement, per channel pair, against speed, range and weather. Real sensors also disagree for honest reasons, such as different mounting positions or latencies, so align them in space and time before you vote.

And remember the voter itself. It is now a single point of failure, and it must be simple enough to trust, and protected like everything else.

An interviewer asks: "We run the same perception binary on two identical computers and compare outputs. What does that protect against, and what does it miss?"

Chapter 7

Keeping parts from hurting each other

Separate memory, time and messages so a small bug cannot reach the safety code

A logging process has a bug. It writes one element past the end of its buffer. On this computer every task shares one memory space, and the next bytes happen to belong to the brake monitor. The monitor's "too close" limit changes from 2.0 m to a garbage value. Nobody notices until the monitor fails to act.

Another week, the same logger gets stuck in a busy loop. Someone gave it a higher priority than the monitor, "so logs are never lost". Now the monitor never gets the processor. It is correct, and it never runs.

Neither bug is in the safety code. Both break it. The cure is freedom from interference: a guarantee that a less critical part cannot cause a more critical part to fail. It has three sides.

One strong way to get time separation is partitioning. The operating system splits time into a repeating frame, say 10 ms, and gives each partition fixed slots in it. A partition can never run outside its slots, even if its code loops forever. Parts at different integrity levels can then share one computer. Without that proof, everything on the computer must be built to the highest level present.

Starve the safety task

One processor runs three tasks for 100 ms. Each warm tick is a monitor deadline. Break the logger, then switch on the protection that stops it.

Toy schedule on one core: the monitor needs 2 ms every 10 ms, perception 25 ms every 50 ms, the logger 5 ms every 100 ms. The fault starts at 30 ms. The partitions give 2, 6 and 2 ms of every 10 ms frame. Illustrative numbers.

Check the healthy load first. The share of the processor each task needs is its run time over its period.

U = 2/10 + 25/50 + 5/100 = 0.20 + 0.50 + 0.05 = 0.75

So there is room, and a correct priority order meets every deadline. But "correct priority order" is a promise that one configuration line can break. Partitions turn the promise into a mechanism: in each 10 ms frame the monitor owns 2 ms, perception 6 ms (30 ms per 50 ms, more than its 25), and the logger 2 ms.

Why the monitor must be simpler than what it monitors

A planner is large. It weighs lanes, objects, comfort and rules, and it is too complex to prove correct. So the safety argument does not rest on it. It rests on a small checker beside it: the planner is the doer, and the checker only asks whether each command is acceptable. This doer and checker split is old and strong. In robotics it is often called the Simplex architecture: a complex controller runs while a simple, verified one stands ready to take over.

Simplicity buys three things. The checker is small enough to review line by line and test to a much deeper level. It fails in different ways from the doer, so their faults are less likely to coincide. And it can run with fewer dependencies: its own process, ideally its own core or chip, and its own inputs, such as the raw radar range instead of the planner's object list.

// A checker much simpler than the planner it watches. It does not re-plan.
// It asks two questions: is the command physically sane, and does it agree
// with the one fact the checker trusts, the radar's gap to the vehicle ahead?
#include <algorithm>
#include <cmath>

struct Command  { double accel_mps2; double steerRate_dps; };
struct Envelope { double maxBrake = -9.0, maxAccel = 3.0, maxSteerRate = 30.0, minTimeGap_s = 1.0; };
enum class Verdict { Pass, Clamped, Rejected };

struct CheckIn { Command cmd; double speed_mps; double radarGap_m; bool radarValid; };

Verdict check(const CheckIn& in, const Envelope& e, Command& out) {
  out = in.cmd;
  if (!std::isfinite(in.cmd.accel_mps2) || !std::isfinite(in.cmd.steerRate_dps)) {
    out = {0.0, 0.0};                                  // garbage in: hold speed, hold the wheel
    return Verdict::Rejected;
  }
  // Rule 1: never accelerate into a short time gap that the radar can see.
  if (in.radarValid && in.speed_mps > 0.5 && in.cmd.accel_mps2 > 0.0 &&
      in.radarGap_m / in.speed_mps < e.minTimeGap_s) {
    out.accel_mps2 = 0.0;
    return Verdict::Rejected;
  }
  // Rule 2: stay inside what the vehicle can physically do.
  out.accel_mps2    = std::clamp(in.cmd.accel_mps2, e.maxBrake, e.maxAccel);
  out.steerRate_dps = std::clamp(in.cmd.steerRate_dps, -e.maxSteerRate, e.maxSteerRate);
  const bool changed = out.accel_mps2 != in.cmd.accel_mps2 || out.steerRate_dps != in.cmd.steerRate_dps;
  return changed ? Verdict::Clamped : Verdict::Pass;
}

Notice what the checker does not do. It does not know about lanes, comfort or traffic rules. It knows two physical facts and one trusted input. That is why a reviewer can believe it.

When separation is only on paper

The usual failure mode: the checker runs in the planner's own process, "to save a context switch". It shares the planner's memory, its thread and its crash. A null pointer in the planner kills both, and the vehicle loses its doer and its checker in the same microsecond. Diagnose with the shared-resource list from Chapter 3: process, address space, thread, core, clock, power, inputs. Each shared line is an argument a reviewer will reject.

A subtler one: the checker reads the same object list that the planner reads. If perception produces a ghost or misses a pedestrian, both are wrong together. Independent inputs matter as much as independent code.

An interviewer asks: "A low-priority logger and the safety monitor share one processor. What must you show before you call that safe?"

Chapter 8

Degraded modes as a state machine

Write the system's modes and the rules between them so it never chatters or gets lost

A car leaves a tunnel into a low sun. For two seconds the camera sees only white, and its health check fails. Then the sun moves behind a building, and the camera recovers. Should the system jump back to normal the moment the camera looks healthy?

Now take a loose connector that makes the camera fail and recover every 200 ms. If the system follows each change, it switches modes five times a second. The speed cap comes and goes, the dashboard flashes, and the driver cannot tell what the car will do. That is chatter, and it is a hazard of its own.

The cure is to write the modes down as an explicit state machine: a fixed list of modes, and named rules for moving between them. A typical driving system has four.

Two rules make it robust. First, hysteresis: leaving a mode is harder than entering it. One failed check enters Degraded; returning to Nominal needs the inputs healthy for, say, 1 s in a row. Second, some transitions are one way. Once the manoeuvre has started, the system does not decide by itself that all is well again. A driver or a deliberate restart ends it.

Drive the mode manager

Pick a fault pattern and press Play. The lanes show camera and radar health over 18 s; the band shows the mode the machine chose, and the line shows speed. Change the hysteresis and count the mode changes.

0.0 s
8.0 s

The machine is the C++ below, ported line for line, run at a 10 ms cycle. Speeds and decelerations are illustrative: The run starts at 100 km/h; Degraded slows to 60 km/h at 2 m/s², and the manoeuvre stops at 3 m/s².

Work the flicker by hand. The camera is healthy for 200 ms, then failed for 200 ms, for 6 s. That is 30 changes of camera health. With no hysteresis, each failure enters Degraded and each recovery returns at once.

no hysteresis: about 30 mode changes in 6 s  ·  1 s hysteresis: the camera is never healthy for 100 cycles in a row → 1 change

Both numbers come from running the C++ below with a 10 ms cycle; the test that starts with a healthy camera counts 29. With hysteresis, the system enters Degraded once and stays there, which is the right answer for a loose connector. If the camera then never settles, the time limit on Degraded moves the car into the minimal-risk manoeuvre.

// Degraded modes as an explicit state machine. Every transition has a named
// condition, recovery needs the inputs healthy for a while (hysteresis), and
// the minimal-risk manoeuvre is one way: it never returns to nominal by itself.
#include <cstdint>

enum class Mode : std::uint8_t { Nominal, Degraded, MinimalRisk, SafeStop };
struct Health { bool camOk; bool radarOk; double speed_mps; };

class ModeManager {
 public:
  ModeManager(int recoverCycles, int maxDegradedCycles)
      : recoverCycles_(recoverCycles), maxDegradedCycles_(maxDegradedCycles) {}

  Mode step(const Health& h) {                       // called once per cycle, e.g. every 10 ms
    const bool allOk = h.camOk && h.radarOk, anyOk = h.camOk || h.radarOk;
    goodStreak_ = allOk ? goodStreak_ + 1 : 0;       // consecutive fully healthy cycles
    switch (mode_) {
      case Mode::Nominal:
        if (!anyOk)      mode_ = Mode::MinimalRisk;  // both lost: no time to degrade
        else if (!allOk) { mode_ = Mode::Degraded; degradedCycles_ = 0; }
        break;
      case Mode::Degraded:                           // reduced function: speed cap, takeover request
        if (!anyOk)                                    mode_ = Mode::MinimalRisk;
        else if (++degradedCycles_ > maxDegradedCycles_) mode_ = Mode::MinimalRisk;  // no recovery in time
        else if (allOk && goodStreak_ >= recoverCycles_) mode_ = Mode::Nominal;    // hysteresis
        break;
      case Mode::MinimalRisk:                        // controlled stop in lane, hazard lights on
        if (h.speed_mps < 0.1) mode_ = Mode::SafeStop;
        break;
      case Mode::SafeStop:                           // latched until a deliberate restart
        break;
    }
    return mode_;
  }
  Mode mode() const { return mode_; }

 private:
  Mode mode_ = Mode::Nominal;
  int goodStreak_ = 0, degradedCycles_ = 0;
  const int recoverCycles_, maxDegradedCycles_;
};

Every mode change is a named line of code, and each one is a test. That is the point of writing modes as a state machine rather than as flags scattered through the planner.

When the machine gets lost

The failure mode of hand-written mode logic is the missing case. A team tests "camera fails" and "radar fails", but never "radar fails while already Degraded because of the camera". In the flag version, the code stays Degraded with no working sensor at all. Diagnose it by writing the full table of modes against events, with an entry in every cell, and a test for every cell. The switch statement above has an answer for each mode and each health combination by construction.

An interviewer asks: "Your degraded mode keeps toggling on and off on one vehicle. What is the likely design gap, and the fix?"

Chapter 9

Arguing that it is safe

Link every requirement to evidence, and speak about the standards a lead must know

A reviewer reads your design for one minute and asks: "How do you know the watchdog fires within 210 ms on the real target?" "I wrote it carefully" is not an answer. "There is a test" is half an answer. The full answer names the requirement, the test, the version it ran on and the measured result.

Safety is not shown by one test or one review. It is shown by an argument that a reader can check, backed by evidence for each step. Three tools make that possible.

Traceability

Traceability links each requirement up to its reason and down to its proof. A safety goal links to the requirements that refine it. Each requirement links to the design and code that meet it, and to the tests that verify it. A reviewer walks the links both ways: every requirement needs evidence, and every piece of safety code needs a requirement. Code with no requirement is a question: why is it there?

Follow the evidence

Tap any box to light its chain up and down. Then break something a real project breaks: delete a test, or change a number in the code without touching its requirement.

A toy trace for one safety goal. Real projects hold thousands of links in a requirements tool, and check them automatically.

The safety case

A safety case is a structured argument that a system is acceptably safe for a given use in a given environment. It is built from three kinds of pieces. A claim says something should be true: "Perception hangs are detected within 210 ms." An argument says why the evidence supports it: "the watchdog's window is 200 ms and its check runs every 10 ms, shown by analysis and by test." Evidence is the artefact: the test report, the timing measurement, the review record.

Claims break into sub-claims until each one rests on evidence. Many teams draw this as a tree in the Goal Structuring Notation (GSN), but the notation matters less than the honesty. A good safety case also names its assumptions ("the driver can take over within 4 s") and its limits ("not validated for snow").

Fault injection as evidence

Chapter 0 showed that faults are too rare to wait for. So you cause them. Fault injection forces each fault on purpose, at several levels: in unit tests with a fake clock, in software on the real computer with test hooks, on a hardware-in-the-loop rig that feeds the real computer simulated sensors, and finally in the vehicle. Each injection measures the detection time and the reaction against the budget.

// Evidence, as code: inject a hang and prove the watchdog fires inside budget.
// A fake clock makes the test exact and repeatable on any machine.
#include <cassert>
#include <cstdio>
#include "c4_watchdog.hpp"
using namespace std::chrono_literals;

int main() {
  Clock::time_point t{};                          // fake time: we move it by hand
  Watchdog wd;
  const int perc = wd.add(50ms, 200ms, t);        // perception must check in every 50..200 ms
  std::uint32_t seq = 0;
  for (int i = 0; i < 10; ++i) {                  // one second of healthy 100 ms cycles
    t += 100ms;
    assert(wd.kick(perc, ++seq, t));
    assert(wd.check(t) == -1);                    // no false alarm while healthy
  }
  const Clock::time_point hangAt = t;             // INJECT: hang right after a kick (worst case)
  Clock::time_point firedAt{};
  for (int step = 0; step < 100 && firedAt == Clock::time_point{}; ++step) {
    t += 10ms;                                    // the monitor runs every 10 ms
    if (wd.check(t) == perc) firedAt = t;
  }
  assert(firedAt != Clock::time_point{});         // it fired at all
  const auto detect = std::chrono::duration_cast<std::chrono::milliseconds>(firedAt - hangAt);
  assert(detect <= 210ms);                        // maxGap + one check period: the budget
  std::printf("hang detected after %lld ms\n", static_cast<long long>(detect.count()));  // 210

  Watchdog w2;                                    // INJECT: kicks with no progress (stuck loop)
  Clock::time_point u{};
  const int id = w2.add(50ms, 200ms, u);
  u += 100ms; assert(w2.kick(id, 1, u));
  u += 100ms; assert(!w2.kick(id, 1, u));         // same counter: caught at once
  assert(w2.check(u) == id);
  return 0;
}

That test is evidence because it is exact (a fake clock), repeatable (no timing luck), and aimed at the worst case (the hang lands right after a kick). The measured 210 ms is the watchdog's 200 ms window plus one 10 ms check. The same test on the target, with the real clock and the real scheduler, closes the gap between the model and the hardware.

What reviewers ask

The standards, at the level a lead must speak

A lead does not need clause numbers in an interview. A lead does need to know what each standard is for, and how they differ. A real programme follows each standard's own text, guided by its safety engineers and assessors.

StandardWhat it is for
IEC 61508The general functional safety standard for electrical, electronic and programmable systems. Several sector standards grew from it. Integrity levels SIL 1 to 4.
ISO 26262Functional safety of electrical and electronic systems in road vehicles. Hazards caused by malfunctions: faults in hardware or software. A full life cycle from concept to decommissioning, and ASIL A to D.
ISO 21448 (SOTIF)Safety of the intended functionality. Hazards with no fault: the function works as designed, but the design is not good enough for a situation, or a user foreseeably misuses it.
DO-178CSoftware in airborne systems. Software levels A to E by the effect of a failure, with objectives for planning, requirements, design, code, verification and configuration.

They share a handful of ideas, and a lead should name them: start from hazards; scale the rigour with the risk; trace requirements to evidence; verify independently; control configuration, so the evidence belongs to the software that ships. Coding rule sets such as MISRA C++ and AUTOSAR C++14 sit inside that picture, as one kind of evidence about the code.

Malfunction or insufficiency?

This distinction comes up in almost every interview for this kind of role. A malfunction is a fault: something does not do what it was designed to do. A watchdog catches a hung process; that is ISO 26262 territory. An insufficiency of the intended function has no fault at all. The perception model runs perfectly, as trained, and still misses a pedestrian in fog, because the design is not good enough there. That is SOTIF territory.

EventKindTypical answer
Perception process hangsmalfunctionwatchdog, degraded mode
A bit flips in the range messagemalfunctionend-to-end CRC
Camera connector works loosemalfunctiontimeout, frozen-frame check
The model misses a pedestrian in foginsufficiencyknow the limits, monitor conditions, restrict where the function runs
Radar sees a ghost under a metal bridgeinsufficiencycross-sensor checks, scenario testing
Driver trusts a hands-on system too muchforeseeable misusedriver monitoring, clear HMI

A safety architecture needs both. The mechanisms in this lesson mostly answer malfunctions. Runtime monitors on the learned models answer many insufficiencies, and they are the subject of the runtime monitors lesson.

When the evidence is not evidence

The classic failure mode: the fault-injection report is real, but it ran on last month's build. Since then the timeout changed. The evidence describes software that no longer ships. Diagnose it by tying every piece of evidence to an exact version hash, and by re-running the safety tests on every release candidate. A second one: the injection test passes because the injected fault never reached the code path, a test flag spelled wrong. Check that the fault-handling code was actually executed, with coverage of that path.

An interviewer asks: "Our perception model, working exactly as trained, misses pedestrians in heavy fog. Is that a functional safety malfunction?"

Chapter 10

The fault bench

Run every fault against every mechanism, hundreds of times, and try to break it

Here is the hero's system again, with every mechanism from this lesson as a switch and every timing number as a knob. Run one fault and watch it. Then run 200 random trials: each picks a fault, a moment within the cycle and a draw of network jitter. The panel reports what a safety review would ask for.

The fault bench

Switch mechanisms on and off, pick a fault (or random), and set the timing. Run one animates a single fault. Run 200 trials fills the results and the detection-time chart.

300 ms
200 ms
2
low
500 ms
 faults detected
 handled inside the FTTI
 detection time, mean / max
 carry on / stop hard / degrade
 false alarms per hour
 caught first by

Toy model, the same as the hero: 100 ms cycles, a 200 ms age limit for timestamps, a 400 ms delay fault, 100 ms to start the reaction. A fault counts as handled inside the FTTI when detection plus 100 ms fits. False alarms come from one simulated fault-free hour with the same jitter. Seeded, so the same settings give the same results.

Experiments worth running

  1. The silent killer. Watchdog off, timeouts on, fault Freeze. Detection falls to zero, because the frozen process keeps sending its last output on time. Switch on the counter, or the watchdog, and it comes back.
  2. The garbled message. Default switches, fault Corrupt. Neither the watchdog nor the timeouts notice. Only the CRC does.
  3. The false alarm trade. Jitter high, timeout 150 ms. Detection is fast and false alarms climb past one a minute. Raise the timeout and the watchdog window together until false alarms fall, and watch the FTTI column fall with them.
  4. Stop or degrade. Compare the outcome column with the degraded mode off and on. The detection numbers do not change; what the vehicle does after detection does.
  5. Debounce. Switch on the CRC, fault Corrupt, and raise the debounce from 2 to 3. The CRC now waits for one more bad message: 100 ms more. At 4, the timeout fires first, because rejected messages never count as fresh. The checks back each other up.

The unplug case can be worked by hand. Messages come every 100 ms, so the last good message arrived between 0 and 100 ms before the fault. The timeout fires 300 ms after that message, at the next 10 ms check.

earliest: 300 − 100 = 200 ms after the fault  ·  latest: 300 + 10 = 310 ms  ·  spread evenly between them

The bench's chart shows that flat spread. Its mean sits near 255 ms. Detection time is not one number: it is a distribution, and the budget must hold for its worst case.

Here is one cycle of the bench's monitor as C++, built from the pieces of Chapters 4, 5 and 8.

// One cycle of the safety monitor, in the order the bench runs it.
// It holds no driving logic. It gathers evidence and picks a mode.
#include "c4_watchdog.hpp"
#include "c5_e2e.cpp"
#include "c8_modes.cpp"

struct LinkMonitor { Clock::time_point lastGood{}; int badRun = 0; RxState rx; };

class SafetyMonitor {
 public:
  SafetyMonitor(Clock::duration timeout, int debounce)
      : timeout_(timeout), debounce_(debounce), modes_(100, 1000) {}

  // One input link: did a good frame arrive, and is the link still healthy?
  bool assess(LinkMonitor& m, const Frame* f, std::uint8_t id, Clock::time_point now) {
    if (f) {                                             // a frame arrived this cycle
      const auto t = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
      const E2E r = check(*f, id, m.rx, std::uint16_t(t.count()), 200);
      if (r == E2E::Ok || r == E2E::Lost) { m.lastGood = now; m.badRun = 0; }  // Lost: this frame is fine
      else ++m.badRun;                                   // corrupt, repeated, stale, wrong sender
    }
    const bool timedOut = now - m.lastGood > timeout_;  // silence is a fault too
    return !timedOut && m.badRun < debounce_;            // one bad frame is tolerated, a run is not
  }

  Mode cycle(const Frame* cam, const Frame* radar, const Watchdog& wd,
             double speed_mps, Clock::time_point now) {
    const bool procOk = wd.check(now) < 0;               // perception and planner checked in on time
    const bool camOk  = assess(cam_, cam, 0x11, now) && procOk;   // the camera path runs through perception
    const bool radOk  = assess(rad_, radar, 0x12, now);  // the radar has a direct fallback path
    return modes_.step({camOk, radOk, speed_mps});
  }

 private:
  Clock::duration timeout_;
  int debounce_;
  LinkMonitor cam_, rad_;
  ModeManager modes_;
};
An interviewer asks: "With only timeouts, your bench never detects a frozen perception process. Why, and what fixes it?"

Chapter 11

Interview arsenal

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

Here is the lesson in one paragraph. Parts fail, and across a fleet even rare faults happen daily. Hazard analysis rates each hazard and sets the rigour; safety goals turn into numbers. The FTTI is the time from fault to harm; detection plus reaction must fit inside it, worst case, with margin.

Where "off" is safe, the design is fail-safe; where it is not, it must stay operational on an independent backup. Heartbeats, watchdogs, timeouts and value checks find dead, hung and wild parts. End-to-end CRCs, counters and timestamps find corrupt, lost, repeated and late messages. Voting outvotes one bad channel, unless a common cause hits several. Separation keeps small bugs out of the safety code, and the checker stays simpler than the doer. Modes live in a state machine with hysteresis. Traceability and fault injection turn all of it into an argument.

Coverage matrix

Rows are faults, columns are mechanisms. Switch mechanisms off and see which faults lose all cover. A design review starts from exactly this table.

A study aid. "Covers" means the mechanism can detect the fault in principle; real coverage depends on thresholds, timing and how each check is built. Tap a column header to switch one mechanism.

Cheat sheet

IdeaOne lineNumber to remember
Fault, error, failurecause, wrong internal state, wrong visible behaviourthe gap between them is your design
Fleet exposurem = N h / T, P(≥ 1) = 1 − e−m100,000 vehicles, 1 h a day, 1 in 100,000 h: daily
Hazard ratingseverity, exposure, controllability set the rigourASIL A to D in road vehicles, D the strictest; QM below
Time budgettdetect + treact ≤ FTTI, worst caseillustrative: 130 + 160 = 290 of 500 ms
Detection worst caseTout + Tcheck + n Tcheck100 + 10 + 20 = 130 ms
Fail-safe vs fail-operationalis "off" a safe state?a hard stop: you 25 m, the car behind 53.3 m
Timeout tradeshorter is faster and noisiertoy: 300 ms gives 1.8 false alarms per hour
End-to-endCRC, counter, timestamp, data IDCRC-8: all 1-bit errors, bursts to 8 bits, 1/256 on garbage
2oo3 votingmedian of three; 3p² independentp = 10−3: 3 × 10−6, but β = 0.1 gives 10−4
Freedom from interferencememory, time, communicationpartitions: fixed slots in a fixed frame
Modesnominal, degraded, minimal risk, safe stopflicker: about 30 changes in 6 s without hysteresis, 1 with
Safety caseclaim, argument, evidenceevery piece of evidence tied to a version

Three system design prompts

1. Design the fault handling for an onboard perception stack

Camera and radar feed a perception process, then a tracker and a planner, at about 10 to 20 Hz (illustrative). The output feeds driver assistance on highways.

  1. Clarify: the hazards and their FTTIs, whether a driver supervises, which faults matter (sensor loss, hangs, corruption, delay, overload), and the target hardware.
  2. Budget: write the FTTI split per hazard: sensor latency, detection, reaction, actuator. Keep margin.
  3. Detect: timeouts on every input, a windowed watchdog with progress counters on every process, end-to-end protection on every safety message, range, rate and frozen-data checks on sensor content.
  4. React: a mode manager with Nominal, Degraded (radar-only path, speed cap, takeover request), minimal-risk manoeuvre and safe stop, with hysteresis and a time cap on Degraded.
  5. Separate: the monitor in its own process or core, with its own inputs; memory protection and time budgets for the rest.
  6. Prove: traceability, fault injection at unit, rig and vehicle level, false-alarm rates from fleet logs.

2. The planner team wants a monitor that re-runs the planner on a second core. Respond.

  1. Name the gain: it catches random hardware faults on one core.
  2. Name the gap: it shares every bug and every input with the doer, so β for software faults is 1.
  3. Propose a checker: a small set of physical rules (envelope, time gap from raw radar) in simple code, verifiable to a deeper level.
  4. Keep both if the budget allows: lockstep or duplicate execution for hardware faults, the checker for design faults.

3. A camera sometimes freezes for a few seconds in the field. Design the detection.

  1. Layers: a timeout for silence; a counter and timestamp for repeated or late frames; a content check (hash of a pixel subsample, noise statistics) for frozen images with a live counter.
  2. Thresholds: from logged data: how often do real frames look identical? Pick N so false alarms fit the budget.
  3. Reaction: Degraded on the radar-only path, with hysteresis on recovery.
  4. Evidence: inject frozen frames on the rig at random phases; measure detection time against the FTTI.

Three coding drills

  1. Watchdog. Implement the windowed watchdog of Chapter 4 with a fake clock. Test: a hang right after a kick, an early kick, a kick with no progress, and no false alarm over 10,000 healthy cycles.
  2. End-to-end check. Implement protect() and check() for a 7-byte frame. Test every status, the counter wrap from 255 to 0, and the timestamp wrap.
  3. Frozen frame. Detect a camera that sends the same image with a fresh counter. One answer is below.
// Drill: catch a camera that keeps sending the SAME image with a fresh counter
// (a stuck image pipeline). Real sensor frames are never bit-identical, because
// of noise, so N identical frame hashes in a row is a fault, not a still scene.
#include <cstdint>

class FrozenFrameDetector {
 public:
  explicit FrozenFrameDetector(int limit) : limit_(limit) {}
  // Returns true while the stream looks alive. hash: e.g. CRC-32 of a pixel subsample.
  bool update(std::uint32_t frameHash, std::uint32_t counter) {
    const bool counterMoved = !first_ && counter != lastCounter_;
    const bool sameImage    = !first_ && frameHash == lastHash_;
    sameRun_ = (counterMoved && sameImage) ? sameRun_ + 1 : 0;   // only a live counter with a dead image counts
    first_ = false;
    lastHash_ = frameHash;
    lastCounter_ = counter;
    return sameRun_ < limit_;
  }

 private:
  int limit_, sameRun_ = 0;
  bool first_ = true;
  std::uint32_t lastHash_ = 0, lastCounter_ = 0;
};

An interviewer looks for one detail here: the detector only counts frames where the counter moved and the image did not. A dead link (no frames) is the timeout's job, and a repeated counter is the end-to-end check's job. Each check owns one kind of wrongness, so each can be tuned and tested alone.

Three debugging scenarios

  1. "The vehicle brakes hard for no reason about twice an hour." Suspect false alarms from a timeout that is close to the real jitter. Check: the logged gap distribution on each link, and which monitor fired. Fix: remove the stalls at the source, or raise the timeout if the FTTI allows, or make the reaction a degraded mode instead of a hard stop.
  2. "A hung perception process went unnoticed for 40 seconds." Suspect a watchdog kicked from a timer thread, or a publisher repeating the last buffer. Check: where the kick is called, and whether messages carry a moving counter. Fix: kick at the end of real work with a progress counter; add counter checks on the receiver.
  3. "After the update, the timestamp check fails all the time." Suspect clock synchronisation, not the network. Check: the offset between sender and receiver clocks. Fix: restore sync, and monitor sync health as its own input.

The deterministic layer and the learned layer

Deterministic safety layer (this lesson)Learned components
What it doesdetects faults, checks commands, picks modesperceives, predicts, plans
Worst casebounded and analysableharder to bound
Failure modesenumerable: silence, hang, corrupt, lateopen-ended: unseen scenes, ghosts, misses
Main standardISO 26262 style malfunction handlingSOTIF style limits and scenario coverage, plus ISO 26262 for the computer it runs on
Evidenceanalysis, unit tests, fault injectiondatasets, scenario tests, field monitoring
How they meetthe learned stack is the doer; the deterministic layer is the checker and the fallback

Reading list

Keep going on this site

The takeaway. Assume every part will fail. For each hazard, know the time you have. Detect silence, hangs, bad values and bad messages with checks simpler than what they check. React in proportion: degrade when you can, stop when you must. Keep parts from hurting each other, and prove all of it with traced evidence from injected faults.

Now press Present or Teach and explain, from memory, why a watchdog catches a frozen process but not a corrupted message, and what does. Then go back and pull a wire: corrupt perception's messages on the second architecture, then on the third, and say out loud which check made the difference.

An interviewer asks: "In one sentence, what makes a software architecture safety-critical rather than merely reliable?"
Safety-Critical Software Architecture
Onboard perception lead · Fail-safe firmware · Back to Gleams