Skip to content

Latest commit

Β 

History

27 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

ReviveX β€” Enterprise Payment Recovery Control Center

Autonomous AI Payment Failure Intelligence & Deterministic Revenue Recovery Platform

Next.js 16 FastAPI Tests 35 Passing NVIDIA AI Razorpay Enterprise Control Center


🧭 Product Mission & Core Operating Philosophy

A failed payment does not permanently mean lost revenue. ReviveX transforms opaque payment gateway telemetry into actionable revenue recovery through a strict separation of concerns:

"AI diagnoses. Safety policies decide. Humans authorize. Recovery executes. Gateway events verify. ReviveX measures."

  1. AI is an Advisor, Not an Autocrat: NVIDIA Nemotron 70B diagnoses root causes from noisy gateway error payloads, but can never directly trigger financial execution.
  2. Deterministic Safety Policies Authoritatively Decide: Hard policies (HARD_DECLINE_POLICY, MAX_RETRIES, CIRCUIT_BREAKER_POLICY) evaluate bounds, exposure limits, and velocity caps before any retry.
  3. Merchants Retain Sovereign Control: Automated recovery batches require explicit merchant authorization with full pre-flight idempotency verification.
  4. Gateway Webhooks Provide Ground Truth: Revenue is only counted as recovered when a cryptographically verified payment_link.paid webhook event is processed and settled.

πŸ“Š Measured Impact (AI vs. Naive Baseline)

To prove quantifiable recovery performance without regulatory or fraud risk, ReviveX was benchmarked against a naive "always retry immediately" baseline across a standardized cohort of N=100 failed transactions (Seed: 42, Total Revenue At Risk: β‚Ή790,969.48).

Metric Naive Baseline (Blind Immediate Retry) ReviveX (AI Diagnosis + Policy Guardrails) Delta / Impact
Recovery Rate (%) 35.0% (35/100) 53.0% (53/100) +18.0% Absolute Lift
Revenue Recovered (β‚Ή) β‚Ή158,530.52 β‚Ή390,977.03 +β‚Ή232,446.51 Net Gain
Compliance Violations Caused 38 violations (Dead VPAs, >3 retries, fraud retries) 0 violations (All intercepted deterministically) 100% Policy Compliance
Compliance Violations Avoided 0 38 violations prevented Complete RBI / Card Rule Safety
High-Risk Transactions Gated 0 (Blindly retried) 10 cases routed to Human Review Zero unauthorized high-value exposure
Wasted Network Retries 65 spam retry calls 0 wasted retries Zero customer friction

Tip

Key Finding: Blindly retrying failed payments triggers severe card network fines on hard declines and chargebacks on fraud signals. ReviveX achieves +18.0% higher recovery while intercepting 100% of compliance violations through NVIDIA Nemotron 70B root-cause diagnosis and deterministic safety policies. Full benchmark reproducibility details: backend/BENCHMARK_RESULTS.md.


⚑ Architecture & End-to-End Pipeline

flowchart TD
    subgraph TELEMETRY["1. Telemetry & Ingestion"]
        A1["Razorpay Webhook Event\n(POST /api/webhooks/razorpay)"] --> A2["HMAC-SHA256 Signature Verification\n(RAZORPAY_WEBHOOK_SECRET)"]
        A2 --> A3["Webhook Idempotency Deduplication\n(WebhookEvent DB Table)"]
        A3 --> A4["Transaction Persistence\n(PostgreSQL Ledger)"]
    end

    subgraph DETECTION["2. Detection & Risk Classification"]
        A4 --> B1["DetectionEngine\n(Rule-Based Risk Tagging)"]
        B1 --> B2["Create/Update RecoveryCase\n(Severity: LOW / MED / HIGH / CRITICAL)"]
    end

    subgraph INVESTIGATION["3. AI Forensic Investigation"]
        B2 --> C1["AIDiagnosisService\n(NVIDIA Nemotron 70B / LLaMA 3.3)"]
        C1 --> C2["Pydantic Response Normalization\n(Root Cause + Confidence Score)"]
    end

    subgraph DECISION["4. Deterministic Policy Gate"]
        C2 --> D1["DecisionEngine & Guardrails\n(HARD_DECLINE_POLICY, TEMPORARY_FAILURE_POLICY)"]
        D1 --> D2{"Safety Policy Check"}
        D2 -->|"Hard Decline / Fraud"| D3["STOP\n(No Retries Allowed)"]
        D2 -->|"Threshold Exceeded"| D4["HUMAN_APPROVAL\n(Risk Queue)"]
        D2 -->|"Temporary Failure"| D5["RETRY / NUDGE\n(Policy-Eligible)"]
    end

    subgraph EXECUTION["5. Recovery Execution & Settlement"]
        D5 --> E1["Merchant Batch Authorization\n(Pre-Flight Verification)"]
        E1 --> E2["RecoveryEngine\n(Razorpay Test-Mode Payment Links)"]
        E2 --> E3["Customer Hosted Checkout\n(https://rzp.io/i/...)"]
        E3 --> E4["payment_link.paid Ingestion\n(Status: RECOVERED)"]
    end

    subgraph AUDIT["6. Immutable Audit & Analytics"]
        E4 --> F1["Immutable Audit Trail\n(Actor: Nemotron | SafetyEngine | Webhook | Operator)"]
        F1 --> F2["Real-Time SQL Dashboards & Control Center\n(Revenue at Risk, Recoverable, Recovered)"]
    end
Loading

πŸ–₯️ Enterprise Control Center (Frontend Views)

The ReviveX frontend is engineered with Next.js 16 (Turbopack) and Vanilla CSS design tokens for ultra-responsive operational visibility:

Route View Name Capabilities & Purpose
/overview Executive Overview Real-time recovery KPIs (Revenue at Risk, Recoverable Revenue, Recovered Revenue, Active Cases), Nemotron 70B Anomaly banner, degraded payment rail breakdown, 24H/7D/30D/90D historical telemetry charts.
/incidents Incident Stream Live gateway degradation alerts, cluster tracking, error volume distribution, latency spikes, and one-click incident drilldown.
/incidents/[id] Incident Forensics Root-cause timeline, affected merchant exposure, gateway nodes involved, and automated mitigation status.
/risk-cases Risk Cases Portfolio Filterable case inventory by status (open, investigating, recovered, abandoned) and severity (CRITICAL, HIGH, MEDIUM, LOW).
/risk-cases/[id] Case Deep Dive Root Cause Decision Tree, side-by-side AI Recommendation vs Authoritative Decision, pre-flight safety checklists, and manual override controls.
/investigations Forensic Investigations 7-Stage Diagnostic Pipeline Visualizer tracing each transaction from telemetry ingestion through to safety clearance.
/investigations/[id] Diagnostic Dossier Full LLM forensic prompt/completion inspector, telemetry metrics, and confidence calibration.
/recovery Recovery Operations Merchant Authorization Card, Batch Queue management, Active Recovery Monitor with dynamic failure-rate tracking, and one-click Circuit Breaker Demonstration.
/transactions Transactions Explorer Global transaction search, status/method filters, error diagnostics, and direct access to lifecycle histories.
/transactions/[id] Transaction Lifecycle 8-stage chronological lifecycle visualizer tracking the transaction from initial checkout error to final webhook settlement.
/policies Safety Policy Center Dynamic policy bounds editor (MAX_RETRIES, COOLDOWN_MINUTES, CIRCUIT_BREAKER_THRESHOLD, EXPOSURE_CAP) with policy documentation.
/audit Immutable Audit Trail Cryptographically verifiable journal of all decisions and actions, tagged by actor (Nemotron 70B, Safety Engine, Human Operator, Razorpay Webhook).
/ai-assistant Operational AI Assistant Grounded operational chat powered by Nemotron 70B with 9 instant telemetry quick-prompts.
/developer-console Developer Console Interactive simulation sandbox with 7 gateway failure presets, real-time stage execution viewer, and live Razorpay Test Checkout launcher.

πŸ› οΈ Technology Stack

Layer Technologies
Frontend Next.js 16.3.2 (Turbopack), React 19, TypeScript, Vanilla CSS Design System, Recharts, Lucide Icons
Backend API FastAPI 0.141, Python 3.11 / 3.14, Pydantic v2, Uvicorn, Httpx
Database & ORM PostgreSQL, SQLAlchemy 2.0 (with connection pooling & pre-ping), Alembic
AI / LLM Engine NVIDIA Integrate API (meta/llama-3.3-70b-instruct) with JSON schema enforcement
Payment Gateway Razorpay Payments & Payment Links API (Test Mode HMAC-SHA256 signature verification)
Safety Engine Deterministic Guardrail Policies, Circuit Breakers, Pre-Flight Verification

πŸ“‚ Project Structure

ReviveX/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ alembic/                         # Database schema migrations
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ models.py                    # SQLAlchemy ORM models (Transaction, RecoveryCase, RecoveryAction, AuditLog, etc.)
β”‚   β”‚   β”œβ”€β”€ schemas.py                   # Pydantic validation schemas & API contracts
β”‚   β”‚   β”œβ”€β”€ database.py                  # PostgreSQL engine, sessionmaker & pool configuration
β”‚   β”‚   β”œβ”€β”€ main.py                      # FastAPI routes, webhook endpoints & error handlers
β”‚   β”‚   β”œβ”€β”€ scripts/
β”‚   β”‚   β”‚   └── generate_data.py         # Realistic transaction data seeder
β”‚   β”‚   └── services/
β”‚   β”‚       β”œβ”€β”€ decision.py              # Authoritative Guardrails & DecisionEngine
β”‚   β”‚       β”œβ”€β”€ detection.py             # Rule-based failure detection & risk classifier
β”‚   β”‚       β”œβ”€β”€ diagnosis.py             # NVIDIA Nemotron LLM diagnosis & prompt engine
β”‚   β”‚       β”œβ”€β”€ orchestrator.py          # End-to-end pipeline orchestrator & audit logger
β”‚   β”‚       β”œβ”€β”€ razorpay.py              # Razorpay Payment Links API & webhook verification
β”‚   β”‚       β”œβ”€β”€ recovery.py              # Real Razorpay recovery execution & simulation engine
β”‚   β”‚       └── simulator.py             # Developer Console simulation & stage tracing session
β”‚   β”œβ”€β”€ tests/
β”‚   β”‚   β”œβ”€β”€ test_data_integrity.py       # Case integrity & idempotency tests
β”‚   β”‚   β”œβ”€β”€ test_decision.py             # Guardrail & policy override tests
β”‚   β”‚   β”œβ”€β”€ test_detection.py            # Failure detection classification tests
β”‚   β”‚   β”œβ”€β”€ test_diagnosis.py            # LLM mock diagnosis & normalization tests
β”‚   β”‚   β”œβ”€β”€ test_exceptions.py          # Exception Center API tests
β”‚   β”‚   β”œβ”€β”€ test_razorpay.py             # Razorpay webhook, signature & payment link tests
β”‚   β”‚   β”œβ”€β”€ test_recovery.py             # RecoveryEngine execution tests
β”‚   β”‚   └── test_settings.py             # Dynamic merchant rules & settings tests
β”‚   β”œβ”€β”€ requirements.txt                 # Python backend dependencies
β”‚   └── alembic.ini                      # Alembic configuration
β”‚
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”‚   β”œβ”€β”€ layout.tsx               # Root layout with top navigation header
β”‚   β”‚   β”‚   β”œβ”€β”€ overview/page.tsx        # Executive Overview dashboard & KPIs
β”‚   β”‚   β”‚   β”œβ”€β”€ incidents/page.tsx       # Incident Stream
β”‚   β”‚   β”‚   β”œβ”€β”€ incidents/[incidentId]/  # Incident Forensics
β”‚   β”‚   β”‚   β”œβ”€β”€ risk-cases/page.tsx      # Risk Cases portfolio
β”‚   β”‚   β”‚   β”œβ”€β”€ risk-cases/[caseId]/     # Risk Case deep dive & Root Cause Decision Tree
β”‚   β”‚   β”‚   β”œβ”€β”€ investigations/page.tsx  # 7-Stage Diagnostic Pipeline Visualizer
β”‚   β”‚   β”‚   β”œβ”€β”€ investigations/[id]/     # Forensic dossier detail
β”‚   β”‚   β”‚   β”œβ”€β”€ recovery/page.tsx        # Recovery Batches & Active Recovery Monitor
β”‚   β”‚   β”‚   β”œβ”€β”€ transactions/page.tsx    # Transactions Explorer
β”‚   β”‚   β”‚   β”œβ”€β”€ transactions/[id]/       # 8-Stage Transaction Lifecycle
β”‚   β”‚   β”‚   β”œβ”€β”€ policies/page.tsx        # Safety Policy Center & parameter bounds
β”‚   β”‚   β”‚   β”œβ”€β”€ audit/page.tsx           # Immutable Audit Trail
β”‚   β”‚   β”‚   β”œβ”€β”€ ai-assistant/page.tsx    # Grounded Operational AI Assistant
β”‚   β”‚   β”‚   └── developer-console/       # Interactive Pipeline Simulator
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ Header.tsx               # Top navigation bar
β”‚   β”‚   β”‚   β”œβ”€β”€ Sidebar.tsx              # Operations navigation sidebar
β”‚   β”‚   β”‚   └── DashboardCharts.tsx      # Recharts visualizations
β”‚   β”‚   └── lib/
β”‚   β”‚       └── config.ts                # API Base URL resolver
β”‚   β”œβ”€β”€ next.config.ts                   # Next.js Turbopack config
β”‚   β”œβ”€β”€ package.json                     # Frontend dependencies & scripts
β”‚   └── tsconfig.json                    # TypeScript compiler config
β”‚
β”œβ”€β”€ .gitignore                           # Git ignore rules
└── README.md                            # Comprehensive project documentation

πŸ”Œ API Reference

1. Telemetry & Webhooks

Method Endpoint Description
POST /api/webhooks/razorpay Cryptographic HMAC-SHA256 verified webhook ingestion & automatic recovery settlement
GET /health Backend and database connection health check

2. Dashboard & Analytics

Method Endpoint Description
GET /api/dashboard/stats Real-time aggregated KPIs (Revenue at Risk, Recoverable, Recovered, Recovery Rate)
GET /api/dashboard/breakdown Root cause & recovery action breakdown for telemetry charts

3. Case & Incident Management

Method Endpoint Description
GET /api/cases List cases with status, severity, and risk type filters
GET /api/cases/{case_id} Retrieve individual recovery case details
GET /api/cases/{case_id}/audit Retrieve chronological 5-step audit trail
POST /api/cases/{case_id}/action Execute operator action (retry, send_nudge, stop)

4. Transactions & Audit

Method Endpoint Description
GET /api/transactions Search and filter transactions by status and payment method
GET /api/transactions/{tx_id} Retrieve full transaction detail with linked recovery case
GET /api/audit Retrieve global immutable audit log records

5. Recovery Operations & Safety Policies

Method Endpoint Description
POST /api/recovery/run Execute recovery cycle on all registered open transactions
POST /api/recovery/batches/{id}/circuit-breaker Trip batch circuit breaker (simulates failure spike)
GET /api/settings Retrieve active safety policies and guardrail thresholds
PUT /api/settings Update policy limits (MAX_RETRIES, EXPOSURE_CAP, etc.)
POST /api/ai-assistant/chat Query the grounded Operational AI Assistant

πŸ” Environment Variables

Backend (backend/.env)

# PostgreSQL Database Connection URL
DATABASE_URL=postgresql://user:password@localhost:5432/revivex

# Frontend Origin for CORS
FRONTEND_URL=http://localhost:3000

# NVIDIA AI Inference API
AI_PROVIDER=nvidia
NVIDIA_API_KEY=nvapi-your-key-here
NVIDIA_BASE_URL=https://integrate.api.nvidia.com/v1
NVIDIA_MODEL=meta/llama-3.3-70b-instruct

# Razorpay Test Mode Configuration
RAZORPAY_WEBHOOK_SECRET=your_test_webhook_secret
RAZORPAY_LIVE_RECOVERY_ENABLED=true
RAZORPAY_KEY_ID=rzp_test_xxxxxxxxxxxxxx
RAZORPAY_KEY_SECRET=yyyyyyyyyyyyyyyyyyyyyyyy

Frontend (frontend/.env.local)

NEXT_PUBLIC_API_BASE_URL=http://localhost:8000/api

πŸš€ Quickstart & Verification

Warning

Before you demo: Our live deployments use Render's free tier for the backend and Vercel for the frontend. Due to free-tier limitations, the Render backend spins down after inactivity. You may experience a cold-start latency of up to 50 seconds on your first request. Please warm up the endpoints beforehand by visiting:

1. Run Backend Server

cd backend
.\venv\Scripts\activate          # Windows (or source venv/bin/activate on Linux/macOS)
pip install -r requirements.txt
python -m uvicorn app.main:app --reload --port 8000

2. Run Frontend Dev Server

cd frontend
npm install
npm run dev

Open http://localhost:3000 (redirects cleanly to /overview).

3. Run Automated Tests

cd backend
.\venv\Scripts\python -m pytest tests -q
# Output: 35 passed in ~40s

4. Build Production Bundle

cd frontend
npm run build
# Output: Next.js Turbopack compiled and generated 10 static & dynamic routes cleanly

πŸš€ Scaling Considerations & Production Load Architecture

For enterprise scale (10,000+ recovery transactions per minute during flash sales and peak festival traffic), ReviveX incorporates the following horizontal scaling and resilience designs:

  1. Decoupled Asynchronous Webhook Processing Queue:

    • Inbound webhook delivery (POST /api/webhooks/razorpay) must acknowledge within < 200ms to satisfy gateway SLAs.
    • Synchronous LLM diagnosis and dynamic payment link creation are decoupled via a distributed worker queue (e.g., Celery + Redis / Redis Streams / AWS SQS).
    • Inbound handlers authenticate the HMAC-SHA256 signature, verify idempotency, persist the raw event, and immediately dispatch background worker jobs (WorkflowOrchestrator.dispatch_async_recovery_task).
  2. High-Performance Database Indexing & Partitioning:

    • Composite B-Tree indexes on (merchant_id, status, created_at) for high-throughput dashboard aggregation queries.
    • Unique hash indexing on (transaction_id) and (idempotency_key) to guarantee O(1) deduplication lookups.
    • Time-based table partitioning on audit_logs and transactions by month/quarter to maintain low query latency as records scale to tens of millions.
  3. Inbound Webhook Rate Limiting & DoS Protection:

    • Redis-backed sliding-window rate limiters on /api/webhooks/razorpay (e.g. 5,000 requests/second per merchant signature) to prevent denial-of-service and replay attack storms.
    • Circuit breaker auto-trip buffers to prevent cascading issuer degradation during major banking node outages.

πŸ›‘οΈ Security & Integrity Guarantees

  • HMAC-SHA256 Webhook Verification: Inbound gateway events are cryptographically authenticated before touching any business logic.
  • Strict Test-Mode Isolation: ReviveX validates the rzp_test_ prefix on Razorpay keys to prevent accidental live charges.
  • Deduplication & Idempotency: WebhookEvent and idempotency_key locking guarantee that duplicate webhook retries never produce duplicate charges or recovery loops.
  • Deterministic Circuit Breakers: If downstream failure rate exceeds 15%, the system immediately trips the circuit breaker, protecting merchant credibility.

πŸ”§ What Broke & How We Fixed It

During our final pre-competition validation, we identified and fixed the following real issues:

  • Simulator NameError Crash

    • What broke: Opening the Developer Console simulator crashed the backend due to an unresolved reference to RecoveryAction in simulator.py.
    • How it was caught: During an end-to-end integrity test of the UI pipeline.
    • The fix: Imported RecoveryAction into simulator.py and patched the env path loading (commit b2aead3).
  • LLM Diagnosis Malformed JSON Keys

    • What broke: The NVIDIA Nemotron 70B model occasionally prefixed JSON keys with dots (e.g. ".root_cause" instead of "root_cause"), causing Pydantic validation failures that dropped valid AI diagnostics into manual human review.
    • How it was caught: Investigating ValidationError logs in the audit trail.
    • The fix: Implemented a deterministic string-replacement normalization layer in diagnosis.py to strip the bad dot notation before Pydantic parsing (commit 217ae8f).

πŸ“„ License

This project is licensed under the MIT License.

About

AI-powered payment failure intelligence and revenue recovery platform for detecting, investigating, and safely recovering failed payments.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages