# Causal

> Estimate treatment effects (ATE, ATT) and propensity scores from observational data with IPW, regression adjustment, and AIPW

This page includes setup, release pins, credentials, hosting and verification evidence. [JSON alternative](https://query.farm/products/orchard/api/v1/connectors/causal.json) contains the same setup facts for structured readers; choose one format.

## Runtime and release

Use DuckDB or Haybarn **2.0.1** with **VGI protocol 3.4**.
Catalog alias: `causal`. Release: [v0.5.0](https://github.com/Query-farm/vgi-causal/releases/tag/v0.5.0). Metadata generated: 2026-12-01T18:22:16+00:00.

## Choose where it runs

- On your machine: use an installation method below. No Query Farm account is required for local execution.
- Self-host: follow [the connector deployment instructions](https://github.com/Query-farm/vgi-causal) and [connection guide](https://query.farm/vgi/connect-to-a-worker/). Use your real endpoint and its authentication settings.
- Query Farm hosted: [create a deployment](https://auth.queryfarm.cloud/console/new?worker=causal). Hosting has a $10 monthly minimum per organization; usage and license fees may apply. Copy the deployment-specific ATTACH from the console.

## Service credentials and prerequisites

No service credentials are declared by this connector. Individual datasets, input files or deployments may have their own prerequisites.

Secret parameter required flags describe the upstream declaration; they do not override the service-level mode above. Keep secrets in environment variables or the deployment secret store. SQL values in angle brackets are placeholders, not automatic environment lookups. Native DuckDB and Haybarn 2.0.1 do not provide a SQL getenv() function, even when worker-supplied snippets mention it. Read environment variables in your application and pass credential values through client parameter bindings (for example, Python con.execute("CREATE SECRET stripe (TYPE stripe, api_key ?)", [os.environ["STRIPE_API_KEY"]]) after attaching the connector. Omit unused optional parameters and keep real values out of saved SQL and logs.

## Install the extension

In stock DuckDB:

```sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;
```

In Haybarn:

```sql
INSTALL vgi FROM community;
LOAD vgi;
```

## Attach the connector

The local recipes below pin the catalog release for repeatability. A public demo endpoint follows its deployed release.

### uvx

Attach with uvx

Needs uv. uvx builds the worker from its release tag on first attach and reuses the cached environment after that.

```sql
ATTACH 'causal' AS causal (
  TYPE vgi,
  LOCATION 'uvx --from git+https://github.com/Query-farm/vgi-causal@v0.5.0 vgi-causal-worker'
);
```

### Docker

Attach the signed image

Needs Docker, Podman or another OCI runtime. The extension runs the container and talks to it over stdio.

```sql
ATTACH 'causal' AS causal (
  TYPE vgi,
  LOCATION 'oci://ghcr.io/query-farm/vgi-causal:0.5.0'
);
```

## Estimate the effect of a treatment

Service credentials required for this example: not declared by this example; check the connector requirements above.

```sql
WITH cohort AS (
  SELECT
    g                                                   AS id,
    (g - 30)::DOUBLE / 10.0                             AS x,
    CASE WHEN ((g * 7 + 3) % 10) < 5 + 3 * sign(g - 30) THEN 1 ELSE 0 END AS t,
    5.0 * (CASE WHEN ((g * 7 + 3) % 10) < 5 + 3 * sign(g - 30) THEN 1 ELSE 0 END)
      + 2.0 * ((g - 30)::DOUBLE / 10.0)                 AS y
  FROM generate_series(0, 60) AS s(g)
)
SELECT method, round(estimate, 2) AS estimate FROM causal.main.ate((SELECT t, y, x FROM cohort), treatment := 't', outcome := 'y') ORDER BY method
```

- [causal.main.ate — table_in_out_function](https://query.farm/products/orchard/connectors/causal/objects/table_in_out_function.bWFpbg.YXRl.md): exact declaration for this example.

Execution evidence: **captured_result**.

```json
{
  "status": "captured_result",
  "capturedAt": "2026-12-01T06:12:39+00:00",
  "engineVersion": "2.0.1",
  "protocolVersion": "3.4.0",
  "releaseTag": "v0.5.0",
  "sample": {
    "columns": [
      "method",
      "estimate"
    ],
    "types": [
      "VARCHAR",
      "DOUBLE"
    ],
    "rows": [
      [
        "aipw",
        5
      ],
      [
        "ipw",
        4.68
      ],
      [
        "regression_adjustment",
        5
      ]
    ],
    "more": false
  }
}
```

## Connector reference

### Causal Inference in SQL: Treatment Effects, Propensity & Doubly-Robust Estimation

![DoWhy logo](https://raw.githubusercontent.com/py-why/dowhy/main/docs/source/_static/dowhy-logo-small.png)

**Estimate the causal effect of an intervention directly in DuckDB SQL** — average treatment effect (ATE), effect on the treated (ATT), and per-subject propensity scores — from observational cohort data, with confounders adjusted for automatically. This VGI extension turns causal questions like *"did the treatment actually work, after controlling for who was likely to get it?"* into a single SQL query.

Causal inference goes beyond correlation and naive group means: a simple difference between treated and untreated subjects is biased whenever the same factors that drive treatment also drive the outcome (confounding). The `causal` catalog corrects that bias using the standard toolkit of observational causal inference — inverse probability weighting (IPW), regression adjustment (the g-formula), and doubly-robust augmented IPW (AIPW) — so analysts, data scientists, and epidemiologists can run treatment-effect, impact, and intervention analysis where their data already lives, without exporting to a notebook.

Under the hood the estimators are powered by [scikit-learn](https://scikit-learn.org/stable/) ([source](https://github.com/scikit-learn/scikit-learn)) for the propensity and outcome models and [statsmodels](https://www.statsmodels.org/stable/index.html) ([source](https://github.com/statsmodels/statsmodels)) for the regression and inference machinery, with an optional doubly-robust backend via [DoWhy](https://www.pywhy.org/dowhy/) ([source](https://github.com/py-why/dowhy)). Propensities come from an L2-regularized logistic model with score clipping that keeps near-perfect separation from blowing up the weights, and standard errors come from influence functions (IPW/AIPW), OLS (regression adjustment), or a seeded bootstrap (ATT) — every estimate is deterministic and reproducible.

## Estimands

Every estimator consumes a whole cohort as a `(SELECT ...)` relation plus named role arguments; **every column not named by a role is treated as a covariate/confounder and adjusted for**, and treatment must be binary `0/1`.

- **Average treatment effect** `E[Y(1)-Y(0)]`, returned one row per method: IPW, regression adjustment, and doubly-robust AIPW, each with a standard error and 95% confidence interval.
- **Average treatment effect on the treated** `E[Y(1)-Y(0)|T=1]` via IPW-ATT weighting, with a bootstrap standard error.
- **Per-row propensity** `e(X)=P(T=1|X)` from the logistic model, keyed by your `id` column.

Runnable, catalog-qualified demonstrations live in each object's example queries (and the schema's `vgi.example_queries`), so they are executed and coverage-checked rather than pasted inline here.

Estimates are causal only under the usual assumptions — **unconfoundedness** (no unmeasured confounders given the supplied covariates), **overlap** (`0 < e(X) < 1`), and **SUTVA**. Choosing the covariate set is your modeling decision; the worker estimates, it does not assume the assumptions hold.

## Find the exact SQL object

[Browse 4 object declarations](https://query.farm/products/orchard/api/v1/connectors/causal/objects.json) or [search within this connector](https://query.farm/products/orchard/api/v1/search.json?kind=object&connector=causal&q=causal).

Follow one format of each needed object for complete argument types, defaults, named flags, return columns and examples. Existing links above can replace another search. For questions about hosting, credentials or supported operations, stop once the documentation answers the question; SQL and unrelated object lookups are unnecessary.

## Verification and interpretation

- Missing, null, or undeclared metadata means unknown; do not invent defaults, credential scope, platform support or endpoint URLs.
- Search is keyword retrieval, not proof of a capability. Read the exact object declaration before generating SQL.
- A table and a table function can have the same name. Preserve parentheses and use the matching overload and schema.
- Service credentials, external data availability and deployment authentication are separate requirements.
- Catalog verification records the harvest environment. It is not proof that every query or current live API call succeeds. Only an example with captured_result has a saved result for that exact SQL.

```json
{
  "generatedAt": "2026-12-01T18:22:16+00:00",
  "repository": "https://github.com/Query-farm/vgi-causal",
  "harvest": {
    "status": "ok",
    "method": "subprocess",
    "error": null,
    "vgi_version": "9773130dde"
  },
  "catalogVerification": {
    "verified": true,
    "status": "passed",
    "total": 3,
    "passed": 3,
    "failed": 0,
    "needs_credentials": 0,
    "location": "uvx --from git+https://github.com/Query-farm/vgi-causal@v0.5.0 vgi-causal-worker",
    "transport": "subprocess",
    "environment": {
      "vgi_extension_version": "9773130dde",
      "haybarn_version": "2.0.1rc3",
      "engine_version": "v2.0.1",
      "python": "3.12.4",
      "platform": "darwin_arm64",
      "protocol_version": "3.4.0"
    },
    "checked_at": "2026-12-01T06:12:19+00:00"
  },
  "interpretation": "Catalog verification records the harvest environment. It is not proof that every query or current live API call succeeds. Only an example with captured_result has a saved result for that exact SQL."
}
```
