Skip to content
Charan Kumar Reddy
AI & AgentsData & MLCompleteSynthetic data

Vehicle Telemetry Anomaly Detection

Stateful streaming anomaly detection with ONNX Runtime serving

Anomaly detection on synthetic vehicle telemetry: point and per-vehicle window models, ONNX export, PySpark or pandas micro-batch streaming with carried state, and FastAPI serving.

Trained and evaluated on synthetic telemetry.

F1 of the per-vehicle window model (synthetic test split)
0.962
reports/model_evaluation.json
p50 ONNX Runtime single-event scoring
0.042 ms
reports/benchmark_results.json

The problem

Some telemetry faults are slow drifts that stay inside the fleet's normal range and only show against a vehicle's own history, so detection needs per-vehicle state that survives micro-batches and replays.

The approach

Point and per-vehicle window models are trained with scikit-learn and XGBoost, exported to ONNX, scored in pandas or PySpark micro-batch streaming with carried state, and served through FastAPI.

Architecture

  1. 01

    Synthetic telemetry generator

    data_generator.py runs a seeded vehicle simulation with five single-event fault types and two gradual drift types, and writes streaming JSON Lines files with injected malformed events and duplicates.

  2. 02

    Features and training

    Point features from a single reading and causal per-vehicle EWMA window features feed RandomForest and XGBoost models per feature set, plus an unsupervised IsolationForest baseline, using vehicle-grouped splits and validation-tuned thresholds.

  3. 03

    ONNX export

    Selected models are exported to ONNX at training time with skl2onnx and onnxmltools and checked for score parity against the native models.

  4. 04

    Micro-batch streaming

    A PySpark Structured Streaming engine or a pandas fallback reads files, validates and quarantines bad events, de-duplicates on event_id, scores with the window model while carrying per-vehicle state, and writes atomic per-batch sinks with checkpoints.

  5. 05

    FastAPI serving

    FastAPI serves /predict, /predict-batch and /predict-stream with scikit-learn/XGBoost or ONNX Runtime; /predict-stream returns per-vehicle state for the client to send back.

  6. 06

    Benchmark and reports

    benchmark.py compares a pandas baseline path, a NumPy feature path, the optimized native path and ONNX Runtime, and evaluation, benchmark and streaming reports are committed under reports/.

Key decisions

  • Summarises each vehicle's history in five numbers (EWMA values and a count), so one implementation serves training, streaming and the API, and chunked processing with carried state matches a full pass exactly (tested). The EWMAs are event-indexed, so irregular sampling would need time-based decay.
  • Keeps /predict-stream stateless on the server: the client sends back the state returned with each response, so any instance can serve any request; state is capped at 1,000 vehicles per stream.
  • Writes sink files atomically and names them by batch id, and the local engine commits its processed-file list only after outputs are written, so a batch replayed after a crash overwrites its own output and reproduces the same scores. De-duplication covers each micro-batch, not across batches.
  • Splits train, validation and test by vehicle_id with GroupShuffleSplit and uses only the validation split for early stopping, thresholds and model selection, so no vehicle appears in more than one split.
  • Builds features straight into a NumPy matrix and avoids per-call DataFrame construction and joblib thread-pool start-up; ONNX Runtime runs with one intra-op thread as an edge-like setting. The measured trade-offs are kept: native multi-threaded XGBoost beats single-threaded ONNX on large batches, and ONNX session creation for the forest is slower than joblib.load.
  • Runs Spark scoring and window state on the driver inside foreachBatch so both engines share the same code; this suits a single node but would need executor-side state for a cluster.

Results

  • On the synthetic test split the window model catches gradual faults that the per-event model largely misses, most clearly battery degradation, and raises fewer false alarms.
  • The committed streaming run quarantined exactly the injected malformed events and dropped exactly the injected duplicates.
  • ONNX Runtime decisions agree with the native models on every test-split event in the committed benchmark parity check.
  • The PySpark file-source and checkpoint path runs in Linux CI and is compared against the pandas engine.
Measured results and the files they come from
MetricValueSource
Window RF (synthetic test)F1 0.962 / PR-AUC 0.992reports/model_evaluation.json
ONNX RF single-event0.042 ms p50reports/benchmark_results.json
Streaming run100,500 events; 1,000 quarantined; 500 dupes droppedreports/streaming_summary.md
Unoptimized pipeline single-event36.15 ms p50reports/benchmark_results.json

How it is tested

  • 87 pytest test functions (the README reports 109 collected tests) covering config, the generator, window-feature invariants, preprocessing and every validation rule, prediction parity (optimized vs reference, ONNX vs native), all API endpoints and streaming.
  • Streaming tests cover crash replay reproducing scores, recovery and incremental file pickup, an empty Spark batch keeping state, and Spark-versus-pandas parity.
  • CI runs ruff, ruff format and mypy in strict mode, then the tests on Ubuntu with Python 3.11, Java 17 and PySpark, and fails if any test is skipped so the Spark file-source test always runs.
  • A Docker CI job builds the API image, runs it with Render-like limits (ONNX Runtime, 512 MB, half a CPU, one inference thread) and runs deploy_smoke_test.py against it.

Limits, stated plainly

  • All data is synthetic; faults are clean spikes and linear drifts, and the models have never seen real telemetry.
  • The Kafka source is not implemented; streaming reads files only.
  • No watermark-based reordering of late events, and no cross-batch de-duplication.
  • Benchmarks come from one developer laptop with normal background load; the free Render instance is slower.
  • Dockerfile.spark is not built in CI, and the public demo has no authentication or rate limiting beyond request validation.

Stack

Pythonscikit-learnXGBoostONNX RuntimePySparkpandasFastAPIDocker