Skip to content

About

SQL agent that finds root causes of warranty spikes: guarded SQL, statistical drill-down, BigQuery + Cloud Run

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

quality-rca-agent

An agent that investigates vehicle warranty spikes the way a quality engineer would: it writes SQL, runs it under guardrails, drills down from "brake caliper claims are up" to "supplier S03, lot L-S03-2507", and backs every conclusion with statistics, symptom evidence and a full query trace. It runs on DuckDB locally and on BigQuery in production, and deploys to Cloud Run with Terraform.

CI Python GCP

All data is synthetic and generated by qrca generate: 60,000 vehicles, 600,000 part records and about 2,800 warranty claims. Models, plants, suppliers and customers are fictional. The root causes were planted on purpose, so the agent can be scored against them.

The problem

When claims for a component jump, quality engineers spend days slicing data by supplier, lot, plant, build week, trim and region to find out where the problem lives. It is the right job for an agent, but only with three conditions:

  1. It has to be right, and say how sure it is. A wrong supplier escalation is expensive. Findings come with a claim rate, a lift, a p-value and the share of excess claims they explain.
  2. It can't be allowed to do damage. Model-written SQL is untrusted input: no writes, no PII, no runaway scans, no file or network access.
  3. It has to be auditable. Every query it ran is recorded, and past investigations are remembered.

Results

From qrca eval --full (report: reports/eval_report.md). CI fails if any planted cause is missed, any control raises an alarm, or any unsafe query gets through.

Component Planted cause Agent's root cause Lift Top symptom phrase found
brake caliper lot L-S03-2507 supplier S03, lot L-S03-2507 11.7x "piston seal leak"
fuel pump plant P-KCY, weeks 18–21 plant P-KCY, build weeks 2025-W18 to W21 10.3x "pump relay burnt"
window regulator trim Limited trim Limited 5.1x "cable snapped"
infotainment unit supplier S07 supplier S07 3.7x "black after update"
transmission valve body Birch, model year 2026 model Birch, model year 2026 5.3x "solenoid stuck"
battery sensor Northeast region sale region Northeast 4.4x "sensor corrosion"
coolant pump plant P-LOU, weeks 30–33 plant P-LOU, build weeks 2025-W30 to W33 8.9x "impeller cracked"
airbag clockspring lot L-S11-2603 supplier S11, lot L-S11-2603 19.8x "ribbon cable torn"
seat heater, door lock actuator (controls: nothing planted) no significant concentration – –
  • 8 of 8 planted causes found, 0 false alarms, and the same result on three more random datasets (seeds 101, 202 and 303).
  • Median of 12.5 SQL queries and 186 ms per investigation on DuckDB.
  • SQL guardrails: 25 of 25 unsafe queries blocked; 15 of 15 normal analytical queries allowed and run.

Where it stops working. I set every defect to the same strength to see where detection fails. This matters more than the 8 of 8:

Defect strength (claim-rate multiplier) Causes found False alarms
2x 1 of 8 0
3x 3 of 8 0
5x 5 of 8 1
8x 7 of 8 0

A 2x problem in one supplier lot of about 500 vehicles produces a handful of extra claims, which is statistically indistinguishable from noise at this volume. Catching weak defects earlier needs more exposure data (more vehicles or more months), not a cleverer prompt. At 5x, one control produced a false alarm, which is a reminder to treat findings as hypotheses for an engineer to confirm.

How an investigation runs

flowchart TD
    Q["Why are brake caliper claims up?"] --> L[link entities<br/>component, model, model year]
    L --> M[recall memory<br/>past findings + similar questions]
    M --> T[trend<br/>monthly claims]
    T --> D1[drill-down level 1<br/>supplier · plant · model · year · trim · region<br/>+ every lot + rolling 4-week plant build windows]
    D1 --> S{any segment significant?<br/>Bonferroni-corrected}
    S -->|no| N[no significant concentration]
    S -->|yes| D2[refine or tighten<br/>supplier→lot · plant→build-week window · model→year<br/>only if it explains ≥70% of the excess]
    D2 --> SY[symptom analysis<br/>log-odds of phrases inside vs outside the segment]
    SY --> R[report<br/>root cause · evidence · masked VINs · actions · narrative]
    R --> MEM[(investigation memory)]
    subgraph every step
      G[SQL guardrails] --> E[(DuckDB / BigQuery)]
    end
Loading

The statistics, in short: exposure is every vehicle with the part, and events are vehicles with a claim on it. Each candidate segment's claim rate is compared with all other vehicles using a Poisson log-likelihood ratio, then corrected for the number of segments tested. Rolling plant build windows use SQL window functions (SUM(...) OVER (PARTITION BY plant ORDER BY week ROWS BETWEEN ...)).

SQL guardrails (guardrails.py)

Rule Example it blocks
Exactly one statement, read-only SELECT only SELECT 1; DROP TABLE parts, DELETE ..., COPY ... TO, ATTACH, SET, INSTALL
Allowlisted tables only, no system schemas information_schema.tables, pg_catalog.pg_tables
No PII columns, and no SELECT * on tables that hold PII (CTEs included) SELECT customer_name ..., WITH x AS (SELECT customer_phone ...)
No table functions or unknown functions read_csv('/etc/passwd'), getenv('HOME'), duckdb_settings()
No cartesian products FROM vehicles, parts, CROSS JOIN
LIMIT always enforced (added or clamped) Unbounded result sets
Scan budget checked before running (BigQuery: dry-run bytes) Accidental full-table joins
Defense in depth: the engine is read-only with external access disabled Anything the parser missed

Model-written SQL (POST /ask, when an LLM key is set) goes through exactly the same checks. A test makes a fake model return SELECT customer_name, customer_phone ... and checks that it is blocked.

Quickstart

git clone https://github.com/rakeshsaineni/quality-rca-agent && cd quality-rca-agent
python -m venv .venv && source .venv/bin/activate
make install && make data
qrca investigate "What is driving the increase in fuel pump claims?"
make test        # 59 tests
make eval-full   # regenerates reports/ (adds 3 seeds and the sensitivity sweep)
make serve       # API on :8080 (/investigations, /sql, /ask, /health)

Example output (trimmed):

{
  "status": "root_cause_found",
  "summary": "Fuel pump claims are concentrated in plant P-KCY, build weeks 2025-W18 to W21: 25 claims on 965 vehicles (2.59%) versus 0.25% elsewhere, 10.3x higher. The most over-represented symptom is \"pump relay burnt\". Pull plant P-KCY change records (tooling, staffing, process parameters) for the build window.",
  "root_cause": {"label": "plant P-KCY, build weeks 2025-W18 to W21", "vehicles": 965, "claims": 25,
                 "lift": 10.26, "p_value": 3.06e-17, "excess_claims": 22.6},
  "refined_from": {"label": "plant P-KCY"},
  "affected_vehicles": {"count": 965, "sample_vins": ["1DEMO********0138", "1DEMO********0186", "..."]}
}

With an LLM (optional): set GEMINI_API_KEY (or ANTHROPIC_API_KEY). The model writes the narrative and answers free-form questions via POST /ask. It is never in the root-cause path, and a narrative that contains numbers not found in the evidence is discarded in favor of the template.

Deploy on GCP

cd infra/terraform
terraform init
terraform apply -var project_id=YOUR_PROJECT \
  -var image=us-central1-docker.pkg.dev/YOUR_PROJECT/quality-rca/agent:v1 \
  -var 'invoker_members=["group:quality-engineering@yourco.com"]'

This creates Artifact Registry, the BigQuery dataset, and a service account with read access to that one dataset, bigquery.jobUser, and one Secret Manager secret, plus a Cloud Run service with no public access (only the listed invokers). With BQ_PROJECT set, the backend switches to BigQuery: the same SQL is transpiled with sqlglot, dry-run checked, and capped with maximum_bytes_billed.

Design decisions

  • Statistics find the cause; the LLM only explains it. Root-cause analysis on tabular data is a counting problem. Using a model there would add cost and variance and remove auditability. The model's job is language: narratives and ad-hoc questions.
  • Fine segments at level 1, not only coarse ones. My first version only drilled down from coarse segments and found just 4 of 8: it missed both lot-level defects and both plant-window defects. A bad lot is about 3% of a supplier's volume, so its signal disappears at the supplier level. Testing lots and rolling build windows directly, with a stricter multiple-testing correction, fixed it without causing false alarms.
  • Refine only when the evidence supports it. Going from supplier to lot happens only if the lot explains at least 70% of the supplier's excess claims. That is why S07 (a whole-supplier problem) stays at supplier level.
  • VINs are masked in reports, and PII never leaves the warehouse. Customer name and phone can't be selected even by an analyst using POST /sql.
  • Memory is structured first, semantic second. "Has S03 caused problems before?" is a SQL query. TF-IDF recall of similar past questions is a bonus, not the source of truth.

Limitations and next steps

  • Exposure ignores time in service. A survival-style model (claims per 1,000 vehicle-months) would compare young and old vehicles more fairly.
  • Interactions are checked only along known hierarchies. Two-dimensional scans (e.g. trim × region) would catch combined causes.
  • Add an export from the in-process trace to Cloud Trace via OpenTelemetry, plus a small UI for engineers to accept or reject findings (which also builds a labeled eval set).

Project layout

src/qrca/        data (synthetic warehouse) · backends (DuckDB, BigQuery) · guardrails · rca · agent · memory · trace · llm · api · evaluate · cli
infra/terraform  Cloud Run, BigQuery dataset, IAM (least privilege), Secret Manager, Artifact Registry
tests/           59 tests: guardrail suites, every planted cause, controls, agent, API, LLM path (mocked)
reports/         latest evaluation report

About

SQL agent that finds root causes of warranty spikes: guarded SQL, statistical drill-down, BigQuery + Cloud Run

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages