Skip to content

devansh-125/Sipra2.0

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

55 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš‘ Sipra

Autonomous AI Orchestrator for Bio-Logistics

Built for Google Solutions Challenge 2026.

Coordinating emergency medical transport β€” organs, vaccines, blood β€” with zero human dispatcher in the loop.

Go Next.js Python PostGIS Redis Docker


πŸ“– Table of Contents

  1. The Problem
  2. The Solution
  3. Key Features
  4. Tech Stack
  5. System Architecture
  6. Data Flow Diagrams
  1. Edge Cases
  2. Future Improvements

🩺 The Problem

Emergency medical cargo lives or dies inside a golden-hour deadline β€” the narrow window during which an organ remains transplantable, a vaccine remains potent, or a blood unit remains usable.

Today's logistics stack fails this window in three places:

Pain Point Today's Reality Cost
Dispatch Manual phone-tree between hospital, ambulance, partner fleets 3 – 8 minutes lost per incident
Corridor visibility Partner fleets (Uber, Swiggy, food delivery) have zero awareness of the ambulance's path Every red light shared with civilian traffic
Failsafe If the route slips past breach, the only fallback is "call a helicopter" Often impossible inside city limits

Sipra fixes that loop in software.


πŸ’‘ The Solution

Sipra is an event-driven AI orchestrator built on three core pillars that operate concurrently and autonomously β€” no human dispatcher required.


Pillar 1 β€” B2B Exclusion Corridor (Live, Working βœ…)

Every time a GPS ping arrives, Sipra recomputes a 2 km rolling exclusion corridor around the ambulance's travel path using PostGIS ST_Buffer(ST_MakeLine(...), 2000m). That polygon is immediately:

  • Broadcast over WebSocket to the Mission Control dashboard (Deck.gl map, pulsing overlay).
  • Fan-out via HMAC-signed webhooks to every registered B2B partner β€” Uber, Swiggy, food delivery fleets, or any logistics operator subscribed to the system.

Partner fleets receive a compact GeoJSON polygon and can reroute their drivers before they physically enter the corridor. This is the core B2B value proposition: partner companies integrate once via webhook, and Sipra continuously keeps them informed of the live ambulance path. No polling, no phone calls, no manual dispatcher.

Ambulance ping β†’ PostGIS ST_Buffer(2km) β†’ versioned corridor row
                                         β†’ WS dashboard (real-time map)
                                         β†’ HMAC POST to Fleet Partner A
                                         β†’ HMAC POST to Fleet Partner B
                                         β†’ HMAC POST to Fleet Partner N

The corridor is versioned and history-preserving β€” old versions are stamped valid_until = NOW() rather than overwritten. This means the bounty engine can later verify which drivers were inside the corridor at claim time, using the correct historical polygon.


Pillar 2 β€” Drone Failsafe (Live, Working βœ…)

Every 10 seconds, the Risk Monitor evaluates every active trip:

  1. Fetches the latest GPS ping and the trip's golden-hour deadline.
  2. Calls the AI Brain (POST /predict) β€” a Python FastAPI service that queries Google Routes for live traffic ETA, applies an OpenWeatherMap weather factor, and runs a logistic-sigmoid to produce a breach_probability.
  3. If will_breach == true, the Risk Monitor autonomously transitions the trip to DroneHandoff, calls the drone dispatch API, and broadcasts HANDOFF_INITIATED to the dashboard and all WebSocket clients.

No human approves the drone call. The system makes the decision, executes it, and notifies all parties in the same 10-second cycle. The drone dispatch mock returns a drone_id and eta_seconds; the dashboard renders a HandoffOverlay with the incoming drone's ETA.

Risk Monitor tick
  β†’ AI Brain: breach_probability = sigmoid((deadline - eta) / 300s)
  β†’ if breach: trip.TransitionTo(DroneHandoff)
             β†’ POST /dispatch β†’ drone_id + eta_seconds
             β†’ BroadcastHandoffInitiated β†’ dashboard overlay

Pillar 3 β€” Async Pipeline (Never Blocks βœ…)

The ingest hot path returns 202 in under 5 ms regardless of what the corridor engine, AI brain, or webhook pool are doing. Three independent tickers β€” 5 s flush, 10 s risk β€” decouple every stage so a slow partner webhook or a stalled Postgres batch never delays the next ambulance ping.


✨ Key Features

  • 🟒 Sub-5 ms ingest hot path β€” POST /pings returns 202 immediately; Redis is the buffer, Postgres flushes every 5 s.
  • 🟒 Versioned PostGIS corridors β€” ST_Buffer(ST_MakeLine(...)) recomputed per flush; old rows stamped valid_until (history-preserving, never UPDATE).
  • 🟒 Real-time WebSocket fan-out β€” 7 envelope types broadcast over /ws/dashboard with non-blocking per-client buffers.
  • 🟒 B2B webhook dispatcher β€” bounded worker pool, HMAC-signed payloads, mock partner verifies signatures end-to-end.
  • 🟒 Deterministic AI brain β€” Python FastAPI: Google Routes + OpenWeatherMap β†’ logistic-sigmoid breach probability.
  • 🟒 Drone failsafe β€” Risk Monitor transitions InTransit β†’ DroneHandoff, calls drone dispatch, broadcasts to dashboard.
  • 🟒 Surge-pricing bounty engine β€” PostGIS ST_DWithin checkpoint verification + multiplier; partner drivers earn points.
  • 🟒 God-mode demo simulator β€” 20 fleet vehicles on real Bangalore roads, ambulance on a Google-Directions polyline.
  • 🟒 Chaos panel β€” flood a bridge, spawn fleets, force a handoff, all from /admin/chaos.
  • 🟒 Prometheus metrics at /metrics β€” corridor compute duration, WS clients, handoffs triggered.

πŸ› οΈ Tech Stack

LayerTechnology
Core APIGo 1.26 Β· Fiber v2 Β· pgx/v5 Β· redis/v9 Β· zerolog Β· prometheus/client_golang
DatabasePostgreSQL 16 + PostGIS 3.4 + uuid-ossp
Cache / StreamsRedis 7 (allkeys-lru, 256 MB cap)
AI BrainPython 3.11 Β· FastAPI Β· Pydantic v2 Β· httpx Β· uvicorn
Routing engineValhalla (self-hosted, India southern-zone tiles)
FrontendNext.js 14 (App Router) Β· React 18 Β· TypeScript strict Β· Deck.gl 9 Β· @vis.gl/react-google-maps Β· Tailwind v3 Β· shadcn/ui Β· Turf.js
MocksNode 18 Β· Express (fleet-receiver, drone-dispatch)
InfraDocker Compose Β· Prometheus Β· GitHub-flavored CI-ready layout

πŸ—οΈ System Architecture

High-Level View

graph TB
    subgraph Clients
        AMB[πŸš‘ Ambulance<br/>GPS Pings]
        OPS[πŸ‘¨β€βš•οΈ Mission Control<br/>Browser]
        DRV[πŸ“± Partner Driver<br/>Mobile]
    end

    subgraph "Sipra Core (Go / Fiber :8080)"
        REST[REST Handlers]
        WSHUB[WebSocket Hub]
        FLUSH[Ping Flusher<br/>5 s ticker]
        CORR[Corridor Engine<br/>PostGIS]
        RISK[Risk Monitor<br/>10 s ticker]
        WHK[Webhook Dispatcher<br/>Worker Pool]
        BNT[Bounty Engine<br/>ST_DWithin]
    end

    subgraph "Data Plane"
        REDIS[(Redis 7<br/>:6379)]
        PG[(PostGIS 16<br/>:5433)]
    end

    subgraph "AI / Drone"
        AI[🧠 AI Brain<br/>FastAPI :8000]
        DRONE[πŸ›Έ Drone Dispatch<br/>Mock :4003]
    end

    subgraph "B2B Partners"
        FLEET[πŸš— Fleet Receiver<br/>Mock :4000]
    end

    subgraph "External APIs"
        GMAPS[πŸ—ΊοΈ Google Maps<br/>Routes / Places]
        OWM[☁️ OpenWeatherMap]
        VAL[πŸ›£οΈ Valhalla<br/>:8002]
    end

    AMB -->|POST /pings| REST
    REST --> REDIS
    REDIS -.5s flush.-> FLUSH
    FLUSH --> PG
    FLUSH --> CORR
    CORR --> PG
    CORR --> WSHUB
    CORR --> WHK
    WHK -->|HMAC POST| FLEET
    PG --> RISK
    RISK -->|HTTP /predict| AI
    AI -->|GET| GMAPS
    AI -->|GET| OWM
    RISK -->|breach=true| DRONE
    RISK --> WSHUB
    WSHUB -->|WS /ws/dashboard| OPS
    WSHUB -->|WS| DRV
    DRV -->|claim| BNT
    BNT --> PG
    REST -.chaos sim.-> VAL

    classDef core fill:#1e293b,stroke:#3b82f6,color:#fff
    classDef data fill:#7c2d12,stroke:#ea580c,color:#fff
    classDef ext  fill:#064e3b,stroke:#10b981,color:#fff
    class REST,WSHUB,FLUSH,CORR,RISK,WHK,BNT core
    class REDIS,PG data
    class AI,DRONE,FLEET,GMAPS,OWM,VAL ext
Loading

The Three Async Boundaries

Sipra's core design choice: three independent tickers that never block each other.

sequenceDiagram
    autonumber
    participant Amb as Ambulance
    participant API as Go API
    participant R as Redis
    participant F as Flusher 5s
    participant PG as Postgres
    participant CE as Corridor Engine
    participant WS as WS Hub
    participant W as Webhook Pool
    participant FL as Fleet Partners
    participant RM as Risk Monitor 10s
    participant AI as AI Brain
    participant DR as Drone Dispatch

    Note over Amb,API: INGEST β€” sub-5 ms hot path
    Amb->>API: POST /trips/:id/pings
    API->>R: HSET ping buffer
    API-->>Amb: 202 Accepted immediately

    Note over R,FL: FLUSH β€” every 5 s corridor broadcast
    F->>R: drain ping buffer
    F->>PG: pgx.Batch INSERT pings
    F->>CE: CalculateRollingCorridor
    CE->>PG: stamp old corridor valid_until, insert next version
    CE->>WS: BroadcastCorridorUpdate to dashboard
    CE->>W: fan-out corridor polygon to all partners
    W->>FL: HMAC-signed POST exclusion zone

    Note over RM,DR: RISK β€” every 10 s breach check
    RM->>PG: ListInTransit trips
    RM->>AI: POST /predict with latest ping and deadline
    AI-->>RM: breach_probability and predicted_eta
    RM->>WS: BroadcastRiskPrediction
    alt will_breach == true
        RM->>PG: UPDATE trip status to DroneHandoff
        RM->>DR: POST /dispatch with trip coordinates
        DR-->>RM: drone_id and eta_seconds
        RM->>WS: BroadcastHandoffInitiated
    end
Loading

Why three boundaries?

A single synchronous pipeline (ingest β†’ corridor β†’ broadcast β†’ predict) would couple ambulance latency to the slowest downstream consumer. Sipra isolates each stage with a buffer:

  • Ingest writes to Redis and returns 202 β€” bounded by Redis RTT (sub-ms).
  • Flush is a 5 s ticker that batches into Postgres β€” bounded by pgx.Batch.
  • Risk is a 10 s ticker that calls the AI brain β€” bounded by the brain's 5 s SLA.

A stalled Postgres or a slow brain therefore cannot delay the next ping write.


πŸ“Š Data Flow Diagrams

Trip State Machine

stateDiagram-v2
    [*] --> Pending: POST /trips
    Pending --> InTransit: POST /trips/:id/start
    Pending --> Failed: cancelled
    InTransit --> Completed: arrived
    InTransit --> DroneHandoff: AI predicts breach
    InTransit --> Failed: deadline elapsed
    DroneHandoff --> Completed: drone delivers
    DroneHandoff --> Failed: drone aborts
    Completed --> [*]
    Failed --> [*]
Loading

The state machine lives in services/core-go/internal/domain/trip.go. All transitions go through Trip.TransitionTo(next, now); illegal transitions return ErrInvalidTransition and never touch the database.

Corridor Lifecycle

flowchart LR
    A[GPS pings flushed] --> B{">= 2 pings?"}
    B -->|Yes| C[ST_MakeLine ordered<br/>chronologically]
    B -->|No| D[Single point]
    C --> E["ST_Buffer(::geography, 2000m)"]
    D --> E
    E --> F[BEGIN TX]
    F --> G[UPDATE corridors<br/>SET valid_until = NOW<br/>WHERE valid_until IS NULL]
    G --> H[INSERT new row<br/>version = MAX+1]
    H --> I[COMMIT]
    I --> J[Post-commit hook<br/>detached goroutine]
    J --> K[WS BroadcastCorridorUpdate]
    J --> L[Webhook fan-out<br/>per partner]
Loading

Corridors are versioned and history-preserving β€” old rows are stamped with valid_until = NOW() rather than overwritten. This means the bounty engine can replay any historical corridor for verification.

Risk Evaluation Flow

flowchart TD
    Start([Tick every 10s]) --> List[ListInTransit trips]
    List --> Loop{For each trip}
    Loop --> Ping[Get latest GPS ping]
    Ping --> Pred[Call /predict on AI brain]
    Pred --> Cast[Broadcast RISK_PREDICTION<br/>to dashboard]
    Cast --> Check{will_breach?}
    Check -->|No| Loop
    Check -->|Yes| Trans[trip.TransitionTo<br/>DroneHandoff]
    Trans --> Save[UPDATE trip status]
    Save --> Disp[POST /dispatch on drone API]
    Disp --> Hand[Broadcast HANDOFF_INITIATED]
    Hand --> Loop
Loading

Frontend Component Hierarchy

graph TD
    Layout[app/layout.tsx<br/>RootLayout + Toaster]
    Layout --> Intake["/intake<br/>IntakePortal"]
    Layout --> Dash["/dashboard<br/>MissionControlLayout"]
    Layout --> Driver["/driver/[tripId]<br/>DriverShell"]
    Layout --> Admin["/admin/chaos<br/>ChaosPanel (gated)"]

    Dash --> CM[CorridorMap<br/>Deck.gl]
    Dash --> TP[TripPanel]
    Dash --> SB[StatusBar]
    Dash --> AB[AIBrainPanel]
    Dash --> BP[BountyPanel]
    Dash --> RSP[RerouteStatusPanel]
    Dash --> HBP[HospitalBillPanel]
    Dash --> HO[HandoffOverlay]
    Dash --> DPO[DriverPovOverlay]

    CM --> EP[ExclusionPolygon]
    CM --> FS[FleetSwarm]
    CM --> HM[HospitalMarkers]
    CM --> RP[RoutePath]

    Driver --> ER[ExitRouteCard]
    Driver --> BM[BountyModal]

    Dash -. uses .-> WSH[useSipraWebSocket]
    Driver -. uses .-> WSH
    Driver -. uses .-> DPH[useDriverProximity]
    Driver -. uses .-> BL[useBountyLifecycle]
    Driver -. uses .-> PW[usePointsWallet]

    classDef hook fill:#312e81,stroke:#a5b4fc,color:#fff
    class WSH,DPH,BL,PW hook
Loading






πŸ›£οΈ Future Improvements

  1. Real drone integration β€” drop the mock, wire to e.g. Skyports or Zipline.
  2. LLM ai_reasoning β€” swap the template for Gemini Flash (1–2 s budget, off the hot path).
  3. Multi-tenant partners β€” partner-scoped HMAC secrets, partner-scoped corridor filters.
  4. gRPC streaming for fleet β€” replace the :4001 JSON WS with a typed gRPC stream.
  5. Postgres logical replication β€” let the dashboard subscribe to corridor changes natively.
  6. End-to-end encryption β€” wrap WS payloads with libsodium for hospital-to-dashboard sensitive metadata.
  7. Rust rewrite of the corridor engine β€” explore SIMD-accelerated ST_Buffer if the partner count grows past 1k.

Sipra β€” Because every minute past the golden hour costs a life.

Made with ❀️ By Devansh & Kinshuk for Google Solutions Challenge 2026.

About

Autonomous AI platform for emergency medical logistics and real-time ambulance coordination. Enables B2B fleet rerouting with smart exclusion corridors and autonomous drone failsafe delivery.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors