Robotaxi Teleoperations Schema and Fleet Stability Pipeline

Medium · System Design · Data Engineer · Onsite

Prompt

You are building core data infrastructure for a driverless ride-hailing service where passengers book point-to-point trips in autonomous vehicles overseen by a centralized remote-operations center. Remote specialists can track each vehicle's live map position, stream real-time exterior camera feeds, and step in with guidance or remote control whenever a vehicle gets blocked or requests assistance.

Each assistance incident progresses through a structured workflow: 1. An autonomous vehicle raises an assistance ticket to remote operations. 2. The ticket enters a routing queue. 3. An on-duty specialist is assigned to handle the ticket. 4. The specialist inspects the scene, provides advisory trajectory guidance, assumes a remote-control lease, escalates to another queue/specialist, or closes the incident as resolved.

Active vehicles on the road always outnumber on-duty specialists, and one specialist handles many vehicles across a shift.

Design two connected systems: 1. Teleoperations warehouse model: Model the entities, table grains, relationships, lifecycle invariants, and metrics required to evaluate both efficiency (queue speed, handle times, staffing utilization) and effectiveness (clean autonomy recovery, repeat-incident rates, safety, and rider impact). 2. Fleet stability data architecture and pipeline: Design the end-to-end data platform that measures autonomous driving reliability across the fleet, detailing telemetry sources, streaming and delayed depot ingestion, storage tiers, transformations, quality gates, normalized stability metrics, and downstream consumers.

Scope & Expectations

  • Establish key non-functional guarantees—keeping analytics isolated from live vehicle actuation, meeting ~5-second live operational freshness alongside ~3-second historical query latency, enforcing rider/employee privacy, and handling late or duplicate telemetry deterministically.
  • Separate the assistance lifecycle into clean multi-grain fact and dimension tables (requests, queue stays, assignments, interventions, control leases, outcomes, operator desk states, and versioned metric/publication metadata) with explicit clock semantics.
  • Define producer and query contracts covering deterministic event deduplication, watermarks, bounded pagination, role-based authorization, and provisional-versus-final dataset states.
  • Show how live cellular streams and delayed depot uploads reconcile through automated quality checks into exposure-normalized fleet stability rollups without replay/backfill jobs polluting live operational views.

Step-by-step walkthrough

  1. Scope, core guarantees, and control-plane isolation

    We are designing two connected data systems for a driverless ride-hailing fleet overseen by remote operations: 1. A teleoperations warehouse schema quantifying efficiency (how fast and at what staffing cost operators handle assistance tickets) and effectiveness (whether remote intervention restored autonomous driving cleanly and safely). 2. A fleet stability architecture and pipeline measuring autonomous driving reliability across software builds, hardware revisions, operating zones, and weather conditions.

    Three core guarantees guide every design choice: 1. Deterministic accuracy across delayed arrivals: Autonomy rollout gates and shift staffing depend on trustworthy numbers. Duplicate cellular packets, clock skew, or depot hard-drive uploads arriving 4–36 hours after a shift must reconcile deterministically without double-counting, and any late backfill or formula change must publish as a new versioned dataset snapshot rather than silently mutating numbers leadership reviewed yesterday. 2. Dual-speed latency SLAs (<= 5 s live operational views, <= 3 s historical slicing): - Live operational monitoring (<= 5 seconds end-to-end freshness): Floor supervisors need live queue depth, unassigned wait times, and active control leases within 5 seconds of an event so they can rebalance queues or pull operators from wrap-up before congestion snowballs. - Historical analytics (<= 3 seconds p95 query latency): Engineers and team leads slicing 30–90 days of teleops SLAs or software release stability by city, shift, or reason code need interactive sub-3-second responses via pre-computed, quality-checked aggregates. 3. Privacy and least-privilege access control: Exterior cameras capture pedestrians, license plates, and riders, while operator metrics reflect individual employee performance. Role-Based Access Control (RBAC) — a security model restricting APIs, rows, and columns by job role — ensures analytical tables store pseudonymous trip_id keys and neighborhood map cells rather than rider identities, gates raw video clips behind audited face/plate-blurred access, and restricts per-operator handle-time drilldowns to authorized team leads.

    System scope and domain rules: - Control-plane isolation: Live WebRTC camera feeds and real-time remote vehicle guidance (< 100 ms round-trip) run on an isolated operational control plane. Analytical pipelines never sit inline with live vehicle actuation — operational services publish lifecycle records asynchronously from local buffers so a Kafka slowdown or warehouse outage can never block an operator from assisting a stuck vehicle. - Domain cardinalities: On-road vehicles vastly outnumber staffed operators; a single help request may traverse multiple queues and operators (shift handoffs or escalations); and vehicle stability spans both operational stability (help requests, stuck events, critical faults, and minimal-risk maneuvers (MRMs) — safety fallbacks where a car pulls over or stops itself) and motion stability (hard braking and high jerk, normalized by autonomous miles or hours driven).

  2. Back-of-the-envelope scale: tiny teleops facts vs. massive fleet telemetry

    Assume a baseline fleet of 1,000 active robotaxis operating 20 hours/day (20,000 vehicle-hours/day, or ~240,000 autonomous miles/day at a 12 mph urban average), raising 0.25 help requests per vehicle-hour with a 3-minute mean handle time:

    1. Teleoperations lifecycle data (small volume — the hard part is exact modeling!)
       - Help requests:          20,000 veh-hr x 0.25         =  5,000 requests/day (~500/hr at peak)
       - Queue & assignments:    ~1.2 placements/assignments  = ~12,000 rows/day
       - Interventions/sessions: ~5 actions per request       = ~25,000 rows/day
       - Operator desk states:   ~60 operators x 100/shift    =  ~6,000 rows/day
       - Total warehouse facts:                               = ~48,000 rows/day (~18M rows/year)
       - Peak event rate:        ~5,000 events/hr (~1.4/s avg, < 25 events/s during storm bursts)
    
    2. Queueing sensitivity at peak (why exact handle-time definitions matter!)
       - Peak workload:          500 requests/hr x 3.0 min    = 25.0 operator-hours of work per hour
       - At 25 operators (100% utilization), queue wait grows without bound!
       - Queueing math (Erlang C) shows 31 operators assign 93.4% of requests within 30 s.
       - If unlogged post-call wrap-up hides +20% true handle time (3.6 min -> 30.0 workload hours),
         those same 31 operators assign only 30.5% of requests within 30 s!
    
    3. Vehicle stability telemetry (high volume + multi-hour offline upload lag!)
       - Live cellular 1 Hz state (pose, speed, accel, odometer):
           1,000 cars x 72,000 s/day                          = 72M rows/day (~22 GB/day raw, ~4 GB Parquet)
       - Discrete vehicle events (mode flips, faults, brakes):
           ~200 events/veh-hr                                 = 4M rows/day (~2 GB/day)
       - Depot SSD bulk logs (100 onboard software modules at 1 Hz):
           1,000 cars x 100 modules x 72,000 s                = 7.2 BILLION raw ticks/day
           Summarized during extraction into 1-min rollups:   = 120M module-minute rows/day
       - Raw camera / LiDAR bags (terabytes per car/day):     Kept in raw S3; analytical tables store
                                                              lightweight `(bag_s3_uri, offset_s)` pointers.
    
    4. Meeting our <= 5 s live and <= 3 s historical SLOs
       - Live <= 5 s:       1,000 cars emit ~1,300 cellular msgs/s (< 1 MB/s), easily processed in-memory
                            by a small stateful stream cluster within 1-2 seconds.
       - Historical <= 3 s: Daily stability aggregates across 10 releases x 50 zones x 4 time bands produce
                            ~2,000 rows/day (< 750k rows/year, < 25 MB columnar) — scanned in < 300 ms!
    
  3. Event ingestion, live state, and historical query contracts

    Explicit API and event contracts decouple operational producers from analytical consumers while guaranteeing deduplication, freshness visibility, and sub-3-second query bounds: - An idempotency key (event_id) is a deterministic unique identifier attached to every event so receiving a retried message twice produces the exact same state as receiving it once. - A watermark is a moving event-time timestamp telling readers that almost all events generated before that moment have been ingested and processed. - Keyset (cursor) pagination passes an opaque page_token encoding the last-seen sort key rather than a SQL OFFSET, preventing skipped or duplicated rows while live queues change.

    1. Lifecycle Event Ingestion Contract: POST /v1/events:ingest (and Kafka envelope)
       Request batch item:
         { "schema_version": "1.3.0",
           "event_id":       "car_12:boot_88:seq_40912",   // deterministic idempotency key
           "producer":       "teleops_control_svc" | "robot_runtime",
           "entity_id":      "req_501",                    // shared request_id or vehicle_id
           "sequence_no":    14,                           // per-entity monotonic counter (detects gaps)
           "event_type":     "help_request.assigned",
           "event_time":     "2026-11-30T13:58:10.120Z",   // source clock (vehicle GNSS or server)
           "software_release": "2026.48.2",
           "payload":        { ... } }
       Per-item response status:
         - ACCEPTED           (persisted to durable raw log; server stamps `server_received_at`)
         - DUPLICATE_IGNORED  (matching `event_id` already seen; HTTP 200 so producer stops retrying)
         - QUARANTINED        (schema or invariant failure routed to dead-letter table with `error_code`)
    
    2. Live Operational State Contract: GET /v1/teleops/live-state
       Query params (bounded):
         site_id (required), queue_id, priority_in, status_in, page_size (max 200), page_token
       Auth: OAuth2 scope `teleops:live:read` restricted to caller's `site_id` (rider PII masked)
       Response:
         { "as_of_server_time":  "2026-11-30T14:00:05.000Z",
           "event_watermark_at": "2026-11-30T14:00:02.400Z",
           "watermark_lag_ms":   2600,                     // SLO <= 5000 ms; flips `freshness_state`
           "freshness_state":    "FRESH",                  // FRESH (<=5s) | STALE_WARNING (>5s)
           "summary": { "waiting_requests": 4, "active_control_sessions": 9,
                        "available_operators": 18, "live_wait_p90_s": 19.4 },
           "open_requests": [ ... ],
           "next_page_token": "eyJwcmlvIjoxLCJxdWV1ZWRfYXQiOi..." }
    
    3. Historical Metrics Query Contract: POST /v1/analytics/metrics:query
       Request (bounded to guarantee <= 3 s p95 latency):
         { "metric_ids":        ["sla_assigned_30s", "repeat_help_10m_rate", "mrm_per_1k_miles"],
           "metric_version":    "v2",                      // pinned version (defaults to active)
           "publication_id":    "pub_2026_11_29_final_01", // optional snapshot pin for audit/gates
           "start_date":        "2026-11-01", "end_date": "2026-11-29",  // max 90d hourly / 365d daily
           "group_by":          ["software_release", "city"],            // allowlisted dimensions only
           "min_quality_state": "FINAL",                   // PROVISIONAL | FINAL
           "page_size": 500, "page_token": null }
       Auth: `fleet:metrics:read` for cohorts; `group_by: ["operator_id"]` requires `teleops:coach:read`
       Response:
         { "publication_id":     "pub_2026_11_29_final_01",
           "metric_versions":    {"sla_assigned_30s": "2.1", "mrm_per_1k_miles": "1.4"},
           "quality_state":      "FINAL",                  // PROVISIONAL | FINAL | QUARANTINED
           "depot_completeness_pct": 99.8,
           "freshness_watermark_at": "2026-11-30T06:15:00Z",
           "rows": [ {"software_release": "2026.48.2", "city": "sf",
                      "mrm_per_1k_miles": 0.27, "numerator": 8, "denominator_miles": 29630.0} ],
           "next_page_token": null }
    
  4. Multi-grain warehouse schema, lifecycle invariants, and clock rules

    We model the warehouse as a star schema — central numerical fact tables (fct_*) linked to descriptive dimension tables (dim_*). - Table grain defines the exact single real-world entity or interval that one row represents; mixing grains in one table causes double-counting or overwritten history. - An accumulating snapshot is a fact table with one row per request whose milestone timestamp columns fill in as the request progresses from creation to resolution. - Slowly Changing Dimension Type 2 (SCD Type 2) tracks historical attribute changes (such as an operator changing teams or a robotaxi getting upgraded LiDAR) by inserting a new row with (valid_from, valid_to) bounds and a surrogate key (*_sk) — a warehouse-generated ID pointing to the exact historical version active when an event happened.

    Help-request state transitions and concrete multi-grain trace (req_501): Suppose car_12 gets blocked by a double-parked truck at 13:58:00. Operator Alice accepts the request, acquires a waypoint guidance session, hits shift end at 14:00:00, and hands off to Bob, who guides car_12 clear at 14:01:20:

    State Machine of a Help Request:
      CREATED --> QUEUED --> ASSIGNED --> IN_PROGRESS (Observe / Advise / Remote Control)
                    ^            ^             |
                    |            +-- HANDOFF --+--> RESOLVED (resumed_autonomy | roadside_assist |
                    +---- ESCALATED (re-queue) -+              trip_cancelled | self_cleared)
    
    Concrete Multi-Grain Rows for `req_501` (why 1 flat table is never enough!):
      fct_help_request (1 row/request):
        [req_501 | car_12 | recv=13:58:00 | queued=13:58:02 | 1st_asgn=13:58:10 | resolved=14:01:20]
      fct_request_queue_entry (1 row/queue stay):
        [q_ent_1 | req_501 | queue=urban_general | prio=P1 | 13:58:02 -> 13:58:10 | exit=assigned]
      fct_request_assignment (1 row/operator assignment):
        [asgn_1  | req_501 | Alice | initial | 13:58:10 -> 14:00:00 (110s) | release=handoff ]
        [asgn_2  | req_501 | Bob   | handoff | 14:00:00 -> 14:01:20  (80s) | release=resolved]
      fct_intervention (1 row/operator action) & fct_control_session (1 row/exclusive control lease):
        [intv_1  | asgn_1  | observe           | 13:58:11 -> 13:58:40]
        [intv_2  | asgn_1  | waypoint_guidance | 13:58:40 -> 13:59:55] -> [ctl_91 | rtt_p50=42ms]
        [intv_3  | asgn_2  | waypoint_guidance | 14:00:03 -> 14:01:15] -> [ctl_92 | rtt_p50=39ms]
        [intv_4  | asgn_2  | resolve           | 14:01:15 -> 14:01:20]
    

    Complete teleoperations entities, relationships, and governance tables:

    Raw & Governance Entities (Owned by Data Platform)
      bronze_teleops_events    Grain: 1 immutable ingested event (`event_id` PK)
      dim_metric_definition    Grain: 1 versioned metric (`metric_id`, `metric_version` PK, `owner_team`,
                                      `numerator_expr`, `denominator_expr`, `sql_git_sha`, `effective_from`)
      ctl_publication_version  Grain: 1 published dataset snapshot (`publication_id` PK, `dataset_name`,
                                      `partition_date`, `quality_state`, `depot_completeness_pct`, `published_at`)
      agg_teleops_15m          Grain: 1 checked 15-min rollup per `(site, queue, reason, publication_id)`
    
    Dimensions (Sourced from Fleet, Workforce, & Autonomy Services)
      dim_vehicle              Grain: 1 robot hardware/config version (`vehicle_sk` PK, `vehicle_id`) [SCD2]
      dim_operator             Grain: 1 operator role/team/tier version (`operator_sk` PK)            [SCD2]
      dim_software_release     Grain: 1 autonomy build (`release_id` PK, `semver`, `rollout_at`)
      dim_reason               Grain: 1 help reason (`reason_code` PK, `category`, `default_priority`)
      dim_location             Grain: 1 map cell (`h3_cell_r8` PK, `zone_name`, `city`)
    
    Core Analytical Fact Tables (Owned by Teleops & Fleet Analytics)
      fct_help_request              1 help request (`request_id` PK; shared with vehicle logs!)
      fct_request_queue_entry       1 stay of 1 request in 1 queue tier (`queue_entry_id` PK)
      fct_request_assignment        1 continuous operator assignment on 1 request (`assignment_id` PK)
      fct_intervention              1 discrete operator action inside an assignment (`intervention_id` PK)
      fct_control_session           1 exclusive remote-control lease on a robot (`control_session_id` PK)
      fct_request_outcome           1 terminal resolution + 10-min post-clear follow-up (`request_id` PK/FK)
      fct_operator_state_interval   1 uninterrupted desk state (`available|handling|wrap_up|break`)
      fct_operator_shift            1 scheduled/worked operator shift (`shift_id` PK)
      fct_trip                      1 passenger ride (`trip_id` PK, nullable FK from `fct_help_request`)
    

    Enforced domain invariants and four-clock temporal semantics: - Invariants: (1) Control mutual exclusion: at most one open fct_control_session may exist per vehicle_id and per operator_id at any instant; (2) Monotonic server order: server_received_at <= first_queued_at <= first_assigned_at <= resolved_at; (3) Clean closure: a request cannot transition to RESOLVED while any control session or assignment remains open; (4) Time conservation: every second between first_queued_at and resolved_at belongs to either a queue entry (waiting) or an assignment (active). - Four distinct timestamps: vehicle_event_time (onboard GNSS clock for physical driving physics), server_received_at (Teleops server monotonic clock — authoritative for queue and operator SLAs so cellular lag never penalizes operators), ingested_at (analytics arrival clock for pipeline lag monitoring), and SCD2 valid_from / valid_to + published_at (for point-in-time attribution and audit reproducibility).

  5. Deep dive 1: Teleoperations efficiency & effectiveness metrics (and time-accounting traps)

    Category        Metric                            Exact Definition
    ---------------------------------------------------------------------------------------------------------
    Efficiency      Queue Wait (p50, p90, p99)        `SUM(exited_at - entered_at)` in `fct_request_queue_entry`
                    Initial SLA Attainment (<= 30 s)  Share of requests with first assignment <= 30 s after queue
                    Time to First Intervention        `first_intervention_at - first_assigned_at`
                    End-to-End Time to Resolve        `resolved_at - server_received_at` (server clock only!)
                    Handle Time per Request           `SUM(released_at - assigned_at)` across assignments
                    Operator Occupancy                `(handling_s + wrap_up_s) / (handling_s + wrap_up_s + available_s)`
                    Throughput per Staffed Hour       `COUNT(resolved requests) / staffed_operator_hours`
    
    Effectiveness   Autonomous Recovery Rate          Share of resolved requests with `outcome = resumed_autonomy`
                    10-Minute Repeat Help Rate        Share where same robot requests help again within 10 min & 200 m
                                                      (catches hasty "band-aid" clears that immediately re-stuck!)
                    Control Safety-Trip Rate          Share of `fct_control_session` ending in `safety_envelope_trip`
                    Escalation Rate                   Share of requests re-queued to a specialist tier
                    Passenger Ride Impact             Added `trip_delay_s` and cancellation rate on affected `fct_trip`
    

    Five time-accounting traps that break naive teleoperations dashboards:

    1. Overlapping multi-vehicle monitoring (> 100% occupancy bug): If Alice monitors Car A (10:00–10:06, 6 min) and briefly overlaps on Car B (10:03–10:09, 6 min), summing assignment lengths gives 12 busy min / 9 clock min = 133% occupancy! Busy wall-clock time must take the union of merged intervals (or read non-overlapping desk states from fct_operator_state_interval):
    Car A:  |=========|          (0s .. 360s)
    Car B:       |=========|     (180s .. 540s)
    Union:  |==============|     Merged busy time = 540s (9 min), NOT 720s (12 min)!
    
    def merged_busy_seconds(intervals):
        """Return total wall-clock seconds covered by at least one (start_s, end_s) interval."""
        if not intervals:
            return 0
    
        sorted_spans = sorted(intervals)
        total_seconds = 0
        cur_start, cur_end = sorted_spans[0]
    
        for start, end in sorted_spans[1:]:
            if start > cur_end:
                # Non-overlapping gap: bank the finished interval and start a fresh one
                total_seconds += cur_end - cur_start
                cur_start, cur_end = start, end
            elif end > cur_end:
                # Overlapping interval extends the active end boundary
                cur_end = end
    
        total_seconds += cur_end - cur_start
        return total_seconds
    
    1. Right-censoring survivorship bias on live queue waits: Right-censoring occurs when still-open events lack a completion timestamp and accidentally drop out of a query. If a live dashboard computes p90(first_assigned_at - first_queued_at) only on already-assigned rows, then during an understaffed spike where 40 cars have sat unassigned for 8 minutes (first_assigned_at IS NULL), all 40 vanish and the dashboard falsely reports a healthy 12 s wait! Live queries must include still-waiting requests at now() - first_queued_at:
    -- Live queue wait health including still-unassigned ("right-censored") requests
    WITH live_waits AS (
      SELECT
        first_queued_at,
        first_assigned_at,
        resolved_at,
        initial_queue_wait_s,
        -- If unassigned: wait ended at `resolved_at` (self-cleared) or is STILL ticking at `now()`!
        COALESCE(
          initial_queue_wait_s,
          EXTRACT(EPOCH FROM (COALESCE(resolved_at, now()) - first_queued_at))
        ) AS effective_wait_s
      FROM fct_help_request
      WHERE first_queued_at >= now() - interval '6 hours'
    )
    SELECT
      date_trunc('hour', first_queued_at)                            AS hour_bucket,
      COUNT(*)                                                       AS total_requests,
      percentile_cont(0.90) WITHIN GROUP (ORDER BY effective_wait_s) AS wait_p90_s,
      -- Unassigned requests <= 30s old return NULL so AVG ignores undecided in-flight requests
      AVG(CASE
            WHEN initial_queue_wait_s <= 30 THEN 1.0
            WHEN effective_wait_s > 30 THEN 0.0
          END)                                                       AS sla_30s_rate
    FROM live_waits
    GROUP BY 1
    ORDER BY 1;
    
    1. Never subtract across unsynchronized clocks: Subtract server clock from server clock (resolved_at - server_received_at), and measure cellular uplink delay (server_received_at - vehicle_event_time) separately.
    2. Never average percentiles: Weekly p90 wait cannot be computed by averaging seven daily p90 numbers — aggregate from request rows or merge t-digests (compact data structures that summarize value distributions so percentiles combine accurately across partitions).
    3. Control for reason-code mix shift: Heavy rain shifts requests toward complex construction/flooding scenarios; stratify handle time by dim_reason.category before evaluating operator speed.
  6. End-to-end architecture: live monitoring and fleet stability lakehouse

    To measure both teleoperations and fleet-wide vehicle stability without touching live vehicle-control channels, we combine six data sources into a unified streaming + Medallion Lakehouse architecture: - A transactional outbox writes each teleops lifecycle event into a local database table inside the same atomic commit as the operational state change, then relays it asynchronously to Kafka so events are never lost and never block live vehicle control. - Change Data Capture (CDC) tails committed row changes from external service databases (passenger rides and fleet maintenance) into Kafka without requiring custom application hooks. - A Medallion Lakehouse organizes open Apache Iceberg tables on S3 into Bronze (immutable raw payloads), Silver (validated, deduplicated entities and continuous intervals), and Gold (quality-checked business facts and aggregates), paired with a columnar OLAP (Online Analytical Processing) store (ClickHouse) for sub-second live queries.

      [ Robotaxi Fleet ] <==== Isolated <100 ms WebRTC Video & gRPC Control ====> [ Teleops Control Plane ]
             |             (SAFETY-CRITICAL PATH: zero synchronous analytics calls!)         |
             | 1. Async cellular telemetry         2. Depot Wi-Fi/10GbE SSD upload           | 3. Transactional
             |    (1 Hz state + discrete events)      (4-36h lag, 100% lossless bags)        |    Outbox relay
             v                                               v                               v
      [ Ingest Gateway ]                         ( S3 Raw Sensor & Module Bags )      ( Kafka: teleops.* )
      (Auth, schema check)                                   |                               |
             |                                               v                               |
             v                                    [ Spark Bag Extractor ]                    |
      ( Kafka: vehicle.* ) <---- 4/5. Ride &      ( Discrete events + 1-min                  |
             |         |         Maint. CDC         100-module health rollups )              |
             |         +-------------------------------------+-------------------------------+
             |                                               |
             v                                               v
      [ Flink Event-Time Reconciler ]             +-------------------------------------------------------+
      (Dedup `event_id`, 2s watermark,            |        Apache Iceberg Lakehouse on S3                 |
       open-request & session state)              |  BRONZE: Immutable raw events + Quarantine DLQ        |
             |                                    |     |    (Validation, `event_id` dedup, depot merge)  |
             v (<= 5s end-to-end freshness)       |     v                                                 |
      [ Live State Store (ClickHouse/Redis) ]     |  SILVER: Canonical `fct_*` & `fct_vehicle_mode_*`     |
             |                                    |     |    (Write-Audit-Publish staging checks)         |
             v                                    |     v                                                 |
      [ Live State API ]                          |  GOLD:   Checked `agg_*` + `ctl_publication_version`  |
      (`GET /live-state`)                         +-------------------------------------------------------+
             |                                               |                          ^
             |                                               v (<= 3s p95 queries)      | Isolated branch:
             +---> [ Observability & RBAC Gateway ] <--- [ Semantic Metrics API ]       | Replay / Backfill
                   (5s lag SLO, 3s query SLO, PII/video   (Pins `metric_version` &      | reads Raw Bronze
                    access audit, quarantine alerts)       `publication_id` for BI/ML)  +--(never live!)
    
  7. Transformations: turning raw vehicle telemetry into canonical stability facts

    Scheduled idempotent Spark/SQL jobs reconcile each event-date partition from Bronze through Silver to Gold in six deterministic steps (adding 6th source context: hourly weather feeds and H3 spatial index cells — uniform hexagonal map neighborhoods that standardize spatial grouping):

    1. Deduplicate Bronze into Silver (silver_vehicle_events): Partition by event_id = (vehicle_id, boot_id, seq). When both the live cellular copy and the delayed depot SSD copy exist, retain the depot copy (which carries richer onboard diagnostic context) while preserving the earliest ingested_at timestamp.
    2. Reconstruct continuous vehicle mode intervals (fct_vehicle_mode_interval): Stitch autonomy_mode_changed events (autonomous, teleop_guided, minimal_risk, manual_driver, parked) into non-overlapping (start_time, end_time, mode, software_release) intervals per robot. Any unexplained telemetry silence > 5 seconds becomes an explicit mode = 'unknown' interval so missing coverage is measured rather than hidden.
    3. Compute true driving exposure (fct_vehicle_exposure_hourly): Slice mode = 'autonomous' intervals across hour boundaries and H3 map cells, deriving autonomous_miles from wheel/inertial odometer deltas — never raw GPS point-to-point distances, which accumulate phantom miles while parked next to tall buildings due to satellite multipath bounce!
    4. Point-in-time ("as-of") hardware attribution: Join each event and exposure slice against SCD Type 2 dim_vehicle bounds so mid-month sensor swaps never rewrite earlier weeks:
    -- Attribute each vehicle event to the exact hardware revision installed at `event_time`
    SELECT
      e.event_id,
      e.vehicle_id,
      e.event_time,
      e.event_type,
      e.software_release,
      v.vehicle_sk,
      v.hardware_rev
    FROM silver_vehicle_events AS e
    JOIN dim_vehicle AS v
      ON v.vehicle_id = e.vehicle_id
     AND e.event_time >= v.valid_from
     AND e.event_time <  COALESCE(v.valid_to, TIMESTAMP '9999-12-31 00:00:00');
    
    1. Collapse fault storms into discrete episodes (fct_fault_episode): A loose connector can emit CAMERA_FRAME_DROP 10,000 times in two minutes. Grouping contiguous raises until fault_cleared into 1 fault episode prevents one noisy sensor from distorting fleet failure rates 1,000x.
    2. Materialize additive Gold rollups (agg_stability_daily): Group by (event_date, software_release, hardware_rev, city, h3_zone, time_of_day_band, weather_bucket, publication_id) and store raw numerators and raw denominators as separate additive columns (help_request_cnt, mrm_cnt, stuck_cnt, hard_brake_cnt, autonomous_miles, autonomous_hours, depot_completeness_pct) — never pre-divided ratios alone.
  8. Deep dive 2: Fair fleet stability metrics, exposure normalization, and statistical noise

    Layer               Stability Metric                          Numerator                        Denominator (Exposure)
    ----------------------------------------------------------------------------------------------------------------------
    Operational         Help Requests per 1,000 Autonomous Miles  `COUNT(help_requested)`          `autonomous_miles / 1000`
    Stability           Stuck Events per 100 Autonomous Hours     `COUNT(stuck_detected)`          `autonomous_hours / 100`
                        Minimal-Risk Maneuvers (MRMs) / 1k Miles  `COUNT(enter minimal_risk)`      `autonomous_miles / 1000`
                        Critical Fault Episodes / 100 Hours       `COUNT(episodes severity >= P1)` `powered_on_hours / 100`
                        Module Crashes per 100 Autonomous Hours   `COUNT(module_restart)`          `autonomous_hours / 100`
    Motion Stability    Hard Brakes per 1,000 Autonomous Miles    `COUNT(decel > 4.0 m/s^2)`       `autonomous_miles / 1000`
                        High-Jerk Events per 1,000 Miles          `COUNT(|jerk| > 5.0 m/s^3)`      `autonomous_miles / 1000`
    Fleet Readiness     Autonomy Fleet Availability (%)           `in_service_autonomous_hours`    `scheduled_service_hours`
    

    Four statistical safeguards keep release comparisons honest: 1. Ratio of sums, never mean of per-vehicle ratios:

    Car A drove 1,000 miles with 1 hard brake  ->   1.0 per 1,000 miles
    Car B drove     2 miles with 1 hard brake  -> 500.0 per 1,000 miles (pulled back into depot)
    
    WRONG (Mean of per-car ratios): (1.0 + 500.0) / 2       = 250.5 hard brakes / 1,000 miles!
    RIGHT (Ratio of sums):          (1 + 1) / (1002 / 1000) =   2.0 hard brakes / 1,000 miles!
    
    Storing separate additive `numerator` and `denominator` columns ensures `SUM(mrm_cnt) / (SUM(autonomous_miles) / 1000.0)` rolls up accurately across any slice.
    
    1. Stratify against Simpson's paradox (mix shift): Simpson's paradox is a statistical reversal where an aggregate rate misleads because two cohorts ran under different operating mixes. Canary builds often launch on quiet daytime suburban routes; re-weighting both releases across identical (h3_zone x time_of_day_band x weather_bucket) exposure weights prevents easy-route bias.
    2. Require Poisson confidence intervals for rare safety events: Rare events like MRMs follow a Poisson process (a probability model for independent rare counts over continuous distance or time). If Production logs 120 MRMs in 300,000 miles (0.40 / 1k mi) and a Canary logs 8 MRMs in 30,000 miles (0.27 / 1k mi — seemingly 33% better!), testing Canary's event share (8 / 128) against its mileage share (30k / 330k = 1/11) gives two-sided p = 0.35 — indistinguishable from coin-flip luck! Release gates must check confidence bounds, not raw point drops.
    3. Split mid-shift over-the-air (OTA) updates: Because software_release is stamped on every event envelope, fct_vehicle_mode_interval splits exposure cleanly at the exact minute of an OTA upgrade.
  9. Deep dive 3: Late depot data, Write-Audit-Publish quality gates, and replay boundaries

    Handling multi-hour offline depot uploads without silent metric drift: - Explicit quality state (PROVISIONAL vs. FINAL): Every Gold row carries depot_completeness_pct (the share of active vehicle-hours whose depot SSD logs have reconciled). Live and same-day views surface quality_state = 'PROVISIONAL' badges; automated Canary Release Gates require quality_state = 'FINAL' (depot_completeness_pct >= 99.5%). - 72-hour rolling restatement window + immutable publications: Daily partitions re-materialize as depot uploads trickle in over 4–36 hours, locking at 72 hours under a recorded publication_id in ctl_publication_version. If a stranded robotaxi uploads 5 days late, engineers publish a new publication_id (SUPERSEDED pointer on the old snapshot) so historical safety decks stay 100% reproducible.

    Write-Audit-Publish (WAP) quality gates: Write-Audit-Publish writes candidate Silver/Gold partitions to an isolated Iceberg staging branch, runs automated checks, and atomically fast-forwards the main pointer only when every check passes:

    Quality Gate           Concrete Assertion                                     Failure Action
    -----------------------------------------------------------------------------------------------------------
    Schema & Physics       Valid registry version; `0 <= speed_mps <= 45`;        Route bad records to Quarantine
                           lat/lon inside metro polygon; no future timestamps     DLQ; page on-call if > 0.1%.
    Uniqueness & State     `event_id` unique in Silver; `request_id` unique in    Abort publish immediately!
    Invariants             `fct_help_request`; <= 1 active control lease/robot
    Mode Continuity        Per robot-day, mode intervals never overlap and        Hold `FINAL` promotion if
                           `unknown` telemetry gap share < 1.0%                   fleet-wide unknown > 0.5%.
    Cross-Source           1) Cellular miles vs. Depot SSD miles within 1.0%      Block publish! Catches silent
    Reconciliation         2) >= 99.5% of robot `help_requested` events match a   packet drops or broken teleops
                              `request_id` in `fct_help_request`                  outbox relays!
    Zero-Drop Parser       Non-zero fault/brake rates vs. trailing 28-day band    Page on-call (0 faults signals
    Check                                                                         a broken parser, not perfection!).
    

    Strict replay and backfill isolation boundary: When backfilling a new metric version (stuck_rate_v2) or replaying after a parser bug fix, jobs read immutable Bronze S3 logs into a sandboxed backfill_<run_id> Iceberg branch — never pushing historical events back through the live Kafka/ClickHouse < 5 s state path (which would trigger false live pages and corrupt open-queue counters) and never overwriting locked FINAL snapshots in place.

  10. Downstream consumers, observability, scaling, and key trade-offs

    Downstream consumers served by the platform: - Teleops Floor Supervisors (<= 5 s freshness): Poll GET /v1/teleops/live-state for open queue SLAs, right-censored wait spikes, and operator occupancy by site. - Operations Team Leads (<= 3 s historical queries): Review shift coaching scorecards (fct_request_assignment, fct_intervention, 10-min repeat help rate) gated behind teleops:coach:read RBAC. - Autonomy Release Gates: Query FINAL agg_stability_daily snapshots (publication_id pinned) with stratified Poisson confidence intervals before expanding a canary rollout. - Workforce Planners: Multiply forecasted fleet miles by help_requests_per_1k_miles per (city, hour, weather) to schedule operator shifts via Erlang C queueing models. - Autonomy ML & Triage Engineers: Filter Silver fct_fault_episode or stuck_detected rows and follow (bag_s3_uri, offset_s) pointers to blurred camera/LiDAR clips with every access logged in the privacy audit trail.

    Observability, failure recovery, and 10x scaling (to 10,000+ robotaxis): - Pipeline observability: Dashboards and pages track watermark_lag_ms (alerting before breaching the 5 s live SLO), p95 query latency against the 3 s historical SLO, Quarantine DLQ rate, unclosed help_request anomalies (> 30 min open), and vehicle clock drift (detected whenever minimum server_received_at - vehicle_event_time turns negative, flagging drifted clocks > 2 s). - Scaling & storage layout: Partition Silver/Gold Iceberg tables by event_date, cluster (Z-order) by (vehicle_id, event_type), run hourly small-file compaction on streaming partitions, and keep 100-module 1 Hz diagnostics summarized into 1-minute rollups (60x row reduction). If bad metric SQL slips past review, Iceberg snapshot rollback restores clean dashboards in seconds.

    Summary of core trade-offs: - Async outbox off the control path vs. synchronous logging: Guarantees analytics failures never endanger live vehicle control, accepting 1–3 seconds of asynchronous relay lag well inside our 5-second live freshness target. - Multi-grain teleops facts (request, queue_entry, assignment, intervention, control_session) vs. one flat request table: Accurately captures escalations, shift handoffs, control mutual exclusion, and true occupancy, hiding join complexity behind the Semantic Metrics API. - Dual cellular + depot SSD ingestion with versioned PROVISIONAL / FINAL publications: Delivers sub-5-second operational visibility and 100%-complete safety numbers within 36 hours, trading pipeline deduplication and explicit quality-state badges for zero silent historical drift.

Intuition & how it works

Think of designing data for autonomous robotaxi teleoperations and fleet stability like building analytics for both a 911 dispatch center and an airline's flight-safety board at the same time — without ever getting in the way of a live rescue. The 911 dispatch center (teleoperations) handles relatively few calls (~5,000 help requests per day for 1,000 robotaxis), so data volume is small; the real challenge is sub-5-second live visibility and exact credit/time accounting when requests re-enter queues on escalation, hand off between operators at shift change, or briefly overlap across vehicles. Meanwhile, the flight-safety board (vehicle stability) processes billions of onboard health and motion ticks per day arriving across two paths: a live cellular stream (arrives in seconds, but drops packets inside tunnels) and end-of-shift depot solid-state drive (SSD) uploads (arrives 4–36 hours later, 100% lossless).

A naive design puts a single operator_id column on one flat help_requests table, writes analytics synchronously from the live control server, and counts raw fault events directly from the cellular stream. That breaks safety, accuracy, and fairness all at once: synchronous logging risks stalling live vehicle control if the warehouse hiccups; a single operator_id erases shift handoffs, escalations, and idle available time needed for staffing occupancy; and counting raw live-stream faults misses tunnel blackouts while making a growing fleet look "less stable" simply because it drove more miles! Instead, we isolate analytical pipelines completely from live vehicle-control channels, capture teleoperations in a multi-grain star schema (a warehouse layout of central numerical fact tables linked to descriptive dimension tables, with separate table grains — what one row represents — for requests, queue entries, assignments, interventions, control sessions, and desk-state intervals), and join it via a shared request_id to a Medallion Lakehouse (an open Apache Iceberg storage layout refining Bronze raw logs -> Silver deduplicated intervals -> Gold exposure-normalized aggregates) backed by versioned dataset publications.

Trace one stuck incident (req_501 on car_12 running software 2026.48.2) end to end: 1. Safety-isolated event emission (13:58:00): Blocked by a double-parked truck, car_12 initiates request_id = 'req_501' (server_received_at = 13:58:00, queued_at = 13:58:02). Live WebRTC video and guidance flow over an isolated < 100 ms control plane, while lifecycle events relay asynchronously via a transactional outbox (a local database table committed atomically with operational state and streamed to Kafka). 2. Sub-5-second live state & multi-grain capture (13:58:10–14:01:20): Operator Alice accepts req_501 at 13:58:10 (8 s queue wait), runs a waypoint guidance lease (ctl_91), hands off at shift end 14:00:00 (110 s handled), and Bob finishes guiding car_12 clear at 14:01:20 (80 s handled; 200 s end-to-end from server receipt). Stateful stream reconciliation updates ClickHouse within <= 5 seconds for floor managers and records 1 row in fct_help_request, 1 row in fct_request_queue_entry, 2 rows in fct_request_assignment, 4 rows in fct_intervention, and 2 rows in fct_control_session. 3. Provisional live stability (14:02): Cellular telemetry lands in Silver and Gold tables tagged quality_state = 'PROVISIONAL' (depot_completeness_pct = 0%) so operations engineers can query same-day downtown stuck trends in <= 3 seconds. 4. Final depot reconciliation (22:30): car_12 docks at the depot and uploads its lossless SSD bag. Spark deduplicates on deterministic event_id = (vehicle_id, boot_id, seq), computes exact wheel-odometer miles, passes Write-Audit-Publish checks (verifying req_501 matches across vehicle and teleops tables and no robot held two simultaneous control leases), and publishes an immutable FINAL snapshot (publication_id = 'pub_2026_11_30_final_01') crediting 1 help request / 142.6 autonomous miles.

Key trade-offs

  • Asynchronous outbox off the control path vs. synchronous analytics writes. Decoupling event ingestion via local ring buffers and a transactional outbox guarantees an analytics outage can never block an operator rescuing a vehicle, trading 1–3 seconds of relay delay that still fits comfortably inside our <= 5-second live freshness SLO.
  • Multi-grain teleops facts (request, queue_entry, assignment, intervention, control_session, state_interval) vs. one flat help_requests table. Separating grains enforces domain invariants (such as mutual exclusion of active control leases) and preserves re-queues, shift handoffs, and idle availability, trading multi-table joins that we encapsulate behind a governed Semantic Metrics API.
  • Accumulating snapshot + immutable Bronze log vs. append-only events alone. Maintaining an accumulating snapshot (one row per request_id updated as milestones arrive) plus pre-computed checked aggregates lets historical SLA queries finish in <= 3 seconds without self-joining raw events, while keeping immutable Bronze payloads underneath makes metric backfills trivial.
  • Dual-path telemetry (cellular stream + depot SSD upload) with versioned publications vs. single-path ingestion. Merging fast cellular events with delayed depot bags gives both sub-5-second operational awareness and 100%-complete release-gate metrics within ~36 hours, at the cost of event_id deduplication, a 72-hour restatement window, and explicit PROVISIONAL vs. FINAL quality badges tracked in ctl_publication_version.
  • Summarizing 1 Hz onboard module health into 1-minute rollups + S3 clip pointers vs. loading all raw ticks into SQL. Aggregating 100 software modules per car during Spark extraction cuts 7.2 billion ticks/day down to 120 million rows/day (60x cheaper and faster), while (bag_s3_uri, offset_s) pointers still let engineers inspect sub-second raw logs behind privacy-audited Role-Based Access Control (RBAC) (permissions scoped to job role).
  • Write-Audit-Publish (WAP) quality gates + isolated backfill branches vs. direct in-place overwrites. Staging new Silver/Gold partitions on an isolated Iceberg branch before moving the live pointer prevents duplicate keys, broken outbox relays, or historical replays from ever corrupting executive dashboards or firing false live pages, trading a few minutes of batch validation latency.

Common mistakes

  • Putting analytics or Kafka acks on the synchronous vehicle-control or video path. Any broker pause or schema error could stall remote vehicle assistance; operational control and analytics must be decoupled asynchronously.
  • Storing a single operator_id and queued_at on fct_help_request with no queue, assignment, or control-session history. That blames or credits 100% of a 20-minute escalated request to whichever specialist clicked "Resolve" at the end and hides multiple control handoffs.
  • Summing raw assignment durations to compute operator occupancy. When an operator monitors two vehicles concurrently for a few minutes, naive sums exceed 100% occupancy; always compute the union of overlapping intervals or sum non-overlapping fct_operator_state_interval rows.
  • Computing live queue wait percentiles (p90) only over already-assigned requests. That introduces right-censoring (a survivorship bias where still-waiting requests have first_assigned_at IS NULL and drop out of the query), making the live dashboard look greenest during the worst staffing meltdowns!
  • Averaging per-vehicle failure rates instead of dividing SUM(events) / SUM(autonomous_miles). A robotaxi pulled back into the depot after 1 fault in 2 miles (500 / 1,000 miles) blows up an unweighted mean across vehicles; always store additive numerators and denominators separately.
  • Promoting a canary software release on raw point-estimate drops without stratifying or checking statistical noise. Canary cars often run easier daytime suburban shifts — causing Simpson's paradox (where unequal operating mixes reverse the apparent winner) — and rare events like minimal-risk maneuvers carry wide Poisson variance on small mileage samples.
  • Overwriting dim_vehicle or dim_operator in place instead of using Slowly Changing Dimension Type 2 (SCD Type 2). Without SCD Type 2 (valid_from, valid_to) version rows, upgrading a vehicle's LiDAR today retroactively rewrites last month's faults onto the new hardware, and replaying backfills directly into the live operational store triggers false pager storms.

Follow-up questions

  • How would you leverage this schema to size hourly operator staffing shifts without exposing individual employee performance data to workforce planners? Forecast expected hourly arrivals by multiplying planned autonomous miles per (city, hour, weather) by recent help_requests_per_1k_miles, and pull site-level mean_handle_s (active handling plus post-call wrap-up, queried at team grain so planners do not need individual HR access) from fct_operator_state_interval. Establish an analytical staffing baseline with the Erlang C queueing formula — a mathematical queueing model for n parallel servers handling random arrivals at offered workload a = arrivals_per_sec * mean_handle_s Erlangs (for example, 500 requests/hr * 180 s = 25.0 Erlangs requires n = 31 operators to assign 93.4% of requests within 30 seconds at 81% occupancy) — then add a buffer by replaying bursty multi-car rain/construction spikes through a discrete-event simulator.
import math


def erlang_c_wait_prob(num_operators, offered_load_erlangs):
    """Probability an arriving help request must wait in queue (n > a > 0)."""
    # Compute 1 / Erlang-B iteratively so large fleets never overflow floating point
    inv_erlang_b = 1.0
    for k in range(1, num_operators + 1):
        inv_erlang_b = 1.0 + (k / offered_load_erlangs) * inv_erlang_b

    erlang_b = 1.0 / inv_erlang_b
    numerator = num_operators * erlang_b
    denominator = num_operators - offered_load_erlangs * (1.0 - erlang_b)
    return numerator / denominator


def share_assigned_within_sla(num_operators, offered_load_erlangs, sla_s, mean_handle_s):
    """Fraction of requests assigned within `sla_s` seconds under M/M/n queueing."""
    prob_wait = erlang_c_wait_prob(num_operators, offered_load_erlangs)
    decay = math.exp(-(num_operators - offered_load_erlangs) * sla_s / mean_handle_s)
    return 1.0 - prob_wait * decay


# Peak check: 500 req/hr * 180s = 25 Erlangs -> n=30 gives 89.1%, n=31 gives 93.4% <= 30s!
  • Three days into a canary rollout, a new autonomy build logs 33% fewer minimal-risk maneuvers per 1,000 miles than production (0.27 vs. 0.40). Should you approve full fleet deployment? Not yet — check dataset finality, exposure mix, statistical power, and guardrail metrics first. Verify quality_state = 'FINAL' (depot_completeness_pct >= 99.5%) on both cohorts, then check sample size: if Production logged 120 MRMs in 300,000 miles and Canary logged 8 MRMs in 30,000 miles, an exact conditional binomial test yields two-sided p = 0.35, meaning an apparent 33% drop is easily random Poisson noise on just 8 events! Stratify and re-weight both releases across identical (h3_zone x time_of_day x weather) cells, confirm guardrail metrics (help_requests_per_1k_miles, 10-min repeat help rate, hard_brakes_per_1k_miles) did not regress, and accumulate more randomized miles under a sequential test (a pre-registered statistical boundary that allows daily safety checks without inflating false positives).
  • Suppose engineering tightens the motionless threshold for stuck_detected from 60 seconds to 45 seconds. How do you roll out that definition change without corrupting past executive reports or disrupting the 5-second live view? Register stuck_rate_v2 alongside v1 in dim_metric_definition rather than mutating SQL in place, and backfill historical partitions by reading immutable Bronze state_sample_1hz logs into an isolated backfill_stuck_v2 Iceberg branch so replay traffic never touches the live ClickHouse state store or overwrites prior FINAL publication_id snapshots. Once Write-Audit-Publish checks pass, publish the new v2 series side by side with v1 for a two-week transition window so executives and anomaly alerts can re-baseline against the expected ~15–25% higher sensitivity before deprecating v1 with a permanent cutover annotation.

Follow-up questions

Similar questions

More Zoox interview questions

All 22 Zoox questions →