Automotive Camera Occlusion Architecture and Periodic Fault Debugging

Medium · System Design · Software Engineer · Technical Screen

Prompt

You are architecting the exterior vision health monitor and safety-degradation subsystem for an electric adventure vehicle equipped with Level 2+ highway assist (automated lane keeping, adaptive cruise gap control, and initiated lane changes) as well as low-speed autonomous guidance (automated parking and narrow off-road trail creeping).

In real-world driving, exposed camera optics encounter mud spray, snow and ice buildup, trail dust, interior fogging, and direct low-angle sun glare. Your design must address both on-vehicle architecture and active field root-cause investigation:

  1. Multi-modal 360-degree sensor layout: Select and position exterior cameras alongside complementary ranging modalities (such as millimeter-wave radar and ultrasonic transducers) to achieve full surround awareness and redundant forward highway coverage.
  2. Real-time lens health classification: Detect and report per-camera optical status (Clear, Partially Occluded, Fully Occluded, Blinded/Glare) on an embedded automotive SoC accelerator using under 5% of the perception compute budget and flagging full blockage within 1.0 second.
  3. Graceful feature degradation: Specify deterministic fallback transitions across lateral and longitudinal control—distinguishing fail-operational handoff windows from fail-safe stops—when individual or overlapping sensors degrade.
  4. Bandwidth-bounded diagnostic snapshots: Record event-driven diagnostic bundles (health state context, aligned hardware timestamps, and compact thumbnail imagery) while keeping normal cellular telemetry strictly at or below 20 MB per driving hour.

Field Investigation Scenario: Validation technicians report that multiple test vehicles raise a spurious "Front Wide Camera Fully Occluded" fault roughly once every 60 minutes (+/- 2 minutes) on cloudless, sunny highway drives, momentarily dropping lateral steering assist. Outline how you would partner with the validation team to form falsifiable hypotheses, reproduce and isolate the defect without putting test drivers at risk, capture time-aligned bus/ECU traces (CAN, automotive Ethernet, PTP/monotonic clocks), and verify a permanent fix before fleet rollout.

Scope & Expectations

  • Sensor topology & resource-bounded detection: Concrete 360-degree camera/radar/ultrasonic layout, back-of-the-envelope compute/latency/cellular math, and a fast optical-health pipeline combining image statistics with cross-sensor checks.
  • Safety fallback state machine: Deterministic degradation hierarchy separating steering handoffs from radar-backed longitudinal control, complete with debounce hysteresis and driver takeover escalation.
  • Structured embedded debugging: Testable periodic embedded failure hypotheses (sensor calibration cycles, clock-sync jumps, counter/buffer wraps, thermal or I/O stalls) paired with synchronized trace collection.
  • Safe reproduction & release gating: Stepwise off-road isolation (offline replay, HIL bench fault injection, A/B hardware swaps) and statistical regression validation prior to over-the-air deployment.

Step-by-step walkthrough

  1. Clarify scope, safety context, and constraints

    This problem combines embedded system design (sensor placement, real-time camera blockage detection, safe feature degradation, and cellular telemetry) with systematic field debugging (diagnosing a repeatable once-per-hour false "Front Wide Camera Fully Occluded" alert).

    Key assumptions and operating context

    • Autonomy level: Level 2+ means the vehicle can steer, accelerate, and brake on mapped highways up to 130 km/h (and creep autonomously below 15 km/h for parking and off-road trails), while an attentive human driver—monitored by an interior infrared camera—remains the ultimate safety fallback.
    • Hardware platform: One automotive SoC (system-on-chip—a single chip integrating multiple specialized processors): an ISP (image signal processor that turns raw camera pixels into clean images and downscaled thumbnails in hardware), a DSP (digital signal processor optimized for fast pixel/math loops), an NPU (neural processing unit for deep-learning perception models), a hardware H.265 video encoder, and an isolated lockstep safety core (a dedicated microcontroller partition certified under ISO 26262 / SOTIF safety standards).
    • Crucial fifth health state (Unavailable): Beyond Clear, Partially Occluded, Fully Occluded, and Blinded/Glare, our detector explicitly separates Unavailable (missing frames, frozen buffer, link checksum errors, or active ISP recalibration). Confusing "no valid frames arrived" with "mud is covering the glass" causes wrong diagnostics, useless washer sprays, and phantom field faults like the hourly bug in Part 2.
    • Target reliability: Fewer than 1 false Fully Occluded event per 1,000 driving hours per camera (the reported field bug of ~1 per hour is 1,000x above budget).

    Hard embedded constraints

    • Compute: < 5% of the perception compute budget.
    • Detection latency: Flag Fully Occluded within <= 1.0 second of physical onset.
    • Cellular bandwidth: <= 20 MB per driving hour during normal operations (depot Wi-Fi is uncapped for validation vehicles).
  2. Propose the 360-degree sensor layout and verify budgets

    Multi-modal 360-degree sensor suite (11 exterior cameras + 5 radars + 12 ultrasonics + 1 interior camera):

                                          FRONT OF VEHICLE
                   [Corner Radar FL]     [Long-Range Radar]     [Corner Radar FR]
                       [Narrow 30° + Main 60° + Wide 120° Cameras]  (behind wiped/heated windshield)
                       [Front Fisheye 190°] in grille (air/washer jet) + 6 Front Ultrasonics
    
      [Side-Forward L 90°] on B-pillar                               [Side-Forward R 90°] on B-pillar
      [Side-Rear L 75° + Fisheye L 190°] on mirror       [Fisheye R 190° + Side-Rear R 75°] on mirror
                                     [Interior IR Driver Monitor]
    
                       [Rear Fisheye 190°] on tailgate (air/washer jet) + 6 Rear Ultrasonics
                   [Corner Radar RL]                            [Corner Radar RR]
                                           REAR OF VEHICLE
    
    Sensor group Count Field of view & role
    Forward Narrow / Main / Wide (8 MP) 3 30° (far highway lanes), 60° (primary objects/lanes), 120° (cut-ins, tight curves, traffic lights); share windshield wipers + defroster
    Side Forward & Side Rear (3 MP) 4 75°–90°; blind spots, merges, and automatic lane-change verification
    Surround Fisheyes (3 MP) 4 190°; 360° stitching for parking and tight rock/trail clearance; exposed lenses get air/washer nozzles
    Long-Range Front + Corner Radars (77 GHz) 5 Independent physics modality (millimeter-wave radio) immune to glare, darkness, and light mud splatter
    Ultrasonic Bumpers 12 Short-range (0.2–4 m) curb, wall, and obstacle distance below 15 km/h

    Compute, latency, and cellular bandwidth math:

    1. Compute budget (evaluated separately on DSP vector cores vs. NPU tensor cores)
       ISP hardware scaler output:   480 x 270 luma+chroma @ 10 Hz (every 3rd 30-fps frame), zero CPU/NPU cost
       Grid geometry:                16 x 9 = 144 tiles of 30 x 30 pixels
       Classical DSP pixel pass:     480 x 270 x ~50 ops/px = ~6.5M ops/frame x 10 Hz = 65M ops/s per camera
                                     11 exterior cameras = ~0.72 GOPS -> ~0.7% of a 100 GOPS DSP budget (< 5%!)
       Optional tiny NPU CNN check:  128 x 72 thumbnail, ~20M MACs (~40M ops) x 10 Hz x 11 = ~4.4 GOPS
                                     4.4 GOPS / 50,000 GOPS (50 TOPS perception NPU) = < 0.01% of NPU (< 5%!)
    
    2. Worst-case detection latency for "Fully Occluded" (target <= 1.0 s)
       Sensor exposure + readout + ISP scale:        ~50 ms
       Wait for next 10 Hz detector tick:          0-100 ms
       DSP tile feature + cross-sensor pass:         ~20 ms
       Debounce (5 of 6 frames @ 10 Hz after 1st): 400-500 ms
       Safety-core 50 Hz step + mode broadcast:      ~40 ms
       Worst-case end-to-end total:                ~0.71 s  (~0.29 s safety margin inside 1.0 s!)
    
    3. Cellular telemetry budget (target <= 20 MB / driving hour)
       1-minute health summaries:    11 cameras x 60 min x ~200 B    = ~0.13 MB / hour
       Compressed event snapshot:    ~197 KB (~200 KB budget) each
       Token-bucket rate limiter:    12 MB/h refill + 4 MB burst     = <= 16.0 MB in ANY 60-min window
       Worst-case hourly cellular:   16.0 MB + 0.13 MB               = ~16.1 MB / hour (strictly <= 20 MB!)
    
  3. Define internal bus interfaces and dual-clock timestamps

    Every safety-relevant message carries an alive counter (incrementing sequence number) and a CRC (cyclic redundancy check—a fast mathematical checksum) so receivers immediately catch dropped, repeated, or corrupted packets:

    Topic: camera_health/<camera_id>   (10 Hz, published by DSP Blockage Detector)
      { camera_id, seq, alive_counter, crc32,
        capture_ts_ptp_ns,          // Vehicle-wide synchronized clock (gPTP) for cross-ECU log alignment
        publish_ts_monotonic_ns,    // Local non-jumping stopwatch since boot for ALL timeout/age math
        status: CLEAR | PARTIALLY_OCCLUDED | FULLY_OCCLUDED | BLINDED_GLARE | UNAVAILABLE,
        confidence: 0.0..1.0,
        weighted_blocked_fraction: 0.0..1.0,
        cause_hint: NONE | STATIC_DIRT | SNOW_ICE | LOW_CONTRAST_ENV | SUN_GLARE | MISSING_OR_ISP_CAL,
        blocked_tile_bitmap: uint8[18] }   // 144 bits (1 bit per 30x30 tile)
    
    Topic: adas_mode                   (50 Hz, published by Safety-Core Degradation Manager)
      { highway_level: D0_FULL | D1_CAUTIOUS | D2_NO_LANE_CHANGE | D3_TAKEOVER_RADAR_LONG | D4_MRM_STOP,
        low_speed_state: ACTIVE | BRAKE_HOLD | OFF,
        takeover_alert: NONE | VISUAL_CHIME | URGENT_HAPTIC,
        active_reasons: ["front_wide:FULLY_OCCLUDED"],
        entered_at_monotonic_ns }
    

    Why every message carries TWO clocks: - capture_ts_ptp_ns comes from gPTP (generalized Precision Time Protocol, IEEE 802.1AS, which synchronizes clocks across vehicle Ethernet nodes to sub-microsecond accuracy). Use it only to line up camera frames with radar and CAN logs. - publish_ts_monotonic_ns comes from the SoC's monotonic hardware timer (a stopwatch counting ticks since boot that never steps forward or backward). Measuring frame age or watchdog timeouts with a network-synced clock is a classic embedded bug: a +200 ms clock sync jump instantly makes fresh frames look 200 ms stale!

  4. High-level embedded architecture and data model

      11 Exterior Cameras (GMSL/FPD-Link serializer links)
             |
             v
      +-------------+  full-res 8MP/3MP @ 30fps   +------------------------------------+
      | Hardware ISP|---------------------------->| Perception Neural Nets (NPU)       |---> Planning
      +------+------+                             +-----------------+------------------+
             |  \                                                   | object boxes per region
             |   +-- 480x270 @ 10Hz + exposure/gain/cal flags       v
             |                                    +------------------------------------+
             |   CAN (speed, yaw, wipers, sun) -->| Blockage Detector (Isolated DSP)   |
             |   77 GHz Radar tracked objects --->|  - 6-stage CV + cross-sensor check |
             |                                    +-----------------+------------------+
             |                                                      | camera_health (10Hz, E2E CRC)
             v                                                      v
      +----------------+                          +------------------------------------+
      | H.265 Encoder  |                          | Degradation Manager (Safety Core)  |---> Steering / Brakes
      +-------+--------+                          |  - Deterministic 50Hz D0..D4 table |---> Cluster HMI / Chime
              |                                   +-----------------+------------------+---> Washer / Air Jets
              v                                                     | trigger on state transition
      [ DRAM Ring Buffers ] (30s tile features,                     v
       20s encoded video, 15s CAN/gPTP traces) -->+------------------------------------+
                                                  | Event Snapshotter & Flash Store    |
                                                  +-----------------+------------------+
                                                                    |
                                             +----------------------+----------------------+
                                             | <= 20 MB/h Token Bucket                     | Uncapped
                                             v                                             v
                                     [ Cellular LTE/5G ]                           [ Depot Wi-Fi Offload ]
    
    • Compute isolation: Running the blockage detector on the DSP guarantees that an NPU perception spike can never starve health monitoring, and running the degradation manager on the lockstep safety core ensures a main-OS crash triggers a safe takeover within 300 ms (3 missed 10 Hz heartbeats).
    • Periodic-bug telemetry fields: Every persistent flash event explicitly records both uptime_s (seconds since SoC boot) and minute_of_hour (0..59 UTC). Plotting histograms of those two numbers across the fleet separates boot-timer bugs from wall-clock bugs in seconds.
  5. Deep dive 1: Six-stage blockage detection pipeline

    Rather than trusting a black-box classifier alone, the detector runs six interpretable stages at 10 Hz:

    1. Stage 1 — Stream integrity gate (UNAVAILABLE): Check monotonic frame age (< 100 ms), sequential frame counter, bit-identical frozen-buffer check, link CRC errors, and ISP metadata flags (calibration_active, hdr_mode_switch). Corrupted or missing streams emit UNAVAILABLE; single frames flagged calibration_active by the ISP are skipped cleanly instead of poisoning blockage counters.
    2. Stage 2 — Classical per-tile CV features (16 x 9 = 144 tiles): On each 30 x 30 tile, compute spatial frequency / sharpness (Laplacian variance, measuring second-derivative intensity jumps that vanish under blur, mud, or frost), edge gradient density (fraction of pixels with strong horizontal/vertical brightness steps), histogram contrast (standard deviation of pixel brightness), bright-saturation / dark-pixel fractions, and 1-second pixel change:
    import numpy as np
    
    TILE_SIZE = 30  # 270 x 480 luma frame -> 9 rows x 16 cols = 144 tiles
    
    
    def compute_tile_features(gray: np.ndarray, gray_1s_ago: np.ndarray) -> dict:
        """Compute classical per-tile blockage features on 270x480 uint8 luma frames."""
        img = gray.astype(np.float32)
    
        # 1. Edge gradients (|dx| + |dy|) capture crisp lane/object boundaries.
        grad_x = np.abs(img[:, 2:] - img[:, :-2])
        grad_y = np.abs(img[2:, :] - img[:-2, :])
        grad_mag = np.pad(grad_x[1:-1, :] + grad_y[:, 1:-1], 1, mode="edge")
    
        # 2. 2D discrete Laplacian captures high spatial frequency (sharpness).
        lap_core = (
            img[1:-1, :-2] + img[1:-1, 2:] + img[:-2, 1:-1] + img[2:, 1:-1]
            - 4.0 * img[1:-1, 1:-1]
        )
        lap = np.pad(lap_core, 1, mode="edge")
    
        # 3. 1-second temporal frame difference spots static mud while moving.
        frame_diff = np.abs(img - gray_1s_ago.astype(np.float32))
    
        n_rows = gray.shape[0] // TILE_SIZE
        n_cols = gray.shape[1] // TILE_SIZE
        out = {k: np.zeros((n_rows, n_cols), dtype=np.float32)
               for k in ("contrast", "sharpness", "edge_density", "saturated", "dark", "change_1s")}
    
        for r in range(n_rows):
            for c in range(n_cols):
                ys = slice(r * TILE_SIZE, (r + 1) * TILE_SIZE)
                xs = slice(c * TILE_SIZE, (c + 1) * TILE_SIZE)
                patch = gray[ys, xs]
                out["contrast"][r, c] = img[ys, xs].std()
                out["sharpness"][r, c] = lap[ys, xs].var()
                out["edge_density"][r, c] = (grad_mag[ys, xs] > 25.0).mean()
                out["saturated"][r, c] = (patch >= 250).mean()
                out["dark"][r, c] = (patch <= 10).mean()
                out["change_1s"][r, c] = frame_diff[ys, xs].mean()
        return out
    
    1. Stage 3 — Tile classification with sky protection (UNCERTAIN): Tiles classify into CLEAR, BLOCKED, SATURATED, or UNCERTAIN. Clear blue sky or sunlit desert concrete naturally has low sharpness and edge density; marking bright, uniform upper-horizon tiles UNCERTAIN (excluded from the denominator unless stationary over changing background) prevents clear-day false positives.
    2. Stage 4 — Cross-sensor validation:
      • Optical flow vs. vehicle speed: Optical flow is the apparent motion of scene pixels across consecutive frames. Above 5 m/s (18 km/h), road and roadside pixels must expand outward at rates proportional to CAN speed and yaw rate; tiles with change_1s ~ 0 while neighboring tiles flow normally indicate matter stuck directly on the glass.
      • Radar target projection: Project 77 GHz front-radar tracks into camera coordinates. If radar tracks a car 40 m ahead inside tiles where the camera sees flat, zero-edge pixels, physical occlusion confidence rises sharply; conversely, live NPU detections inside a tile prove it is see-through.
      • Overlapping forward cameras: front_narrow, front_main, and front_wide share the central forward cone. Sharp lane lines in front_main paired with blur in front_wide isolates a local front_wide smudge, whereas simultaneous contrast loss across all cameras indicates fog, heavy rain, or an unlit tunnel (LOW_CONTRAST_ENV).
      • Sun vector check: GPS position + UTC time + vehicle heading + dashboard solar sensor confirm whether SATURATED tiles match direct sun near the lens axis (BLINDED_GLARE).
    3. Stage 5 — Priority camera rollup (road/horizon ROI tiles carry 2x weight; first match wins):
      • UNAVAILABLE (Stage 1 fault) -> BLINDED_GLARE (saturated >= 0.30 + sun alignment; checked before FULLY_OCCLUDED so sun-washed frames don't trigger mud washers!) -> FULLY_OCCLUDED (weighted_blocked >= 0.90 and not LOW_CONTRAST_ENV) -> PARTIALLY_OCCLUDED (weighted_blocked >= 0.20) -> CLEAR.
    4. Stage 6 — Temporal debounce with hysteresis (hysteresis means requiring stricter, longer proof to clear a fault than to enter it so states never chatter rapidly):
      • Enter FULLY_OCCLUDED or BLINDED_GLARE on 5 of the last 6 frames (0.5–0.6 s), meeting the <= 1.0 s budget; exit only after 20 consecutive clean frames (2.0 s). Enter PARTIALLY_OCCLUDED after 2.0 s and exit after 5.0 s.
  6. Deep dive 2: Deterministic degradation hierarchy and driver handoff

    In safety engineering, fail-operational means continuing to control the vehicle safely (possibly with reduced features) after a component fault, whereas fail-safe means transitioning cleanly to driver control or a safe stop. On a 120 km/h highway, a Level 2+ pilot is fail-safe overall, but its multi-second handoff transition must be fail-operational—snapping steering torque to zero mid-curve would surprise a hands-free driver.

    The safety core evaluates a deterministic 50 Hz lookup table (D0 through D4; worst active condition wins):

    Level  Triggering sensor condition            Lateral (steering) behavior          Longitudinal (speed/gap) behavior
    -----  -------------------------------------  -----------------------------------  ---------------------------------
    D0     All highway sensors CLEAR              Full lane centering + auto lane chg  Full adaptive cruise
    D1     1 forward cam PARTIAL, or 1 side cam   Keep lane centering; block auto      Full cruise with +0.5s larger
           / corner radar degraded                lane changes toward affected side    following time gap
    D2     front_wide FULL / UNAVAILABLE while    Keep lane centering on main+narrow;  Full cruise capped at 110 km/h;
           front_main + front_narrow are CLEAR    lower max curve rate; no lane chg    notify driver on cluster
    D3     Forward vision lost (2+ forward cams   IMMEDIATE TAKEOVER REQUEST; hold     RETAIN RADAR-BASED CRUISE
           FULL / GLARE / UNAVAILABLE) while      bounded degraded lane estimate on    (capped speed, larger gap) so car
           front long-range radar is HEALTHY      side cams until hands-on-wheel,      never rear-ends traffic during
                                                  then ramp torque out over 1.5 s      steering handoff!
    D4     Forward vision AND front radar lost,   Urgent haptic + audible alert;       Controlled deceleration (-2 m/s²),
           OR driver ignores D3 for > 10 s        hold last path estimate while        hazard lights on, full in-lane
                                                  braking                              minimal-risk stop
    

    Handoff timeline and anti-flapping invariants: - t = 0 s (entering D3): Visual banner + chime fires; driver-monitoring camera checks eyes/hands; radar maintains safe longitudinal spacing while degraded lateral hold prevents instant lane departure. Once steering-wheel torque/capacitance confirms hands-on, lateral assist smoothly ramps torque out over 1.5 s (never a sudden step!). - t = 4 s (still hands-off): Escalate to loud urgent chime + seat/seatbelt haptic pulse. t = 10 s: Transition to D4 minimal-risk stop. - Manual re-engagement rule: Even if mud washes off 2 s later, steering assist never re-engages automatically after a takeover request—the driver must explicitly press resume. - Low-speed maneuvering (< 15 km/h): Fail-safe by braking immediately. At 15 km/h (4.17 m/s) and 3 m/s² deceleration, stopping distance v² / (2a) = 2.9 m (~3.5 m including 150 ms brake build-up), holding standstill until the driver takes over. - Notice the immediate payoff on our field issue: With D2 in place, a single front_wide fault while front_main and front_narrow are CLEAR gracefully disables auto lane-changes instead of abruptly dropping highway steering!

  7. Deep dive 3: Telemetry snapshotting within 20 MB/hour

    Whenever debounced camera health or adas_mode changes, the Event Recorder freezes a lightweight diagnostic bundle from DRAM rings without exceeding 20 MB/hour:

    Snapshot payload breakdown (per state-transition event)            Raw size    Compressed
    -----------------------------------------------------------------  ----------  ----------
    Tile status + confidence, -10s..+5s (150 frames x 144 x 2 B)          43.2 KB      ~10 KB
    Full 10-feature tile vectors, -1s..+1s (20 frames x 144 x 20 B)       57.6 KB      ~30 KB
    30-fps ISP frame metadata, 15s (450 frames x 64 B: exp/gain/flags)    28.8 KB      ~10 KB
    8 context JPEGs @ 320x180 (6 on fault cam: -4,-2,-1,0,+1,+2s + 2 nbr) 120.0 KB     120 KB
    ~30 CAN + radar summary signals over 10s                              60.0 KB      ~20 KB
    gPTP sync state, monotonic offsets, DSP thread jitter, temperatures   10.0 KB       ~5 KB
    Manifest (VIN, SW/FW/ISP versions, uptime_s, minute_of_hour)           2.0 KB       ~2 KB
    -----------------------------------------------------------------  ----------  ----------
    Total per uploaded snapshot                                                        197 KB (~200 KB)
    

    Guaranteed <= 20 MB/hour enforcement: - Token-bucket rate limiter: A token bucket (a credit counter that refills steadily at 12 MB/hour up to a 4 MB maximum burst cap) governs cellular snapshot uploads. Even if a car starts an hour with a full 4 MB burst and earns 12 MB over the next 60 minutes, it can upload at most 16 MB of snapshots (~80 events) plus 0.13 MB of 1-minute summaries = 16.13 MB <= 20 MB/hour. - Priority & storm deduplication: D3/D4 takeovers and UNAVAILABLE monitor faults get top priority; if the same camera repeats the exact same transition within 5 minutes (e.g., driving through patchy snow spray), it increments occurrence_count and uploads full snapshots only on the 1st and every 10th occurrence. Full H.265 video stays in local flash for depot Wi-Fi pull requests.

  8. Troubleshooting part 1: Root-cause hypotheses and synchronized traces

    Partner directly with the fleet technician to gather ground truth before touching code: compare affected vs. unaffected VINs (camera hardware lot, serializer harness, ISP firmware, SoC OS version), record exact ignition-on and fault timestamps, check whether parked cars in sun or >1-hour night drives trigger it, and inspect whether ±2 min is true timing spread or manual log rounding.

    First diagnostic split — plot uptime_s vs. minute_of_hour: - Spikes at uptime_s ~ 3600, 7200, ... regardless of start time -> boot-relative timer, buffer wrap, or thermal soak. - Spikes at the same wall-clock minute (e.g., :00 every hour) regardless of start time -> scheduled cron/log job or hourly time sync.

    Testable root-cause hypotheses:

    ID Embedded root-cause hypothesis Mechanism producing false FULLY_OCCLUDED Distinguishing trace signature
    H1 Hourly ISP auto-exposure / dark-current / HDR recalibration Camera firmware runs an hourly sensor calibration (3600s ± jitter), emitting 5–6 black or flat frames without setting calibration_active Context JPEGs at t=0 go uniformly black/gray while exposure/gain jumps; front_main stays normal; locked to camera uptime_s
    H2 Hourly PTP / NTP clock synchronization jump Telematics/NTP steps system/gPTP clock hourly; code mistakenly checks age = now_ptp - frame_ptp, drops 6 "stale/future" frames, and maps 0 valid frames -> FULL ptp_offset step or grandmaster switch aligns to the millisecond with the fault; image pixels look completely normal
    H3 Ring-buffer or integer counter wrap-around A 36,000-slot 1-hour 10 Hz history ring wraps (36,000 / 10 Hz = 60.0 min, drifting ±2 min with minor rate jitter) with an off-by-one reading zeroed memory (note: raw 2^32 us = 71.6 min, immediately ruling out 32-bit microsecond rollover!) Fires at exact slot/frame count 36,000 (or 65,536 on a ~18 Hz loop); change_1s or feature array spikes on 1 exact index
    H4 Thermal management fan / SoC throttling cycle Cabin/enclosure heats over ~60 min in bright sun (±2 min weather drift); SoC throttles DSP or enclosure heater fogs/shifts optics soc_temp hits throttle point and DSP deadline misses spike, or period shortens on hotter days
    H5 Hourly flash log rotation / telemetry flush Hourly job saturates eMMC I/O and blocks a mutex foolishly shared by the detector thread for > 600 ms Detector thread execution time spikes from 20 ms to > 600 ms alongside kernel block-I/O stalls

    Synchronized traces to pull over depot Wi-Fi (validation fleet has no cellular cap in the bay): - Per-frame ISP log (frame_counter, sensor_ts, soc_rx_monotonic_ts, ptp_ts, exposure_us, analog_gain, hdr_mode, isp_flags, serializer CRC counters) + saved 320x180 / H.265 frames around t = 0. - Detector per-frame stage outputs (Stage 1 integrity flags, 144 tile feature vectors, thread start/end monotonic timestamps). - gPTP daemon log (offset_from_master, step events, grandmaster MAC) + OS chronyd/NTP adjustments + Linux ftrace scheduler/I/O trace + CAN bus trace (speed, steering assist state, solar sensor, temperatures).

  9. Troubleshooting part 2: Safe reproduction, isolation, and fix validation

    Reproduce on the lowest, safest rung of this 4-step ladder (never disable safety fallbacks on public roads!): 1. Rung 1 — Deterministic offline replay (zero risk): Feed captured raw/encoded frames + ISP/CAN logs from a field incident into the exact detector binary on a workstation. If FULLY_OCCLUDED fires offline, the bug is inside the pixels or detector math (H1 or threshold bug); if it does not fire offline, the bug is real-time scheduling, clock stepping, or memory state (H2–H5). 2. Rung 2 — Hardware-in-the-Loop (HIL) bench (zero driver risk): Mount a production ECU + affected front_wide camera aimed at a high-lux daylight display rig with simulated 100 km/h CAN speed and gPTP master. Compress a 60-minute wait into seconds via fault injection: preload ring-buffer/frame counters to wrap - 100, inject ±500 ms gPTP clock steps, trigger ISP recalibration via register command, heat the ECU in a thermal chamber, and force hourly log rotation. 3. Rung 3 — Stationary sunlit vehicle soak: Park an affected validation truck outdoors in bright sun with ignition on for 3 hours (isolating optical/thermal/ISP effects safely at 0 km/h, noting ego-motion checks stay inactive). 4. Rung 4 — Closed proving ground: Briefed safety driver with hands hovering at the wheel around minute 60, all production safety transitions enabled.

    Isolate via A/B swap: Swap the physical front_wide camera module between a failing truck and a healthy truck—if the hourly fault follows the camera, inspect camera firmware/ISP lot; if it stays with the truck, inspect SoC software, harness, or gateway gPTP. Confirm root cause only when you can toggle the fault ON via injection and OFF with the fix on demand.

    Targeted engineering fixes & statistical release gates: - Structural fixes: Map missing/stale/CRC-bad frames strictly to UNAVAILABLE (holding last valid health for <= 300 ms before D2), compute all frame ages and debounce timers exclusively on CLOCK_MONOTONIC, make ring indices wrap-safe unsigned modular arithmetic, honor/add ISP calibration_active frame-skip flags (and defer non-urgent recalibrations to standstill), and run the detector on an isolated SCHED_FIFO real-time thread with lock-free ring buffers. - Validation before fleet OTA: 1. Unit + HIL regression suite: Automated tests covering counter wrap (35,999 -> 0 and 65,535 -> 0), ±2 s PTP jumps, and injected ISP calibration frames; verify old firmware fails on the HIL bench and new firmware passes 300+ bench-hours with 0 false positives (by the rule of three, 0 events in 300 h bounds the rate below 3 / 300 = 1 per 100 h at 95% confidence). 2. True-positive latency check: Replay the labeled mud/snow/glare dataset and run physical mud-spray track tests verifying FULLY_OCCLUDED still triggers in < 1.0 s (~0.7 s). 3. Shadow mode & staged OTA: Run the new detector in shadow alongside production across validation vehicles (3,000+ driving hours with 0 false alerts proves < 1 per 1,000 h), confirm with the technician on the original trucks, then roll out 1% -> 10% -> 100% with automated A/B rollback gates.

  10. Summary of key trade-offs

    • Interpretable tile CV + cross-sensor checks vs. end-to-end deep neural net: Classical tile heuristics + radar/optical-flow checks use < 1% of DSP budget and make field snapshots trivial to debug, whereas adding a tiny thumbnail CNN only as a secondary tie-breaker avoids opaque false positives.
    • Short 0.6 s debounce (FULL) vs. multi-second motion check (PARTIAL): Meeting the <= 1.0 s safety requirement allows only 5–6 frames at 10 Hz, requiring strong global flatness + cross-camera checks for FULL while reserving slower ego-motion checks for PARTIAL.
    • Dedicated UNAVAILABLE state vs. collapsing pipeline faults into FULLY_OCCLUDED: Adds one enum state across interfaces, but cleanly separates dirty glass from dropped frames, clock jumps, and ISP calibration glitches.
    • Graded fallback (D2 single-camera tolerance, D3 radar cruise + ramped steering handoff) vs. instant full cutout: Requires testing 5 explicit modes on the safety core, in exchange for preventing abrupt highway steering loss when a single lens gets dirty.
    • Asymmetric hysteresis + manual steering re-engagement vs. instant auto-recovery: Keeps features degraded a few extra seconds after clearing, preventing dangerous mode oscillation under flickering tree shadows or patchy spray.
    • 200 KB feature/thumbnail snapshots over cellular + Wi-Fi video pull vs. streaming raw video: Requires a second depot pull when full 8 MP video is needed, while guaranteeing cellular usage stays strictly inside 20 MB/hour.

Intuition & how it works

Think of an automotive camera-blockage and degradation system like an airline cockpit crew flying with three overlapping forward windshields plus weather radar. A fast, lightweight spotter (the DSP blockage detector) inspects a 16 x 9 grid of each windshield 10 times a second and cross-checks it against the plane's airspeed, radar returns, and neighboring windows so it can tell mud stuck on one pane apart from flying into dense fog or a loose display cable. Meanwhile, an independent co-pilot (the safety-core degradation manager) follows a strict deterministic checklist: if only the wide outer pane gets muddy, keep steering on the two clean forward panes and simply pause automatic lane changes; if all forward panes go blind, keep safe distance from traffic ahead using radar while chiming the human driver and holding the lane smoothly for the 1–2 seconds it takes them to grip the wheel.

Two naive shortcuts fail dangerously in real vehicles. First, running heavy neural networks on full 8-megapixel frames wastes perception compute, yet judging a single camera solely by "flat contrast" mistakes clear blue sky, sunlit desert concrete, or dense fog for physical mud—causing startling highway disengagements. Second, lumping "no fresh frames arrived" into "Fully Occluded" or measuring frame age using a network-synced wall clock instead of a local monotonic clock (a non-jumping hardware stopwatch since boot) turns routine hourly embedded events—like an NTP/PTP clock step, an ISP (image signal processor) exposure recalibration, or a ring-buffer wrap—into phantom "Fully Occluded" faults every 60 minutes.

Walk through two concrete 0.7-second traces at 100 km/h (27.8 m/s) on a bright highway:

  1. Real mud splatter on front_wide (t = 0.0 s): Mud covers 135 of the 144 30 x 30 tiles (94%). Sharpness (Laplacian variance, measuring crisp pixel-intensity jumps) and edge gradients drop near zero, and 1-second pixel change stays near zero even though CAN vehicle speed is 27.8 m/s and front_main still sees sharp lane markings in their shared field of view. After 5 of 6 10 Hz frames (t = 0.6 s, comfortably under the 1.0 s limit), front_wide enters FULLY_OCCLUDED, the safety core steps from D0 to D2 (continuing lane centering on front_main + front_narrow while disabling auto lane-change), triggers a cleaning pulse, and queues one 197 KB cellular snapshot.
  2. Hourly +250 ms network clock jump or 5-frame ISP calibration (t = 3600 s): Because Stage 1 measures frame age exclusively on CLOCK_MONOTONIC (12 ms < 100 ms), the clock jump does nothing at all; and if an hourly ISP calibration flags or drops 5 frames, Stage 1 skips flagged calibration frames or emits UNAVAILABLE (holding the last valid state briefly) rather than falsely declaring FULLY_OCCLUDED.

Key trade-offs

  • Classical tile heuristics + cross-sensor checks vs. end-to-end deep neural networks: Computing sharpness, edge gradients, saturation, and 1-second pixel diffs on 480 x 270 ISP hardware thumbnails uses ~0.7% of DSP (digital signal processor) capacity and produces human-readable tile bitmaps for field debugging, whereas adding a tiny 128 x 72 CNN (< 0.01% of NPU neural-accelerator budget) only as a secondary tie-breaker captures subtle condensation without black-box false positives.
  • Fast 0.6 s full-occlusion debounce vs. multi-second motion tracking: Meeting the <= 1.0 s full-occlusion deadline allows only 5 of 6 decisions at 10 Hz, requiring strong whole-frame flatness plus cross-camera disagreement for FULLY_OCCLUDED while reserving slower 2.0 s optical-flow checks (comparing pixel motion against vehicle speed) for PARTIALLY_OCCLUDED.
  • Explicit UNAVAILABLE status vs. folding stream errors into FULLY_OCCLUDED: Adding one status enum across internal topics cleanly separates dirty glass (needs washer jet / driver cleaning message) from dropped frames, clock steps, and frozen buffers (needs software/link diagnostics).
  • Graded fallback hierarchy (D0–D4) vs. binary all-or-nothing disengagement: Supporting intermediate modes (D2 single-camera tolerance; D3 radar longitudinal cruise + ramped lateral handoff) requires exhaustive testing of 5 state rows on the safety core, in exchange for eliminating sudden highway steering cutouts on single-sensor faults.
  • Fail-safe system with a fail-operational handoff window: Keeping 77 GHz radar cruise active and holding bounded lateral lane estimates while ramping steering torque out over 1.5 s once hands-on-wheel is detected requires multi-sensor redundancy, preventing abrupt mid-curve departures at 120 km/h.
  • Asymmetric hysteresis + manual lateral re-engagement vs. instant auto-resume: Requiring 2.0–5.0 s of clean frames to clear a fault and requiring an explicit driver button press to resume steering after a takeover prevents dangerous mode flapping under tree-shadow flicker or road spray.
  • Compact ~200 KB cellular snapshots + depot Wi-Fi video pulls vs. continuous raw uploads: Enforcing a 12 MB/h refill + 4 MB burst token bucket (a credit counter capping any 1-hour window at <= 16 MB of event uploads) guarantees strict compliance with the 20 MB/h cellular cap even in a blizzard, trading an extra Wi-Fi pull step when engineers want full-resolution video.

Common mistakes

  • Mapping missing, stale, or ISP-recalibration frames to FULLY_OCCLUDED: Without a Stage 1 integrity check and a separate UNAVAILABLE state, every frame drop, serializer CRC error, or hourly exposure calibration masquerades as physical mud on the lens.
  • Computing frame age or timeouts with gPTP / wall-clock timestamps: Stepping a network-synced clock forward or backward immediately makes healthy frames appear expired or from the future; always measure elapsed durations with CLOCK_MONOTONIC.
  • Flagging low-texture regions (blue sky, concrete walls, empty highway asphalt) as occluded: Naive contrast thresholds fire constantly on bright clear days unless uniform upper-horizon tiles are marked UNCERTAIN and cross-checked against neighboring cameras and ego-motion.
  • Checking FULLY_OCCLUDED before BLINDED_GLARE: Direct sun saturates pixels into a flat white sheet that matches naive flatness checks, triggering pointless washer sprays into sun glare unless saturation + sun-angle checks take precedence.
  • Dropping steering torque instantaneously (step to 0 Nm) or cutting adaptive cruise simultaneously: Killing both lateral and longitudinal control at highway speed breaks the lateral-versus-longitudinal fallback hierarchy; radar must sustain safe longitudinal spacing while steering hands off smoothly.
  • Writing high-rate camera ring buffers continuously to flash storage: Continuous video writes burn through automotive eMMC (embedded flash memory) program/erase endurance in months instead of keeping rolling buffers in DRAM and flushing only on state transitions.
  • Tweaking detection thresholds blindly to hide the 60-minute bug: Masking an hourly false positive without plotting uptime_s vs. minute_of_hour and reproducing the exact trigger on a HIL (hardware-in-the-loop) bench leaves latent timing or counter-wrap bugs ticking in production.

Follow-up questions

  • How can the perception health monitor distinguish scene-wide low visibility—such as thick fog or an unlit tunnel—from foreign matter physically coating a camera lens? Combine multi-camera scope, spatial depth gradients, and motion physics. Dense fog and dark tunnels degrade contrast simultaneously across all exterior cameras (front_narrow, front_main, front_wide, and side cameras), whereas mud splatter is localized to specific tiles of one camera or one vehicle side and often shows brownish/opaque color shifts. Even inside thick fog or a dim tunnel, near-field hood/lane markings 5–10 m ahead retain visible edge gradients and exhibit outward optical flow matching CAN speed and yaw rate, whereas mud stuck to glass has zero optical flow (change_1s ~ 0) right across the road ROI and hides close-in vehicles that 77 GHz front radar clearly tracks. Auxiliary context (headlights auto-on, maxed ISP exposure/gain, map tunnel polygons, wiper speed) confirms LOW_CONTRAST_ENV—which still triggers conservative ADAS speed/gap limits (D1/D3) because perception visibility genuinely dropped, while suppressing lens-washer sprays and false "Lens Occluded" fault codes.
  • How would you design on-board circular frame buffers to capture raw pre-fault imagery while protecting embedded flash storage from premature wear-out? Keep all continuous circular buffers strictly in volatile DRAM, never on flash: a 20 s H.265 hardware-encoded context ring at 4 Mbit/s (0.5 MB/s) across all 11 cameras uses just 110 MB of DRAM, while an optional diagnostic 2 s raw 12-bit 8 MP Bayer ring (12 MB/frame @ 5 fps = 120 MB) is enabled in DRAM only for targeted cameras under investigation. Write sequentially to a dedicated f2fs circular flash partition only when a debounced fault fires (30 s x 0.5 MB/s x 3 cameras = ~45 MB encoded clip, plus 120 MB if raw burst is armed = 165 MB), governed by a daily flash-write token budget sized from NAND endurance: a 64 GB automotive eMMC rated at 3,000 program/erase cycles with write amplification (flash controller overhead multiplier) of 3 supports 64 GB x 3000 / 3 = 64 TB lifetime host writes, or ~11.7 GB/day over 15 years across the entire vehicle. Capping the recorder at 2 GB/day allows ~44 encoded video incidents/day (or ~12 raw-burst incidents/day) before falling back to tiny 200 KB metadata/thumbnail snapshots, while deduplicating storm repeats and reporting eMMC health registers (EXT_CSD wear-level indicators) in fleet telemetry.
  • Suppose exterior cameras have compressed-air and washer-fluid nozzles; what trigger conditions, cooldowns, and safety interlocks prevent nuisance sprays from impairing visibility? Trigger cleaning only when cause_hint indicates physical surface matter (STATIC_DIRT or SNOW_ICE)—never on BLINDED_GLARE, LOW_CONTRAST_ENV, or UNAVAILABLE. Use asymmetric hysteresis and escalating actuation: start when weighted_blocked_fraction >= 0.30 persists for 3.0 s (or FULLY_OCCLUDED with static-dirt evidence for 1.0 s), firing a dry compressed-air puff first, escalating to a 0.5 s washer-fluid pulse + clearing air puff if blockage stays >= 0.20 after 3.0 s, and declaring clean only once blockage stays < 0.10 for 2.0 s—enforcing a 30 s cooldown and a hard cap of 3 attempts per 5 minutes before latching a "Please clean camera lens" driver message. To protect driver sightlines and ADAS continuity: use coordinated windshield wiper sweeps rather than auxiliary high-pressure jets for behind-glass forward cameras at highway speed, inhibit cleaning during active lane changes or tight curves, stagger cleaning across redundant forward/surround cameras so backup vision stays clear, check fluid-level and < 2 °C freeze interlocks (air/heater only unless heated fluid is active), and notify the degradation manager 100 ms beforehand so water-droplet frames during the 1.5 s wash/settle window are masked rather than triggering a false takeover.

Follow-up questions

Similar questions

More Rivian interview questions

All 1 Rivian questions →