Self-Driving Cars
Topic 21 · Part 5: Making it safe · ⏱ about 3 h

Safety and Testing: How Do You Know It Is Safe?

Why test driving alone can never prove a self-driving car is safe, how teams test instead (simulation, scenarios, closed tracks, shadow mode), how to search for failures rather than wait for them, what the main safety standards ask for, safety rules you can check at run time, and how the law is changing.

Softmaxima Simulator StudioTry this topic's code in the Studio: it opens with the traffic world project, ready to run.Open
Show:
In this topic
Beginner

In plain words

How do you know a self-driving car is safe? Not by driving it a lot: serious crashes are so rare that it would take hundreds of millions of miles to prove anything. Instead, teams test thousands of tricky situations in simulation on purpose, follow safety standards, and write a careful argument for why the car is safe.

By the end of this topic you will be able to explain how self-driving cars are tested, and find the situations where a simple car fails.

Start with: the demo Try it: sweep a cut-in scenario.

Beginner

Safety is the whole problem

Getting a car to drive itself most of the time is now a solved problem in research labs: you have built one in this course. The hard part is the rest of the time: the rare, strange situations, at night, in rain, with people doing unexpected things. A system that drives well for a thousand hours and then fails badly once is not safe enough to remove the human.

So the central question of the whole industry is not "does it drive?" but "how do we know it is safe enough?" This topic is about the answers.

Beginner

Going deeper

The sections marked Intermediate · Maths, Code or Advanced go deeper: the equations, the code and the finer details. They are worth it when you are ready, but you can follow the whole idea without them. To hide them, press those buttons next to Show at the top of the page; the Beginner explanations and Try it demos stay.

Intermediate · Maths

You cannot drive your way to safety

Human drivers in the US have about one fatal crash per 100 million miles. Suppose a self-driving car drives nn miles with no fatal crash. How sure can we be that its fatal-crash rate rr is lower? Treating crashes as rare random events (a Poisson process), the chance of seeing none in nn miles is e−rne^{-rn}. For 95% confidence we need that chance below 5%:

e−rn≤0.05⟹n≥−ln⁡0.05r≈3r e^{-rn} \le 0.05 \quad\Longrightarrow\quad n \ge \frac{-\ln 0.05}{r} \approx \frac{3}{r}

With rr = 1.09 per 100 million miles, that is about 275 million miles with no fatal crash, just to show the car is no worse than people. Showing that it is clearly better takes billions of miles (Kalra and Paddock, RAND, 2016). And every software update changes the car, which in principle restarts the count.

Code

Code: how many miles would it take?

The same idea in code.

Python · NumPy
import math

# US human drivers: about 1.09 deaths and 77 reported injuries per 100 million miles (RAND, 2016, using 2013 data).
rates = {"fatal crashes": 1.09e-8, "injury crashes": 77e-8}

# If a car drives n miles with ZERO failures, how sure can we be that its failure rate is below r?
# With a Poisson model, P(no failures | rate r) = exp(-r n). For 95% confidence we need exp(-r n) <= 0.05:
for name, r in rates.items():
    n = -math.log(0.05) / r
    print(f"to show fewer {name} than human drivers, with 95% confidence: {n / 1e6:,.0f} million miles with none at all")

def upper_bound(failures, miles, conf=0.95):
    """The highest failure rate still consistent (at this confidence) with seeing so few failures in so many miles."""
    lo, hi = 0.0, (failures + 10) * 10 / miles
    for _ in range(100):                                    # bisection on the rate
        r = (lo + hi) / 2
        p = sum(math.exp(-r * miles) * (r * miles) ** k / math.factorial(k) for k in range(failures + 1))
        lo, hi = (r, hi) if p > 1 - conf else (lo, r)
    return r

for f, m in [(0, 1e6), (1, 10e6), (5, 50e6)]:
    print(f"{f} injury crashes in {m / 1e6:.0f} million miles: the true rate could still be up to "
          f"{upper_bound(f, m) * 1e8:.0f} per 100 million miles (humans: 77)")
Open in playground ↗
Beginner

How teams test instead

Because miles alone cannot do it, self-driving teams combine many kinds of evidence, like layers of a pyramid:

  • Unit and component tests: each piece on its own: does the tracker keep IDs through a missed frame? Does the planner never return a path through an obstacle?
  • Simulation at scale: millions of virtual miles a day. Log replay plays back real recorded drives to test a new version of the software on them; scenario-based testing builds specific situations (a cut-in, a child running out) and varies their details. Formats such as ASAM OpenSCENARIO describe scenarios so different simulators can share them.
  • Closed test tracks: dangerous situations staged safely with real hardware, such as foam pedestrians and inflatable cars.
  • Public roads with safety drivers, then without them in a limited area.
  • Shadow mode: the software runs in cars driven by people, deciding but not acting; every time its decision differs from the human's, the case is logged and studied.

Each claim is limited to an operational design domain (ODD): the roads, speeds, weather and times of day the system is designed for. A robotaxi approved for one city's streets in good weather is not approved for snowy motorways.

Beginner

Search for failures, do not wait for them

A scenario has parameters: how close the other car cuts in, how much slower it is, how wet the road is, how late our car reacts. Testing a grid of values shows where the system is safe and where it fails; the boundary is where to look hardest. Smarter methods (falsification) use optimisation to search the parameter space for the worst cases on purpose, instead of hoping random testing finds them.

The demo sweeps a cut-in scenario over 384 combinations of distance and speed difference. Red cells are collisions. Change the reaction time, the braking (dry or wet road), and whether the emergency brake is on, and watch the safe region grow or shrink.

Try it

Try it: sweep a cut-in scenario

Each cell is one complete simulated run. Try a slow reaction (0.8 s) with wet brakes, then turn the emergency brake on and off. Notice that some cells are red whatever you do: if a car cuts in 3 m ahead and 15 m/s slower, no braking can avoid it. A safety argument has to say which situations the car must handle, and show that it handles them.

Interactive: this part runs in your browser.

Code

Code: a scenario sweep

The same sweep in Python. Change delay, brake or ttc_brake and compare the maps.

Python · NumPy
import numpy as np

def cut_in(d, dv, delay=0.3, ttc_brake=1.5, brake=8.0, dt=0.02):
    """A car cuts in d metres ahead of us, dv m/s slower. We follow with IDM and brake hard if the time to
    collision drops below ttc_brake. We see everything delay seconds late. Returns the closest gap (<= 0: crash)."""
    v, vl, gap = 22.0, 22.0 - dv, d
    seen = [(gap, vl)] * (int(delay / dt) + 1)
    closest = gap
    for _ in range(int(12 / dt)):
        seen.append((gap, vl))
        g, l = seen.pop(0)
        s_star = 2 + max(0, v * 1.5 + v * (v - l) / (2 * np.sqrt(1.5 * 2)))
        a = 1.5 * (1 - (v / 25) ** 4 - (s_star / max(g, 0.1)) ** 2)
        if v > l and g / (v - l) < ttc_brake:
            a = -brake                                   # emergency braking
        v = max(0.0, v + max(-brake, a) * dt)
        gap += (vl - v) * dt
        closest = min(closest, gap)
        if gap <= 0:
            break
    return closest

distances = np.arange(3, 50, 2)       # how close ahead it cuts in (m)
speeds = np.arange(15, -1, -1)        # how much slower it is (m/s)
crashes = 0
print("slower by   cut-in distance: 3 m ... 49 m  (# crash, + closer than 2 m, . safe)")
for dv in speeds:
    row = ""
    for d in distances:
        m = cut_in(d, dv)
        row += "#" if m <= 0 else "+" if m < 2 else "."
        crashes += m <= 0
    print(f"{dv:5d} m/s   {row}")
print(f"{crashes} of {len(distances) * len(speeds)} runs crash")
Open in playground ↗
Beginner

Safety standards in simple terms

  • ISO 26262 (functional safety): what happens when something breaks: a sensor fails, a chip has a fault, software has a bug. It rates each hazard by severity, exposure and controllability into a level (ASIL A to D) and demands more rigorous engineering for higher levels: redundancy, diagnostics, careful processes.
  • ISO 21448, "SOTIF" (safety of the intended functionality): what happens when nothing is broken but the system is still not good enough: the camera works perfectly, but the network misreads a light in glare. This is the standard that speaks most directly to machine learning: identify the triggering conditions, and reduce the unknown unsafe situations by testing.
  • UL 4600: a standard for the safety case of a fully self-driving product: a structured argument, backed by evidence, that the system is acceptably safe, including how it handles things nobody foresaw.

None of these says "drive this many miles". They ask for a reasoned argument: what can go wrong, how each risk is reduced, and what evidence shows it works.

Intermediate · Maths

Safety rules you can check while driving

A learned system is hard to verify completely, so many designs wrap it in simple rules that can be checked:

  • Safe distance: Responsibility-Sensitive Safety (RSS, Shalev-Shwartz, Shammah and Shashua, 2017) gives a formula for the minimum gap so that, even if the car ahead brakes as hard as possible, we can stop in time after our reaction delay ρ\rho:
    dmin=vρ+12aaccρ2+(v+ρ aacc)22bmin−vlead22bmax d_\text{min} = v\rho + \tfrac12 a_\text{acc}\rho^2 + \frac{(v + \rho\, a_\text{acc})^2}{2 b_\text{min}} - \frac{v_\text{lead}^2}{2 b_\text{max}}
    where aacca_\text{acc} is the most we might accelerate during the delay, bminb_\text{min} the braking we are sure we can do, and bmaxb_\text{max} the hardest the car ahead might brake.
  • Monitors check, every cycle, that the plan stays on the road, keeps safe gaps, and that the sensors agree with each other.
  • A fallback: if something is wrong, reach a minimal risk condition, such as slowing down and stopping at the side of the road.
Beginner

The law, briefly

Laws for self-driving cars are changing quickly, and differ by country. The shared direction is that when the system is driving, responsibility moves from the person in the seat to the company behind the system. As of late 2026:

  • Australia is developing a national Automated Vehicle Safety Law, which places responsibility for an automated driving system's safety on a corporation, not the human driver. Automated vehicles are being trialled but are not yet in general commercial use.
  • The United Kingdom passed the Automated Vehicles Act 2024. A pilot scheme for self-driving passenger services opened in spring 2026, and full implementation is expected in the second half of 2027.
  • The United States has no single federal self-driving law; states set the rules for testing and deployment, and the federal safety regulator (NHTSA) requires crashes involving automated systems to be reported.
  • The European Union has type-approval rules for automated driving systems in specific situations, building on UN vehicle regulations.

Check the current rules where you live: this section will date faster than the rest of the course.

Check yourself

Quiz

1. Why can test driving alone not prove a self-driving car is safer than people?

2. What is an operational design domain (ODD)?

3. Which standard is about a system that is not broken but still not good enough, such as a network misreading a light in glare?

4. What does "shadow mode" mean?

5. What is falsification in scenario testing?

Go deeper

📚 Further reading

Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.

Ready