Metadata-Version: 2.5
Name: hypequery
Version: 0.1.0b2
Summary: Type-safe ClickHouse semantic layer and serving for Python.
Project-URL: Homepage, https://hypequery.com
Project-URL: Repository, https://github.com/hypequery/hypequery
Project-URL: Issues, https://github.com/hypequery/hypequery/issues
Project-URL: Documentation, https://github.com/hypequery/hypequery/tree/main/python/hypequery#readme
Project-URL: Changelog, https://github.com/hypequery/hypequery/blob/main/python/hypequery/CHANGELOG.md
Author: Hypequery
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: analytics,asgi,clickhouse,datasets,semantic-layer
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Framework :: Django
Classifier: Framework :: Flask
Classifier: Framework :: Pydantic :: 2
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Database
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: anyio>=4.14.2
Requires-Dist: idna>=3.15
Requires-Dist: pydantic>=2.12.2; python_version >= '3.14'
Requires-Dist: pydantic>=2.9.2; python_version < '3.14'
Requires-Dist: tzdata>=2025.2
Provides-Extra: arrow
Requires-Dist: pyarrow>=23.0.1; extra == 'arrow'
Provides-Extra: clickhouse
Requires-Dist: certifi>=2026.10.19; extra == 'clickhouse'
Requires-Dist: clickhouse-connect>=1.4.2; extra == 'clickhouse'
Requires-Dist: urllib3>=2.8.0; extra == 'clickhouse'
Provides-Extra: clickhouse-async
Requires-Dist: aiohttp>=3.14.4; extra == 'clickhouse-async'
Requires-Dist: certifi>=2026.10.19; extra == 'clickhouse-async'
Requires-Dist: clickhouse-connect[async]>=1.4.2; extra == 'clickhouse-async'
Requires-Dist: idna>=3.15; extra == 'clickhouse-async'
Requires-Dist: urllib3>=2.8.0; extra == 'clickhouse-async'
Provides-Extra: django
Requires-Dist: asgiref>=3.8.1; extra == 'django'
Requires-Dist: certifi>=2026.10.19; extra == 'django'
Requires-Dist: clickhouse-connect>=1.4.2; extra == 'django'
Requires-Dist: django>=5.2.17; extra == 'django'
Requires-Dist: sqlparse>=0.6.0; extra == 'django'
Requires-Dist: urllib3>=2.8.0; extra == 'django'
Provides-Extra: flask
Requires-Dist: certifi>=2026.10.19; extra == 'flask'
Requires-Dist: clickhouse-connect>=1.4.2; extra == 'flask'
Requires-Dist: flask[async]>=3.1.3; extra == 'flask'
Requires-Dist: jinja2>=3.1.6; extra == 'flask'
Requires-Dist: urllib3>=2.8.0; extra == 'flask'
Requires-Dist: werkzeug>=3.1.9; extra == 'flask'
Provides-Extra: jwt
Requires-Dist: cryptography>=50.0.0; extra == 'jwt'
Requires-Dist: pyjwt[crypto]>=2.15.0; extra == 'jwt'
Provides-Extra: pandas
Requires-Dist: pandas>=2.3.3; extra == 'pandas'
Provides-Extra: polars
Requires-Dist: polars>=1.0.0; extra == 'polars'
Provides-Extra: server
Requires-Dist: h11>=0.16.0; extra == 'server'
Requires-Dist: uvicorn>=0.30.6; extra == 'server'
Description-Content-Type: text/markdown

# hypequery for Python

A Python semantic layer for ClickHouse datasets, metrics, multi-tenant analytics, and HTTP serving from any Python framework.

> **Beta (0.1.0b2).** Datasets, execution, Serve, generated React clients and
> HTTP-backed MCP are tested end to end from the installed package. APIs may still
> change before 1.0. Please report problems on
> [GitHub](https://github.com/hypequery/hypequery/issues).

## Python → React → MCP example

The [complete client tutorial](https://github.com/hypequery/hypequery/blob/main/python/hypequery/examples/client_dashboard/README.md) shares one
Python definition across authorized HTTP, generated React types and MCP stdio.
It works with the published npm packages (`@hypequery/cli` 1.25+,
`@hypequery/react` 0.7+ and `@hypequery/mcp` 0.10+). Its preparation script
builds the same journey from a checkout, using an installed wheel and packed
Node packages outside the repository.

## Schema-backed Python CLI

Install `hypequery[server,clickhouse]`, export your `CLICKHOUSE_*` connection
settings, then run `hypequery init --path analytics --tables orders,customers`.
The default inspects actual catalog metadata and generates `datasets.py`, a
`schema.json` snapshot, and authenticated endpoints for selected tables.
`--exclude-tables` omits tables; all tables are selected by default.

Physical names map to the same camelCase semantic names as the TypeScript CLI.
Numeric value fields get suggested sum/average measures; IDs and coordinates
remain dimensions. Unsupported columns and tenant candidates are reported.
Review business semantics and configure tenant isolation explicitly. No database
writes or automatic relationship inference occur during discovery.

`totalCount` counts a supported non-nullable column, so it includes every row.
If none exists, the CLI emits `nonNullCount` instead and warns that it counts
only non-null values in the first supported column. Regeneration uses the same
rule; review references to a previously generated `totalCount` before replacing
definitions for an all-nullable table.

`--skip-connection` explicitly creates the offline orders demo with `seed.sql`.
Existing output paths are never overwritten. See the
[TypeScript reference and parity contract](https://github.com/hypequery/hypequery/blob/main/plans/python-cli-schema-generation-parity.md).

## Getting started

From zero to a served dataset. You need Python 3.11+ and a ClickHouse server.

**1. Install** with the server and ClickHouse extras:

```bash
pip install "hypequery[server,clickhouse]"
```

That covers the synchronous executor this guide uses. For the native async
executor (`create_async_clickhouse_executor`), install
`"hypequery[server,clickhouse-async]"` instead.

To try an unreleased build, install from a checkout of this repository instead:
`pip install "./python/hypequery[server,clickhouse]"`.

**2. Create sample data.** Run this in `clickhouse client` (or any SQL console)
against your database:

<!-- getting-started: seed.sql -->
```sql
CREATE TABLE IF NOT EXISTS orders
(
    id String,
    country LowCardinality(String),
    status LowCardinality(String),
    amount Decimal(12, 2),
    created_at DateTime64(3, 'UTC')
)
ENGINE = MergeTree
ORDER BY (created_at, id);

INSERT INTO orders VALUES
    ('o1', 'NZ', 'paid', 120.50, '2026-09-01 10:00:00'),
    ('o2', 'NZ', 'paid', 80.00, '2026-09-02 11:30:00'),
    ('o3', 'AU', 'paid', 200.00, '2026-09-02 12:00:00'),
    ('o4', 'AU', 'refunded', 50.00, '2026-09-03 09:15:00'),
    ('o5', 'US', 'paid', 310.25, '2026-09-04 16:45:00');
```

**3. Define a dataset and serve it.** Save this as `app.py`:

<!-- getting-started: app.py -->
```python
import os
import secrets

from hypequery.datasets import create_dataset_client, dataset, dimension, measure
from hypequery.execution import ClickHouseConnection, create_clickhouse_executor
from hypequery.serve import (
    Credential,
    HttpSecurity,
    Principal,
    create_api,
    create_dataset_endpoint,
    to_asgi_app,
)

orders = dataset(
    "orders",
    source="orders",
    description="One row per customer order.",
    time_key="created_at",
    dimensions={
        "id": dimension.string(),
        "country": dimension.string(),
        "status": dimension.string(),
        "createdAt": dimension.timestamp(column="created_at"),
    },
    measures={
        "revenue": measure.sum("amount"),
        "orderCount": measure.count("id"),
    },
)

executor = create_clickhouse_executor(
    ClickHouseConnection(
        host=os.environ.get("CLICKHOUSE_HOST", "localhost"),
        port=int(os.environ.get("CLICKHOUSE_PORT", "8123")),
        database=os.environ.get("CLICKHOUSE_DATABASE", "default"),
        username=os.environ.get("CLICKHOUSE_USERNAME", "default"),
        password=os.environ.get("CLICKHOUSE_PASSWORD", ""),
    )
)
client = create_dataset_client(executor=executor)

# A development token. Replace this with your real authentication (JWT, API keys).
DEV_TOKEN = os.environ["HYPEQUERY_DEV_TOKEN"]


def authenticate(credential: Credential) -> Principal | None:
    if secrets.compare_digest(credential.value, DEV_TOKEN):
        return Principal(subject="developer")
    return None


api = create_api(
    auth=authenticate,
    security=HttpSecurity(allowed_hosts=("127.0.0.1", "localhost")),
    development_docs=True,
)
create_dataset_endpoint(dataset=orders, client=client).install(api, "/datasets/orders/query")

app = to_asgi_app(api)
```

**4. Run the development server** from the directory containing `app.py`:

<!-- getting-started: run -->
```bash
export HYPEQUERY_DEV_TOKEN=dev-secret
export CLICKHOUSE_PASSWORD=...  # and CLICKHOUSE_HOST / CLICKHOUSE_DATABASE if needed
python -m hypequery.serve.dev app:app --reload
```

The development runner listens on `127.0.0.1:8000` only. Binding anywhere else
(`--host 0.0.0.0`) works but raises an `ExternalBindWarning`: the runner is
not hardened for a network. It refuses APIs created with a `ProductionProfile`;
run those with [`start_server`](#production-process). From Python, call
`serve_dev(api)` or `serve_dev("app:app", reload=True)`
(`run_dev` remains available for compatibility). `app` is a plain ASGI
application, so any ASGI server runs it too: `uvicorn app:app`.

**5. Query it:**

<!-- getting-started: query -->
```bash
curl -s -X POST http://127.0.0.1:8000/datasets/orders/query \
  -H "Authorization: Bearer $HYPEQUERY_DEV_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "dimensions": ["country"],
    "measures": ["revenue", "orderCount"],
    "filters": [{"field": "status", "operator": "eq", "value": "paid"}],
    "orderBy": [{"field": "revenue", "direction": "desc"}]
  }'
```

<!-- getting-started: response -->
```json
{"data":[{"country":"US","revenue":"310.25","orderCount":"1"},{"country":"NZ","revenue":"200.50","orderCount":"2"},{"country":"AU","revenue":"200.00","orderCount":"1"}]}
```

Measure values are strings on the HTTP wire, so decimals keep their precision.
A request without the token gets `401`. Interactive docs are at
<http://127.0.0.1:8000/docs> because the app opts in with
`development_docs=True`; production apps keep them closed.

Next steps: [add tenant isolation](#serving-over-http), relationships
([dataset definitions](#dataset-definitions)), and the
[production profile](#production-process) before deploying.
`scripts/getting_started.py` runs this walkthrough end to end in CI.

## Python CLI

Install `hypequery[server,clickhouse]` for the complete onboarding path (the
`django` or `flask` extra instead for those scaffolds, and `fastapi` beside it
for the FastAPI one), then:

```bash
hypequery init
```

In a terminal, `hypequery init` asks for whatever its flags leave unset: where
to create the project, how to reach ClickHouse (from your environment, or a URL
and credentials typed in and used only to read the schema), which tables when
the database has more than ten, the tenant column when one looks likely, and
which app to scaffold (standalone, FastAPI, Django or Flask, defaulting to the
one it finds). It ends with the same choices as flags, e.g.
`hypequery init analytics --framework django --tenant-column org_id`. Every
flag answers its question; `--no-interactive`, a `CI` environment variable, or
input that is not a terminal skips the questions entirely and uses the defaults.

Then `cd` into the project and run `hypequery dev`. The CLI reads `.env.local`
and `.env` from the folder you run it in, so connection settings can live in a
gitignored `.env`; variables already set in your shell win over both files.

`hypequery init --path <directory>` (or a positional directory) inspects your
configured ClickHouse database by default. Use `--tables` and `--exclude-tables`
to choose tables, and `--tenant-column <column>` to set `tenant_key` on every
table that has it. The selection and tenant column are recorded in
`schema.json`, and `hypequery generate datasets` reuses them unless given
`--tables`, `--exclude-tables` or `--all-tables`, and `--tenant-column` or
`--no-tenant-column`. The scaffold's `.env.example` and README
repeat how discovery connected (`CLICKHOUSE_URL`, or the host, port and TLS
setting), without credentials. Generated definitions and an exact schema snapshot describe
your actual tables; existing output paths are never overwritten. A table's or
column's ClickHouse `COMMENT` becomes its dataset's or dimension's
`description`, which client contracts and MCP agents see; whitespace is
collapsed to single spaces to fit the deployment contract. Install the
`clickhouse` extra and set connection settings (exported, or in `.env`) before running init.
Only explicit `--skip-connection` generates the offline orders demo and `seed.sql`.

`--framework` chooses the application written beside `datasets.py`; every
choice also works with `--skip-connection`:

| `--framework` | Writes | Run with |
| --- | --- | --- |
| `standalone` (default) | `app.py`: `create_api` served as plain ASGI, no web framework | `hypequery dev` |
| `fastapi` | a FastAPI `app.py` mounting the API, and a route of your own | `uvicorn app:app --reload` |
| `django` | a small Django project (`settings.py`, `urls.py`, `manage.py`) and `analytics.py` | `python manage.py runserver` |
| `flask` | a Flask `app.py` | `flask --app app run` |

The Django and Flask apps serve hypequery's endpoints natively (`urls(api)`,
`blueprint(api)`) twice: at `/api/analytics` behind the framework's own login
(`django_user`, `flask_session`) with the same-origin check, for
`@hypequery/react` on pages the app serves, and at `/api/agents` behind a
bearer token, for `@hypequery/mcp` and scripts. Until you wire them to your
login, Flask's session API refuses everyone, and tenant-scoped datasets refuse
signed-in Django users. The generated README walks through both.

FastAPI has no login of its own, so the FastAPI app mounts the bearer-token API
at `/api/agents` (`app.mount("/api/agents", to_asgi_app(api))`) and adds
`/analytics/<dataset>`, a route of your own that queries as the principal its
`current_principal` dependency returns; that refuses everyone until you wire it
to your login. The generated project depends on `fastapi` itself: hypequery
has no FastAPI extra, because mounting needs none. Starlette and Litestar apps
can mount the standalone `app` the same way.

`hypequery dev [module:app]` defaults to `app:app` on `127.0.0.1:8000` with reload
enabled. Use `--no-watch`, `--hostname` or `-p`/`--port` to change those options.
`--no-reload` and `--host` remain supported aliases. The target is an API from
`create_api` or its `to_asgi_app` application. Serving requires the `server`
extra (uvicorn); apps using ClickHouse also need `clickhouse`. The command
retains the development runner's external-bind warning and refuses
production-profile APIs. Use `start_server` for production serving.

`hypequery --help`, `hypequery init --help`, `hypequery dev --help` and
`hypequery --version` (also `-V`) work without extras.
`hypequery help [init|dev]` also shows command help. `python -m hypequery` invokes the same
CLI. Exit codes are `0` for success/help, `1` for runtime failures and `2` for
invalid command usage. No Node tooling is required.

Python keeps `-h` for help; use `--hostname` for the bind address.
Shared CLI commands and supported options use the TypeScript names.
Python entrypoints use `module:attribute`, and scaffolding defaults to the current
directory. See the [cross-language naming audit](https://github.com/hypequery/hypequery/blob/main/plans/python-typescript-naming-parity.md)
for the SDK and pending beta features.

## Install extras

```bash
pip install hypequery
pip install "hypequery[clickhouse]"
pip install "hypequery[clickhouse-async]"
pip install "hypequery[server]"
pip install "hypequery[jwt]"      # JWT auth for hypequery.serve
pip install "hypequery[django]"   # or [flask]
pip install "hypequery[pandas]"   # or [polars], [arrow]
```

| Extra | Adds | Needed for |
|---|---|---|
| (none) | pydantic, anyio | defining datasets, planning, `to_sql()`, protocol artifacts, and `hypequery.serve` under any ASGI server |
| `clickhouse` | clickhouse-connect | `create_clickhouse_executor` and `hypequery init` / `generate` |
| `clickhouse-async` | clickhouse-connect with aiohttp | `create_async_clickhouse_executor`; also covers everything `clickhouse` does |
| `server` | uvicorn | `start_server` and `hypequery dev` |
| `jwt` | PyJWT, cryptography | `jwt_strategy` and `analytics_token_issuer` |
| `django` | Django, clickhouse-connect | `hypequery.contrib.django` |
| `flask` | Flask, clickhouse-connect | `hypequery.contrib.flask` |
| `pandas` / `polars` / `arrow` | that library | `result.to_pandas()` / `to_polars()` / `to_arrow()` |

Combine them as needed, for example `"hypequery[server,clickhouse-async]"`.
`hypequery.serve` needs no web framework: FastAPI, Starlette and Litestar apps
mount an API as plain ASGI.
Without `clickhouse-async`, `create_async_clickhouse_executor` raises an error
naming the extra to install.

The SDK is organised as:

- `hypequery.protocol` for the language-neutral artifact contracts;
- `hypequery.datasets` for dimensions, measures, metrics, and relationships;
- `hypequery.execution` for sync and async ClickHouse execution;
- `hypequery.serve` for a framework-neutral, authenticated HTTP API and its ASGI adapter;
- `hypequery.contrib` for Django, Flask and SQLAlchemy glue.

Python and TypeScript implement the same specifications and run against the same conformance fixtures. The goal is identical semantic and deployment artifacts across both languages, not a line-for-line port of the TypeScript runtime.

## Querying datasets

`create_dataset_client` is the entry point for running semantic queries. It
plans each query, hands the compiled statement to an executor, and returns
rows keyed by column name.

```python
from hypequery.datasets import (
    DatasetQuery,
    ExecutionContext,
    create_dataset_client,
    create_dataset_registry,
    filter,
    tenant,
)
from hypequery.execution import ClickHouseConnection, create_clickhouse_executor

executor = create_clickhouse_executor(ClickHouseConnection(host="localhost", database="analytics"))
client = create_dataset_client(
    executor=executor, registry=create_dataset_registry(orders, customers)
)

result = client.execute(
    "orders",
    DatasetQuery(
        dimensions=("customer.country",),
        measures=("revenue",),
        filters=(filter.eq("status", "paid"),),
    ),
    context=ExecutionContext(tenant=tenant("org_123")),
)
result.data  # ({"customer.country": "NZ", "revenue": "1200.50"}, ...)
result.meta  # query_id, row_count, timing_ms
executor.close()
```

A target is a `Dataset` or the name of a registered dataset. The registry also
resolves relationship targets, so pass one when a query traverses a
relationship. A query can also be a plain mapping with `DatasetQuery`'s field
names (`order_by`, not the HTTP wire's `orderBy`); it is validated strictly and
unknown keys are rejected. The tenant always comes from the trusted
`ExecutionContext`, never from the query.

In a request handler, bind the client to the tenant your auth layer resolved
and pass that on instead of the client itself:

```python
scoped = client.for_tenant(tenant(principal.org_id))
scoped.execute("trips", request_body)
```

`request_body` here is your own handler's JSON, with the same field names. To
serve the HTTP wire format (`orderBy`, `includeMeta`) that `@hypequery/react`
and generated clients send, mount hypequery's endpoints instead (`create_api`,
`urls(api)` or `blueprint(api)`).

A tenant-bound client has only `execute`, `validate`, and `to_sql`. Every
query runs as the bound tenant. A context naming a different tenant is refused
with `forbidden` (`HQ_CAPABILITY_TENANT_MISMATCH`). Binding requires exactly
one tenant: `tenants()` with multiple identifiers and `all_tenants()` are
refused, including when constructing a bound client directly.

`client.validate(...)` reports whether a query would plan without running it.
`client.to_sql(...)` returns the redacted debug statement, which has no values
and cannot be executed. For async code, use `create_async_dataset_client` with
an async executor and `await client.execute(...)`. The client does not own the
executor, so close the executor when the application shuts down.

### Having conditions

`having` filters on aggregated measure values, after grouping: for example,
customers whose revenue exceeds 10,000.

```python
DatasetQuery.model_validate(
    {
        "dimensions": ["customerId"],
        "measures": ["revenue"],
        "having": [{"measure": "revenue", "operator": "gt", "value": 10_000}],
    }
)
```

Each condition must name a selected measure. Operators are `eq`, `neq`, `gt`,
`gte`, `lt`, `lte`, `between`, `in` and `notIn`. Values are finite numbers: a
two-item list for `between`, a non-empty list for `in`/`notIn`. Conditions are
AND-ed, bound as parameters, and count against `limits.max_filters`. The
statement repeats the measure's aggregate in `HAVING` rather than referencing
its alias. Queries with conditions bypass the result cache until the RFC 0009
cache preimage carries `having`. Dataset endpoints accept `having`; metric
endpoints refuse it. This matches `@hypequery/datasets`.

### Measures across relationships

A query can select a target's base measure as `<relationship>.<measure>`, one
hop over a `belongs_to` or `has_one` relationship:

```python
from hypequery.datasets import order

client.execute(
    "orders",
    DatasetQuery(
        dimensions=("status",),
        measures=("revenue", "customer.customerCount"),
        order_by=(order.desc("customer.customerCount"),),
    ),
    context=ExecutionContext(tenant=tenant("org_123")),
)
```

The target rows that count are the ones the selected base rows reach. Base
filters and the base tenant decide which orders take part. The target
measure's own filters apply to customer columns, and the join carries the
target's tenant predicate. An order with no matching customer keeps its own
measures but contributes nothing to the customer aggregate.

A `belongs_to` join repeats each customer once per matching order, so only
duplicate-insensitive aggregates are selectable through it: `count_distinct`,
`min`, `max`, `arg_max` and `arg_min`. A declared `has_one` permits every
aggregate, including `sum`, `count` and `avg`; the declaration is trusted.
`has_many`, deeper paths, SQL-backed target measures, and target measures whose
field or filters use SQL-backed dimensions are rejected. Selecting one name as
both a dimension and a measure is rejected.

Catalog relationship entries list the safe names under `measures`, they are
orderable, and discovery includes them. This matches `@hypequery/datasets`.

## DataFrames

Rows keep JSON-safe values: decimals, dates and datetimes are strings, so
nothing loses precision on the way to an HTTP response. For analysis, convert a
result with the extra for your library installed:

```python
result = client.for_tenant(tenant("acme")).execute(
    "orders", {"measures": ["revenue", "orders"], "by": "month"}
)
frame = result.to_pandas()  # or result.to_polars(), result.to_arrow()
frame.dtypes
# period     datetime64[us, UTC]   (the query's timezone)
# revenue                float64
# orders                   Int64
```

Column types come from the dataset definition, not from the values, so an
empty result is typed too; `result.column_types` lists them. Timestamps become
timezone-aware datetimes in the query's timezone (`result.timezone`, UTC unless
the query or client sets one), so a `period` bucket keeps its local day. Counts
become nullable 64-bit integers, other numbers floats (a number column holding
only whole values stays an integer), and booleans nullable booleans. Integers
beyond `Int64` become unsigned 64-bit columns, or exact decimals past `UInt64`.
Pass `decimals="decimal"` to keep exact `Decimal` values instead of floats. A column whose type the definition cannot tell, such as `min` over a
column no dimension describes, converts as returned.

## Result caching

Pass a `ResultCache` to cache results. Keys follow RFC 0009 and RFC 0013: the
store only ever sees opaque `hq1.…` keys, never queries, tenant ids, or filter
values.

```python
from hypequery.datasets import MemoryCacheStore, ResultCache, create_dataset_client

cache = ResultCache(
    store=MemoryCacheStore(max_entries=1_000),
    project="acme",
    environment="production",
    ttl_seconds=60,
)
client = create_dataset_client(executor=executor, registry=registry, cache=cache)
result = client.execute("orders", query, context=context)
result.meta.cache  # "miss", then "hit" for the same request
```

- **Tenant isolation.** Entries are keyed by tenant fingerprint, so two tenants
  never share an entry. Tenant-free, tenant-scoped, and `all_tenants()`
  executions never share one either.
- **Equivalent requests share an entry.** Filter order, `offset: 0`, and empty
  lists do not create separate entries.
- **Never fails a query.** A store error is treated as a miss: the query runs,
  `meta.cache == "miss"`, and `on_error` sees the failure. So is a stored value
  that isn't well-formed `CachedRows` with exactly this query's columns. A query with no
  portable form runs uncached and reports `meta.cache == "bypass"`, as does
  `use_cache=False`, which skips the cache for one call.
- **The secret is optional.** Without one, the cache generates a random secret
  for its own lifetime. Keys stay opaque, and entries last as long as the
  process, which is all an in-memory store needs.
- **Shared stores need a secret to share entries.** For a store such as Redis,
  pass `secret=bytes.fromhex(os.environ["HYPEQUERY_CACHE_SECRET"])`: 32+ random
  bytes, the same on every instance, distinct per environment, and never
  shipped. Without one, instances stay isolated from each other, and a warning
  says so. Increment `key_version` when you rotate it.
- **Sharing across runtimes.** Set `definition_identity` to the deployed bundle
  identity to share entries with other runtimes serving the same release.
  Otherwise a digest of the local definitions is used, and any definition
  change starts fresh.

`CacheStore` is a small protocol (`get`, `set`), so a shared store such as
Redis can be plugged in. Stores are called synchronously, including from the
async client.

## Django, Flask and SQLAlchemy

The dataset client is a plain library: call it from a Django view or a Flask
route like any other. `hypequery.contrib` adds what each framework lacks, a
client per process that is created on first use and closed at exit, and a
client per request that is already bound to the caller's tenant.

Runnable versions of everything below live in `examples/`: `django_app.py`,
`flask_app.py`, `dataframes.py` (pandas) and `sqlalchemy_engine.py`. Each runs
against `examples/seed.sql`, and CI runs them against a live ClickHouse.

### Django

```python
# settings.py
INSTALLED_APPS = [..., "hypequery.contrib.django"]
MIDDLEWARE = [
    ...,
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "hypequery.contrib.django.HypequeryMiddleware",
]
HYPEQUERY = {
    "URL": None,  # None reads CLICKHOUSE_URL or the CLICKHOUSE_* variables
    "REGISTRY": "analytics.datasets.registry",
    "TENANT": "analytics.tenancy.tenant_for_request",
}


# analytics/tenancy.py
def tenant_for_request(request):
    user = request.user
    return user.organization_id if user.is_authenticated else None


# views.py
def revenue(request):
    result = request.analytics.execute("orders", {"measures": ["revenue"], "by": "month"})
    return JsonResponse({"data": list(result.data)})
```

`request.analytics` is built on first access, bound to the tenant `TENANT`
returns. With no tenant it is the unscoped client, and datasets with a
`tenant_key` refuse to run. In an `async def` view the same attribute is the
async client, so `await` its calls. There, `TENANT` runs through `sync_to_async` on
the first query, so it may use the ORM just as in sync views. `manage.py check` validates `HYPEQUERY` (bad import
paths, URLs, keys) without connecting. Outside a request, `get_client()` and
`get_async_client()` return the process's clients. `get_client()` does not
connect until its first query, so modules can hold it at import time and the
project starts even with ClickHouse down. Other keys:
`READONLY_POLICY`, `TIMEZONE`, `MAX_CONCURRENT`.

### Flask

```python
from flask import Flask
from flask_login import current_user
from hypequery.contrib.flask import Hypequery

hq = Hypequery()


@hq.tenant_loader
def current_tenant():
    return current_user.org_id if current_user.is_authenticated else None


def create_app():
    app = Flask(__name__)
    app.config["HYPEQUERY_REGISTRY"] = "analytics.datasets:registry"
    hq.init_app(app)

    @app.get("/revenue")
    def revenue():
        result = hq.client.execute("orders", {"measures": ["revenue"]})
        return {"data": list(result.data)}

    return app
```

`hq.client` is bound to the request's tenant once per request; `async def`
routes use `hq.async_client`. Config keys: `HYPEQUERY_URL` (else the
environment), `HYPEQUERY_REGISTRY`, `HYPEQUERY_READONLY_POLICY`,
`HYPEQUERY_TIMEZONE`, `HYPEQUERY_MAX_CONCURRENT`. `init_app` validates them
without connecting. The client is not closed in `teardown_appcontext`, which
runs after every request; it lives for the process, and connects on its first
query. Outside a request (CLI commands, background jobs, setup code in
`create_app`), `hq.client_for(app)` returns the app's client with no app context
and without connecting.

A decorator on an `async def` route must itself be async-aware. A plain sync
wrapper (a hand-written `login_required`, say) returns the route's coroutine
unawaited, and Flask answers 500. Check `inspect.iscoroutinefunction(view)` and
wrap with an `async def`, as Flask's own `ensure_sync` expects.

### hypequery's HTTP endpoints

These integrations run queries inside your Django views and Flask routes. The
generated React hooks and the MCP bridge instead call hypequery's own HTTP
endpoints (`hypequery.serve`; see "Serving over HTTP"). Django and Flask serve
those natively, with no second app and no FastAPI:

```python
# Django: urls.py
from django.urls import include, path
from hypequery.contrib.django import get_client, urls
from hypequery.serve import create_api

api = create_api(auth=authenticate, client=get_client(), datasets={"orders": orders})
urlpatterns = [path("api/analytics/", include(urls(api)))]


# Flask: in create_app()
from hypequery.contrib.flask import blueprint

api = create_api(auth=authenticate, client=hq.client_for(app), datasets={"orders": orders})
app.register_blueprint(blueprint(api), url_prefix="/api/analytics")
```

Every request below the prefix reaches the API, which answers exactly as it
does under any other adapter: authentication before the body, the body policy,
security profile, request ids and the error envelope. `ServeRequest.raw` is the
framework's request (`HttpRequest`, Flask's `Request`).

- **One event loop.** Django's view is async under ASGI, running the API on
  the server's loop, and sync under WSGI. Under WSGI, and in Flask, the API
  runs on one event loop per process, started on its own thread at the first
  request, while the request's thread waits. No loop is created per request,
  and a threaded server (gunicorn `--threads`, waitress) serves requests
  concurrently on it. Host code (your authenticator, a sync dataset client)
  sees the request thread's context, so Flask's `request` and `g` work in it.
- **Bodies** are read from the request's stream, lazily and bounded by
  `max_body_bytes`; Django's `DATA_UPLOAD_MAX_MEMORY_SIZE` plays no part. In
  Flask, a body over `MAX_CONTENT_LENGTH` is refused as too large. Some
  servers receive the whole body before the application runs (Django's ASGI
  handler, waitress), so cap request sizes at the server or proxy too.
- **Any prefix works**, including one with URL variables. Client contracts and
  discovery name the paths the request was routed under, unless
  `create_api(client_mount_path=...)` names where the API is reached.
- **CSRF.** A header credential (`Authorization: Bearer`, an API key header,
  a JWT) is one a browser never attaches on its own, so Django's views and
  Flask's blueprint for it are CSRF-exempt, Flask's from Flask-WTF's
  `CSRFProtect` whether it is set up before or after the blueprint. Django's
  CSRF middleware and `CSRFProtect` stay in place for the rest of the app, and
  check an API that uses the app's own login (below).

#### Your own login, with no token

A React page served by the same app can call the endpoints with the session
the user already has, as TypeScript's `fromContext` does. `django_user` and
`flask_session` read it:

```python
# Django: the user from AuthenticationMiddleware (sync and async views).
from hypequery.contrib.django import django_user

api = create_api(
    auth=django_user(lambda user: Principal(subject=str(user.pk), tenant_id=str(user.org_id))),
    client=get_client(),
    datasets={"orders": orders},
)

# Flask: Flask-Login's current_user when the app uses it, else the session.
from hypequery.contrib.flask import flask_session

api = create_api(
    auth=flask_session(lambda user: Principal(subject=user.get_id(), tenant_id=user.org_id)),
    ...,
)
```

The mapping receives a signed-in user only; an anonymous one is answered
`401`. Under WSGI and in Flask it runs on the request's own thread, so the
ORM, Flask-Login's user loader and thread-local database sessions behave as
in your views; under Django ASGI the user is loaded through the async ORM.
Both are built on `hypequery.serve.from_context(extract)`, whose `extract`
receives the `ServeRequest` and reads the session from `request.raw`, for any
other framework.

A session cookie is sent by the browser, not the page, so these APIs are
protected against cross-site request forgery:

- **The same-origin check** (`same_origin=True`, the default) refuses a
  `POST`, `PUT`, `PATCH` or `DELETE` with `403 FORBIDDEN` unless the browser
  marks it `Sec-Fetch-Site: same-origin` (or `none`), or its `Origin` is one
  your `HttpSecurity(cors=CorsPolicy(origins=...))` names. It runs in the
  core, under every adapter. A browser without Fetch Metadata (Safari before
  16.4) sends only `Origin`: list your own origin in the CORS policy to serve
  it. A production profile refuses `same_origin=False`.
- **Django's CSRF middleware** also checks these requests: the page sends the
  `csrftoken` cookie's value as `X-CSRFToken`, read per request (signing in
  rotates it). With `@hypequery/react`:

  ```ts
  const csrfToken = () => document.cookie.match(/(?:^|; )csrftoken=([^;]*)/)?.[1];
  const client = createHypequeryClient({
    baseUrl: '/api/analytics',
    headers: () => ({ 'X-CSRFToken': csrfToken() }),
  });
  ```

  A view rendering the page sets the cookie (`get_token(request)` or
  `@ensure_csrf_cookie`). Django's own `403` page answers a missing token.
- **Flask-WTF's `CSRFProtect`**, when the app uses it, checks them the same
  way: the page sends `generate_csrf()`'s token (rendered into the page, for
  example with `csrf_meta_tag()`) as `X-CSRFToken`, and Flask-WTF's own `400`
  answers a missing one. Without Flask-WTF, the same-origin check is Flask's
  protection.

The tenant still comes only from the principal: no header, query parameter or
body field can choose it.

`examples/django_app.py` and `examples/flask_app.py` serve the orders dataset
both ways, behind their own login for a same-origin React page and behind a
bearer token for `@hypequery/mcp`; `examples/README.md` walks through them. Any other WSGI framework or server uses
`hypequery.serve.to_wsgi_app(api)`, and any ASGI one `to_asgi_app(api)`.

### Results in your own views versus hypequery's endpoints

A view that returns `result.data` as JSON sends the values the client returns:
counts as integers, other numbers as floats or decimal strings. hypequery's
HTTP endpoints, the generated React client and MCP send every non-null measure
as a string, matching TypeScript; nulls stay null. A count of `41321` arrives
as `"41321"` there. Pick one shape per API and serialize to it explicitly: to
match hypequery's endpoints, convert non-null measures to strings and keep
nulls. `result.to_pandas()` is for numeric analysis, not for matching the HTTP
shape; by default it converts decimals to floats.

### Async views and shutdown

Neither framework tells an application that the process is stopping, so an
aiohttp-based executor created there leaks its session at exit. The async
client these integrations hand out runs the sync HTTP driver on worker threads
(`create_async_from_sync_clickhouse_executor`) instead, and is closed by an
`atexit` hook. Its admission queue belongs to one event loop, so the
integrations keep one per live loop: one under an ASGI server, and one per
in-flight request when a WSGI server runs async views, where every request gets
a fresh loop. Clients are rebuilt in a forked worker rather than shared with
the parent.

### SQLAlchemy

To point hypequery at the server a SQLAlchemy engine uses:

```python
from hypequery.contrib.sqlalchemy import executor_from_engine

engine = create_engine("clickhousedb://reader:pw@ch:8123/analytics")
client = create_dataset_client(executor=executor_from_engine(engine), registry=registry)
```

This reads the engine's URL and opens hypequery's own clients; it never
borrows a pooled connection, so closing either side leaves the other alone.
The engine must use the HTTP interface (`clickhousedb://` or
`clickhouse+http://`). `clickhouse+native://` is refused: hypequery binds
values as server-side parameters, which only the HTTP interface carries.
`connection_from_engine(engine)` returns the `ClickHouseConnection` instead.

## Serving over HTTP

`hypequery.serve` builds an HTTP API that needs no web framework. As in
TypeScript's `createAPI`, `create_api(...)` returns a transport-agnostic `Api`;
an adapter puts it on a server. Every route requires authentication unless you
explicitly make it public:

```python
from hypequery.serve import (
    Call,
    Credential,
    HttpSecurity,
    Principal,
    ServeResponse,
    create_api,
    to_asgi_app,
)


async def authenticate(credential: Credential) -> Principal | None:
    claims = await verify_jwt(credential.value)  # your code; for JWTs see jwt_strategy
    if claims is None:
        return None
    return Principal(
        subject=claims["sub"],
        scopes=frozenset(claims.get("scope", "").split()),
        tenant_id=claims.get("org_id"),
    )


api = create_api(
    auth=authenticate,
    client=client,  # a dataset client
    datasets={"trips": trips},  # POST /datasets/trips/query
    security=HttpSecurity(allowed_hosts=("api.example.com",)),
)


async def health(call: Call) -> ServeResponse:
    return ServeResponse.json({"status": "ok"})


api.add_route("GET", "/health", health, public=True)

app = to_asgi_app(api)  # uvicorn app:app, or mount it in another ASGI app
```

- **Serving.** `to_asgi_app(api)` is a pure ASGI application: run it with
  uvicorn or any ASGI server, or mount it in FastAPI, Starlette or Litestar
  (`host.mount("/analytics", to_asgi_app(api))`). It reads the request body
  lazily, cancels a query whose caller disconnects, and runs an optional
  `lifespan=` context at startup and shutdown; a mounted app's host runs its
  own. `to_wsgi_app(api)` is the WSGI application, for gunicorn, waitress or
  any WSGI framework; it runs the API on one event loop per process. WSGI
  never reports a caller who has gone, so there a query ends at its deadline.
  Django and Flask serve the API natively: see "hypequery's HTTP endpoints".
  `start_server(api)` runs a production profile under uvicorn, and
  `await api.handle(ServeRequest(...))` serves one request with no server.
- **Endpoints.** `datasets={"name": dataset}` serves
  `POST /datasets/<name>/query`, and `metrics={"name": create_metric_endpoint(...)}`
  serves `POST /metrics/<name>`, as in TypeScript. With either, `GET /discovery`
  lists their datasets, authenticated by default (`discovery=False` leaves it
  out). `add_dataset_endpoint(api, path, ...)` and the other `add_*` functions
  serve endpoints at any other path; `base_path=` prefixes every route.
- **Your own routes.** `api.add_route(method, path, handler)` serves a
  handler that receives a `Call` (the request, the caller's `call.auth` and
  `call.state.request_id`) and returns a `ServeResponse`. Pass `input=` a
  Pydantic `TypeAdapter` to have the body read and validated first, as
  `call.input`; without it the body is never read.
- **Credentials** are read from one header: `Authorization: Bearer <token>`
  by default, or `create_api(credentials=api_key())` for `X-Api-Key`.
  Query strings, cookies, and bodies are never read. A repeated,
  oversized, or malformed header is refused before your authenticator runs.
  To use your app's own login instead, pass `auth=from_context(extract)` (see
  "Your own login, with no token").
- **Your authenticator** (`auth=`) receives only the opaque `Credential`,
  never the request, and returns a `Principal`. To reject a credential,
  return `None` or raise `InvalidCredential`. Wrap your token library's
  errors in it: anything else that escapes is treated as authentication being
  down and answered with a fixed 503. The exception never reaches the
  response. The authenticator may be sync (run in a worker thread) or async.
- **Authentication runs before the body is read**, so an unauthenticated
  caller cannot make the server read or parse anything.
- **The tenant** comes from the principal: `tenant_id` scopes the request, and
  a principal without one is tenant-free. Pass `tenant=` a resolver to decide
  it yourself. A resolver must return a single-tenant scope or `None`; it
  cannot grant `tenants()` with multiple identifiers or `all_tenants()`. No
  header, query parameter, or body field can supply or change the tenant.
- **Public routes** are an explicit `public=True` on the route, or
  `EndpointPolicy(public=True)` on an endpoint.

Every route also has a fixed body policy, applied after authentication:
- bodies must be `application/json` with no charset or `charset=utf-8`,
  otherwise `415`;
- a `Content-Encoding` other than `identity` (gzip, br, ...) gets `415`: the
  size cap counts the bytes received, so compressed bodies are refused;
- a body that isn't valid JSON, including invalid UTF-8 or nesting past
  Python's recursion limit, gets `400 VALIDATION_ERROR`;
- bodies are capped at `create_api(max_body_bytes=...)`, 1 MiB by default,
  and counted as they stream, so a missing `Content-Length` doesn't get
  around the cap;
- a repeated or non-numeric `Content-Length` gets `400`.

Authenticated responses are always sent with `Cache-Control: no-store`. The
API matches a route on its method and its path as sent, like TypeScript; an
unknown path or method is `404 NOT_FOUND`, with no redirect for a trailing
slash.

### JWT authentication

With the `jwt` extra, `jwt_strategy` is a ready-made authenticator for JWT
bearer tokens. It is TypeScript's `createJwtStrategy`: the same claims, the
same checks, and tokens either language mints verify in the other.

```python
from hypequery.serve import analytics_token_issuer, create_api, jwt_strategy, to_asgi_app

# Tokens from an identity provider, verified against its published keys.
api = create_api(
    auth=jwt_strategy(
        jwks_url="https://example.auth0.com/.well-known/jwks.json",
        issuer="https://example.auth0.com/",
        audience="https://api.example.com",
    ),
    datasets={"orders": orders},
    client=client,
)
app = to_asgi_app(api)

# Or tokens you mint for your own frontend, with a shared secret.
issue_token = analytics_token_issuer(SECRET, audience="analytics")
api = create_api(auth=jwt_strategy(secret=SECRET, audience="analytics"), ...)
token = issue_token("user-1", tenant_id="acme", roles=["analyst"])
```

- **Claims map as in TypeScript**: `sub` is the subject, `org_id` the tenant,
  `roles` the roles, and `scope` (space-separated) or `scopes` (an array) the
  scopes. A token without `sub` is refused. Pass `map_claims=` to map claims
  yourself; it returns a `Principal`, or `None` to refuse the token.
- **Checks**: the signature; `issuer` and `audience` when you configure them;
  `exp` and `nbf` when the token has them, with no clock skew unless you pass
  `leeway=`. Algorithms default to HS256 for a secret and RS256 for a key set.
  `alg: none` is never accepted, and a key set never verifies an HMAC token.
- **Secrets** must be at least as long as the hash (32 bytes for HS256).
- **Key sets** are fetched off the event loop, cached for 10 minutes, and
  refetched for an unknown `kid` at most every 30 seconds. A fetch has a 5
  second timeout, follows no redirects, and must use https except on
  localhost. If the keys cannot be fetched the request gets a 503, not a 401.
- **The issuer** mints HS256 tokens (HS384/HS512 with `algorithm=`) carrying
  `sub`, `org_id`, `roles`, `iat`, `exp` (15 minutes by default, `expires_in=`)
  and the configured `iss` and `aud`.

### HTTP security profile

Pass `security=` to `create_api`:

```python
from hypequery.serve import CorsPolicy, HttpSecurity, create_api

api = create_api(
    auth=authenticate,
    security=HttpSecurity(
        allowed_hosts=("api.example.com",),
        cors=CorsPolicy(origins=("https://app.example.com",), allow_credentials=True),
        trusted_proxies=("10.0.0.0/8",),
    ),
)
```

- **Hosts.** `allowed_hosts` must name hosts; `*` is refused. A request for
  any other `Host` gets `400` and is never redirected. Without `security`, an
  API checks no host: leave it out only when the host application in front of
  it does.
- **CORS** is off unless `cors` is set. Origins must be exact
  `scheme://host[:port]` values. Credentialed CORS with `*` fails when the
  policy is built, as do wildcard methods or headers.
  Default allowed request headers include `X-Include-Meta`, used by React's
  infinite-query hooks to request pagination metadata.
- **Proxies.** `X-Forwarded-For` is honoured only from `trusted_proxies`. The
  client is the nearest forwarded address that isn't itself a trusted proxy.
  By default no proxy is trusted.
- **Request ids.** Every response carries a server-generated `x-request-id`,
  which a handler reads as `call.state.request_id`. A caller's `X-Request-ID`
  is never authoritative. If it is short printable ASCII, it is echoed back as
  `x-correlation-id`; otherwise it is dropped. That covers control
  characters, whitespace, look-alike letters, and values over 200 bytes.

### Errors

Every error from a served route uses the same envelope as `@hypequery/serve`:

```json
{"error": {"type": "UNAUTHORIZED", "message": "Access denied", "details": {"reason": "missing_credentials"}}}
```

Every error response is sent with `Cache-Control: no-store` and an
`x-request-id`. The shared fixtures in
[`specs/serve-http`](https://github.com/hypequery/hypequery/blob/main/specs/serve-http/fixtures/errors-v1/README.md) pin the
envelope for both languages.

- **What a handler raises:**
  - `ServeError(status, type, message)` is sent as written, like TypeScript's
    `ServeHttpError`;
  - a `CompiledQueryError` maps its RFC 0010 category to a status and type,
    for example a missed deadline becomes `504 GATEWAY_TIMEOUT`;
  - anything else is logged to the `hypequery.serve` logger with its request
    id and answered with a fixed `500`.

  A server-side failure's own text never reaches the body.
- **Validation errors** are `400 VALIDATION_ERROR` with
  `details.issues[].path`, as in TypeScript. The submitted values are never
  echoed back.

### Rate limiting

Add a `RateLimit` to every route, or to one:

```python
from hypequery.serve import RateLimit, add_dataset_endpoint, create_api

api = create_api(auth=authenticate, limits=[RateLimit(max=600, window_seconds=60)])
add_dataset_endpoint(
    api, "/trips", dataset=trips, client=client, limits=[RateLimit(max=60, window_seconds=60)]
)
```

It counts each request once, after authentication and before the body is
read, so a limited caller costs neither a parse nor a query. The API's limits
run before the route's, in order. A custom `key(request, auth)` receives the
`ServeRequest` and the caller. The defaults match TypeScript:
- the caller is the authenticated principal, or else the client address, as
  set by `HttpSecurity(trusted_proxies=...)` and never by a header the caller
  chose;
- exhaustion answers `429 RATE_LIMITED` with `Retry-After` and
  `X-RateLimit-*`;
- a store failure lets the request through, or with `fail_open=False`
  answers `503`.

`MemoryRateLimitStore` is bounded, at 100,000 callers by default. When every
slot has an active window, a new caller receives `503` until a slot expires;
active counters are never reset to make room. For several
processes, pass a `store` with an async `hit(key, window_seconds)` method.

## ClickHouse execution

The execution extra accepts `CompiledQuery` objects emitted by the planner.
Values travel through ClickHouse's named server parameters; the SQL statement
retains its typed placeholders. The result codec returns a `QueryRows` object
with stable column order and strict scalar values. Decimal values are strings
so callers do not lose precision.

```python
from hypequery.execution import ClickHouseConnection, create_clickhouse_executor

executor = create_clickhouse_executor(ClickHouseConnection(host="localhost", database="analytics"))
rows = executor.execute(compiled_query).named_rows()
executor.close()
```

A connection can also come from a URL or the environment:

```python
ClickHouseConnection.from_url("clickhouses://reader:pw@ch.example.com/analytics")
ClickHouseConnection.from_env()  # CLICKHOUSE_URL, or CLICKHOUSE_HOST, _PORT, ...
```

`clickhouse://` and `http://` are plain HTTP; `clickhouses://` and `https://`
use TLS. SQLAlchemy URLs for the HTTP interface (`clickhousedb://`,
`clickhouse+http://`) work too, with `?secure=true` or `?protocol=https` for
TLS. User and password are percent-decoded. Setting `CLICKHOUSE_URL` together
with any of the field variables is an error, and no error message repeats the
URL.

For async code, install `hypequery[clickhouse-async]` and await
`create_async_clickhouse_executor(connection)` and `executor.execute(compiled_query)`.
Call `await executor.aclose()` when the async executor is no longer needed.
Driver errors are mapped to the canonical safe error categories. Live parameter
tests run in CI against ClickHouse; local execution needs a ClickHouse service.

The synchronous executor factory opens a separate, short-timeout control
connection to stop in-flight queries on cancellation or deadline expiry. When
constructing `ClickHouseExecutor` with your own driver, supply a separate
`control_client` with permission to cancel its queries. Without it, interruption
is checked before and after the blocking call, but cannot stop that call early.
Cancelled results are never reported as a successful HTTP execution.

The async executor limits concurrent queries per client to eight by default.
`ExecutionContext.cancellation` may be a `threading.Event` or `asyncio.Event`;
the planner carries it into the compiled query. Caller cancellation and deadline
expiry issue a separate `KILL QUERY` command using the server query ID. A
cancelled ASGI task is treated as caller cancellation. For a synchronous driver
used inside an async application, `AsyncFromSyncClickHouseExecutor` (built by
`create_async_from_sync_clickhouse_executor(connection)`, which needs only the
`clickhouse` extra) runs query
work in a bounded worker pool with a separate control worker and supports the
same cancellation contract. Create the driver clients it wraps with
`autogenerate_session_id=False`, as the factories do: a clickhouse-connect
client bound to a session refuses concurrent queries, so with the default
client every query past the first fails while another is running. During
application shutdown, call `await executor.aclose()` to wait for workers and
close both supplied driver clients. `close()` stops admission and closes the
driver clients immediately without waiting for workers, for shutdown paths
with no event loop.

`ExecutionContext(deadline=Deadline.after(seconds))` bounds one execution;
`Deadline` is exported by `hypequery.datasets`. A query that is still running
when it expires is killed on the server and fails with `deadline-exceeded`.

### Grants for cancellation

`KILL QUERY` needs privileges a query-only user usually lacks. The control
connection signs in as the query user by default, and that user needs:

```sql
GRANT SELECT ON system.processes TO reader;
```

To keep the query user minimal, give cancellation its own user instead. It
needs both grants, because it stops queries another user started:

```sql
GRANT SELECT ON system.processes, KILL QUERY ON *.* TO hypequery_control;
```

```python
ClickHouseConnection(
    username="reader",
    password=reader_password,
    control_username="hypequery_control",
    control_password=control_password,
)
```

`ClickHouseConnection.from_env()` reads these from `CLICKHOUSE_CONTROL_USERNAME`
and `CLICKHOUSE_CONTROL_PASSWORD`. If ClickHouse refuses a `KILL`, the
executor logs one error naming these fixes on the
`hypequery.execution.cancellation` logger and stops asking. The query then
runs until `max_execution_time`, and the caller still gets `aborted` or
`deadline-exceeded`, though a synchronous caller gets it only once ClickHouse
stops the query: its driver call cannot return early. The native async executor needs the grant less, since its
driver also asks ClickHouse to cancel a readonly query when the connection
closes.

## Canonical protocol values

RFC 0001 tagged values and exact RFC 8785 canonical JSON are available from
`hypequery.protocol`:

```python
from hypequery.protocol import encode_canonical_value, integer_value

value = integer_value(42, bits=64, signed=True)
canonical_bytes = encode_canonical_value(value)
```

Python-native `int`, `Decimal`, `date`, timezone-aware `datetime`, `UUID`, and
`bytes` values use explicit constructors so type meaning is fixed before an
artifact is hashed. Validation never calls custom serializers or conversion
hooks.

## Portable identifiers

RFC 0002 simple and qualified logical identifiers are ASCII-only, preserve
their exact spelling, and carry distinct static types after validation:

```python
from hypequery.protocol import (
    parse_protocol_qualified_identifier,
    split_protocol_qualified_identifier,
)

name = parse_protocol_qualified_identifier("orders.customer.country")
segments = split_protocol_qualified_identifier(name)
```

These names are safe protocol nodes, not SQL identifiers, filenames, or URLs;
adapters must still quote or sanitize them for their destination domain.

## Portable expressions

RFC 0003 expression and semantic-query validators return detached, deeply
immutable dataclass models. The function, operator, aggregation, and grain
registries are closed, and products may lower—but not raise—the protocol's
depth, node-count, and collection limits:

```python
from hypequery.protocol import expression_to_data, validate_protocol_expression

expression = validate_protocol_expression(
    {
        "kind": "binary",
        "operator": "divide",
        "left": {"kind": "reference", "name": "revenue"},
        "right": {
            "kind": "call",
            "function": "nullIfZero",
            "args": [{"kind": "reference", "name": "orders"}],
        },
    }
)
portable_data = expression_to_data(expression)
```

Validation accepts strict plain data only. It never invokes mapping hooks,
serializers, callbacks, or arbitrary functions, and raw SQL is not an
expression node.

## SQL portability

SQL-backed dimensions and measures are portable only when their expression
fits the RFC 0003 subset. `compile_portable_sql_expression()` parses that
subset into the validated AST and reports everything else as a located
incompatibility, so a non-portable definition is surfaced rather than executed
with engine-specific meaning:

```python
from hypequery.datasets import compile_portable_sql_expression

result = compile_portable_sql_expression("revenue / nullIfZero(orders)")
if result.portable:
    expression, dependencies = result.expression, result.dependencies
else:
    issue = result.issues[0]  # code, message, and a start/end source span
```

The subset covers identifiers, literals, arithmetic, comparisons, literal `IN`
lists, literal `BETWEEN`, `LIKE`, boolean logic, parentheses, and the approved
formula functions. Statements, subqueries, casts, lambdas, comments, and
unapproved functions are non-portable by construction. Issue codes and source
offsets match `@hypequery/datasets` case for case, enforced by the shared
`sql-portability-v1` fixtures.

## Portable query schemas

RFC 0004 schemas describe the wire values a named query accepts and returns.
They are a closed node vocabulary — no regular expressions, format names,
validators, or callbacks — so a schema survives the trip between runtimes
without carrying executable behaviour:

```python
from hypequery.protocol import validate_protocol_schema

schema = validate_protocol_schema(
    {
        "kind": "object",
        "properties": {
            "limit": {"kind": "integer", "minimum": 1.0, "maximum": 100.0, "default": 10.0},
            "status": {"kind": "enum", "values": ["new", "paid", "shipped"]},
        },
        "required": ["status"],
        "unknownProperties": "reject",
    }
)
```

Validation returns a detached, deeply immutable model. Numbers are binary64
throughout, matching the reference implementation, so bounds and defaults are
written as `1.0` rather than `1`; a width-tagged integer is a *result value*
concept, not an API-schema one. A declared `default` is checked against its own
schema at validation time, and `UNSET` distinguishes an absent default from a
default of `null`.

## Dataset definitions

Definitions use strict, frozen Pydantic models. Helper spellings are Pythonic,
while serialized aggregation and relationship values preserve the same logical
meaning as `@hypequery/datasets`:

```python
from hypequery.datasets import (
    Dataset,
    DatasetLimits,
    belongs_to,
    dimension,
    filter,
    measure,
)

Customers = Dataset(
    name="customers",
    source="customers",
    dimensions={"id": dimension("string")},
)

Orders = Dataset(
    name="orders",
    source="orders",
    tenant_key="tenant_id",
    time_key="created_at",
    dimensions={
        "id": dimension("string"),
        "customerId": dimension("string", column="customer_id"),
        "status": dimension("string"),
        "amount": dimension("number"),
    },
    measures={
        "revenue": measure.sum("amount"),
        "orderCount": measure.count("id"),
        "uniqueCustomers": measure.count_distinct("customerId"),
        "completedRevenue": measure.sum("amount", filters=(filter.eq("status", "completed"),)),
    },
    relationships={
        "customer": belongs_to(
            lambda: Customers,
            from_field="customer_id",
            to_field="id",
        )
    },
    limits=DatasetLimits(max_dimensions=5, max_filters=10),
)
```

`from_field` and `to_field` name physical columns of the two sources, as in
TypeScript's `from`/`to`, not dimensions: here `customer_id` rather than the
`customerId` dimension that maps it. The target is a `Dataset` or a
zero-argument callable returning one, invoked once when the helper runs. The
target dataset must already be defined, even when using a callable.

A relationship can also join on a composite key: several column pairs that
must all be equal (RFC 0016). Pass `keys` instead of `from_field`/`to_field`:

```python
from hypequery.datasets import belongs_to

customer = belongs_to(
    lambda: Customers,
    keys=(("customer_id", "id"), ("region_code", "region")),
)
```

Each pair is a `(from, to)` tuple or a `RelationshipKey`. Every pair becomes an
equality inside the same single-match join, AND-ed with any tenant predicate,
and a NULL in any component never matches. Keys must be non-empty and must not
repeat a source or target column. The relationship keeps `from_field` and
`to_field` as its first pair, and catalogs, semantic contracts and deployment
contracts carry the full `keys` list. Single-key relationships serialize
unchanged.

Relationship callbacks are invoked once by the helper. Models retain only the
target dataset name, so `model_dump()` and `model_dump_json()` never serialize
Python functions. The `formula` helpers likewise build immutable symbolic
data for `measure.derived`, and `compile_formula()` lowers that data through
the RFC 0003 validator:

```python
from hypequery.datasets import compile_formula, formula, measure

average = measure.derived(
    formula.round(formula.divide("revenue", formula.null_if_zero("orders")), 2)
)
compile_formula(average.formula)  # the portable RFC 0003 expression
```

Every authoring helper lives in a namespace: `dimension.*`, `measure.*`,
`filter.*`, `order.*` and `formula.*`.

## Deployment contracts

RFC 0006 contracts are the validated, deterministic description of the
datasets managed execution can serve. Named queries, standalone metrics,
runtime artifacts, executable callbacks, credentials, and connection
configuration are all outside the contract — `queries`, `artifacts`, and
dataset `metrics` are invalid even when empty:

```python
from hypequery.protocol import prepare_protocol_deployment_contract

prepared = prepare_protocol_deployment_contract(contract_data)
prepared.canonical  # RFC 8785 JSON text
prepared.identity  # sha256 of "hypequery:deployment:v2\0" + canonical bytes
```

Identity is domain-separated, so a deployment hash cannot collide with another
artifact hashed over the same bytes, and the contract is validated before it is
encoded — identity is only ever computed over something that already passed.

The canonical bytes and hash are byte-identical to `@hypequery/protocol` for
the same contract. A 74-probe differential run across both implementations
found no divergence in acceptance, error code, or identity.

### Deployable formulas

Local queries accept every formula the `formula` helpers build. A deployment
contract accepts a narrower subset:

- A derived measure may reference only base measures. `formula.round("aov", 2)`
  over a derived `aov` is not deployable; inline the inner formula instead.
- A literal may appear only as the `round` decimals or as a `coalesce`
  fallback. `formula.multiply("revenue", 2)` and `formula.null_if_zero(0)` are
  not deployable, and the `coalesce` fallback must be a number (`None` is
  refused).

`build_protocol_deployment_contract()` and `write_dataset_bundle()` check this
before building the contract, so the error names the dataset and measure
instead of a contract path. `validate_deployable()` runs the same check on its
own:

```python
from hypequery.datasets import validate_deployable

validate_deployable(orders)
# ValueError: orders.doubled: a numeric literal cannot be an arithmetic operand
# in a deployable formula; literals are only accepted as round decimals or a
# coalesce fallback
```

## Bundles and releases

An RFC 0007 bundle manifest describes the content-addressed directory that
transports a deployment contract and any runtime artifacts, binding the
semantic deployment identity to exact file bytes. An RFC 0008 release envelope
assigns one verified bundle to a project and environment:

```python
from hypequery.protocol import (
    prepare_protocol_deployment_bundle_manifest,
    prepare_protocol_deployment_release_envelope,
)

bundle = prepare_protocol_deployment_bundle_manifest(manifest_data)
release = prepare_protocol_deployment_release_envelope(
    {
        "kind": "hypequery-deployment-release",
        "version": 1,
        "bundleIdentity": bundle.identity,
        "target": {"project": "acme", "environment": "production"},
    }
)
```

Each identity is domain-separated, so a bundle hash, a release hash, and a
deployment hash cannot collide even over identical bytes. A release carries no
timestamp or requester: retrying an unchanged envelope produces the same
identity, which is what makes it usable as an idempotency key.

Validation covers the manifest, not the filesystem. Portable paths are checked
for traversal, absolute forms, Windows device names, case-folding collisions,
and ancestors that are themselves declared files — but walking a real
directory, rejecting symlinks and undeclared files, and verifying hashes is a
consumer's job, and those failures are product errors rather than part of this
stable code set.

A manifest with no runtime artifacts is valid: a dataset-only deployment
references none.

Python definitions can now produce that dataset-only bundle directly. Register
every dataset a relationship can reach, and give an endpoint policy only to
datasets that Cloud should expose:

```python
from hypequery.datasets import create_dataset_registry, write_dataset_bundle

registry = create_dataset_registry(Customers, Orders)
bundle = write_dataset_bundle(
    "analytics/hypequery-deployment",
    registry,
    endpoints={
        "orders": {
            "access": {"kind": "authenticated", "roles": ["analyst"], "scopes": []},
            "tenant": {"kind": "required", "mode": "auto-inject", "column": "tenant_id"},
            "path": "/api/analytics/datasets/orders/query",
        }
    },
)
bundle.deployment_identity  # the RFC 0006 identity
bundle.bundle_identity  # the RFC 0007 identity
```

`write_dataset_bundle()` creates `deployment.json` and `bundle.json` in a new
directory and refuses to replace an existing path. `prepare_dataset_bundle()`
returns the same bytes without filesystem I/O. The output carries no Python
source or executable runtime artifact. The definition adapter requires declared
dependencies on SQL-backed fields and validates the full contract before any
file is written. Object-valued measure filter literals are currently rejected
because their map-entry collation is not yet proven byte-identical to the
TypeScript adapter; scalar and array filter values are supported.

## Query events and diagnostics

RFC 0011 defines two metadata-only records about an execution: the query
event, which is safe to emit broadly, and the diagnostics projection, which is
privileged. Validate either before it leaves the process:

```python
from hypequery.protocol import (
    ProtocolQueryEventError,
    validate_protocol_query_diagnostics,
    validate_protocol_query_event,
)

event = validate_protocol_query_event(
    {
        "kind": "hypequery-query-event",
        "version": 1,
        "eventId": event_id,  # 64 lowercase hex characters
        "occurredAt": "2026-10-01T12:00:00.000Z",
        "target": {"project": "acme", "environment": "production"},
        "queryName": "daily_revenue",
        "operation": "query",
        "outcome": "success",
        "durationMs": 182,
    }
)
```

Neither record has a field for rows, parameter values, SQL text, raw tenant
identifiers, or credentials, so an unknown field fails with
`HQ_EVENT_UNKNOWN_FIELD` (or `HQ_DIAGNOSTICS_UNKNOWN_FIELD`) rather than being
dropped. A record from a newer version fails with `*_INVALID_VERSION` even when
it adds fields, so a consumer can skip it. `ProtocolQueryEventLimits` may lower
the free-text byte limits but never raise them.

Validation is all this package does with these records, as in the TypeScript
reference: it does not yet build them from executions. `debugQuery` and
`safeMessage` are free text, so keeping values out of them is the producer's
job; see RFC 0011's producer obligations.

## Registry and catalog

A registry is how datasets are discovered at startup, and how a relationship's
target is resolved — a Python relationship stores only its target's *name*, so
nothing executable is ever held in a definition:

```python
from hypequery.datasets import create_dataset_registry, get_dataset_catalogs

registry = create_dataset_registry(Customers, Orders)
catalogs = get_dataset_catalogs(registry)
```

The catalog is the public, serializable description of a dataset: what can be
grouped, filtered, aggregated, and ordered. It emits the protocol's camelCase
keys and omits absent optionals rather than writing nulls, so the Python
catalog for a model is deep-equal to the `@hypequery/datasets` catalog for the
same model. `specs/semantic-catalog/catalog.json` pins that contract and both
test suites check themselves against it.

Relationship fields follow the query-time rules exactly: `hasMany` contributes
nothing, SQL-backed target dimensions are not joinable, and a `groupable: False`
target dimension stays queryable as a filter while dropping out of
`groupableFields`.

## Semantic contract

The semantic contract is the hashable projection of a registry's catalogs: a
normalized, sorted snapshot with a version marker and a SHA-256 `contentHash`
over its own stable JSON. Two logically equal models hash identically however
they were authored, which is what makes it usable for snapshots, diffs, and CI
drift checks.

```python
from hypequery.datasets import serialize_semantic_contract

trusted = serialize_semantic_contract(registry)
published = serialize_semantic_contract(registry, include_sql=False)
```

`include_sql=False` is the public discovery projection: a SQL-backed dimension
keeps its `sql` in the trusted contract and loses it in the published one, so
serving the contract to untrusted consumers cannot leak internal SQL. The two
projections are deliberately different contracts and hash differently.

Both projections are byte-identical to `@hypequery/datasets` for the same
model. `specs/semantic-catalog/contract.json` and `contract-public.json` pin
that, and both test suites check themselves against them.

## Planning and compiled queries

The planner turns a semantic query into a `CompiledQuery`: the only shape the
package asks a database to execute. SQL text is planner output, values are
named typed parameters, and policy is a closed settings allow-list — so a
request can influence *what* is selected but never *how* it is executed.

```python
from hypequery.datasets.planner import (
    DatasetQuery,
    ExecutionContext,
    plan_dataset_query,
    tenant,
)
from hypequery.datasets import filter, order

compiled = plan_dataset_query(
    Trips,
    DatasetQuery(
        dimensions=("vendor", "customer.country"),
        measures=("revenue",),
        filters=(filter.gte("pickup", "2026-01-01"),),
        by="day",
        order_by=(order.asc("period"),),
        limit=100,
    ),
    registry=registry,
    context=ExecutionContext(tenant=tenant("acme")),
)

compiled.sql  # SELECT ... WHERE `pickup_datetime` >= {p0:DateTime64(3)} ...
compiled.parameter_values()  # {"p0": "2026-01-01", "p1": "acme"}
compiled.to_sql()  # the redacted debug form — never executable
```

A timestamp filter value must be an ISO 8601 date or date-time: `2026-01-31`,
`2026-01-31 12:00:00`, or `2026-01-31T12:00:00.123Z`. A time needs seconds, and a
fraction or a `Z`/`±hh:mm` offset is optional. Anything else, including an
impossible date such as `2026-02-30`, is refused as `input-invalid` before it
reaches ClickHouse, which would otherwise read it as a different instant.

A dataset that declares a `tenant_key` is not served without a tenant scope:
reading it unscoped returns every tenant's rows, so an absent scope fails
closed with `tenant-required` rather than at whatever consumes the result. A
scope is RFC 0009's tenant capability. Only `tenant()`, `tenants()`, and
`all_tenants()` create one. It is deliberately **not** a Pydantic model, it
cannot be constructed directly, subclassed, or pickled, and its `repr` shows a
tenant count, never a tenant id. `ExecutionContext` rejects anything else in
its `tenant` slot, such as a mapping decoded from a request. Capability
denials carry RFC 0009's stable code on `CompiledQueryError.code`, for
example `HQ_CAPABILITY_TENANT_REQUIRED`; the public envelope from
`failure.to_data()` still carries only the category and message. Joined datasets carry their own tenancy into the join condition rather
than into `WHERE`, where it would silently turn a `LEFT ANY JOIN` into an inner
join. The single-match join also prevents duplicate target keys from
multiplying base rows before aggregation. Filtering the tenant field yourself
is refused while a scope is active.

`to_sql()` is for logs and diagnostics. It shows the same structure with the
same declared types and no values, and its placeholders are `<name:Type>` —
deliberately invalid as ClickHouse SQL, so debug output cannot be pasted into a
client and run.

Two independent checks keep values out of SQL text, and they catch different
things. Ruff's `S608` bans the classic interpolated-statement shape.
`scripts/check_sql_interpolation.py` — which CI runs — catches what `S608`
cannot see, because the planner assembles SQL from fragments that contain no
SQL keyword: it rejects any f-string in the planner that reads caller data, and
then plans the same query twice with different values and asserts the statement
is byte-identical. A deliberately reintroduced interpolation fails the second
check on every axis while `S608` stays green, which is why both are wired up.

Metrics and named queries are deliberately absent from the planner: the Python
definition surface has no metric handles and does not author named queries, so
a branch for either would be unreachable code.

## Development

See [the Python release guide](https://github.com/hypequery/hypequery/blob/main/python/hypequery/RELEASING.md) for beta, canary, and stable
publishing, including the bundled CLI.

See the [datasets implementation guide](https://github.com/hypequery/hypequery/blob/main/python/hypequery/ARCHITECTURE.md) for validation,
compilation and client boundaries, and where future dialect work belongs.

```bash
uv sync --all-extras --dev
uv run pytest
uv run mypy
uv run ruff check .
uv run lint-imports
```

Verify the installed CLI outside the checkout after building both distributions:

```bash
uv build
uv run python scripts/cli_smoke.py dist/*.whl --minimal
uv run python scripts/cli_smoke.py dist/*.tar.gz --minimal
# Requires a local ClickHouse server; creates and drops a fresh scratch database.
CLICKHOUSE_PASSWORD=your-local-password uv run python scripts/cli_smoke.py dist/*.whl
CLICKHOUSE_PASSWORD=your-local-password uv run python scripts/cli_smoke.py dist/*.tar.gz
```

The Python CI matrix runs these checks for Python 3.11–3.14. The full journey
uses the generated README's query and expected response, verifies authentication,
and cleans up the server and scratch database, with a 15-minute onboarding budget.

From the repository root, run the Python shared-fixture gate with:

```console
pnpm conformance:python
```

This runs both Python adapters — `hypequery.protocol.adapter` for the
protocol families and `hypequery.datasets.adapter` for `sql-portability-v1` —
and asserts each one's exact expected family list before running its cases.
`pnpm conformance` runs this Python gate together with the TypeScript
reference and SQL-portability adapters.

See the [implementation plan](https://github.com/hypequery/hypequery/blob/main/plans/python-datasets-serve-pr-level-plan.md) and [security protocol](https://github.com/hypequery/hypequery/blob/main/specs/security-protocol/README.md).

For dataset coverage, CI gates, and remaining gaps, see the
[testing review](https://github.com/hypequery/hypequery/blob/main/python/hypequery/TESTING_REVIEW.md).

## Serve dataset and metric endpoints

Register endpoints over `create_dataset_client` (or
`create_async_dataset_client`) on an API, whose docs are closed by default:

Register `add_discovery_endpoint(api, registry=registry)` to publish a bounded
logical catalog at `/discovery`. It authenticates by default and accepts an
`EndpointPolicy` for role, scope and tenant requirements. Any listed role grants
role access; all listed scopes are required. Explicitly pass
`EndpointPolicy(public=True)` only for intentionally public discovery. The
256 KiB default budget is checked at startup; physical sources, columns, SQL,
tenant policy and tenant values never appear in this projection.

```python
from hypequery.serve import (
    EndpointPolicy,
    HttpSecurity,
    add_dataset_endpoint,
    add_discovery_endpoint,
    add_metric_endpoint,
    create_api,
    to_asgi_app,
)

# authenticate is your host's credential lookup. It returns a Principal whose
# roles, scopes and tenant_id come from trusted server-side identity data.
api = create_api(auth=authenticate, security=HttpSecurity(allowed_hosts=("analytics.example.com",)))
policy = EndpointPolicy(required_scopes=frozenset({"analytics:read"}), tenant="required")
add_dataset_endpoint(api, "/datasets/orders/query", dataset=orders, client=client, policy=policy)
add_metric_endpoint(
    api,
    "/metrics/order_count",
    dataset=orders,
    measure="count",
    name="order_count",
    client=client,
    policy=policy,
)
add_discovery_endpoint(api, registry=registry)
app = to_asgi_app(api)
```

An endpoint serves its own dataset's fields only. Its policy says who may read
that dataset, not the datasets its relationships reach. Fields such as
`customer.country`, related measures, and named filters defined on a related
field therefore need an explicit opt-in, per relationship:

```python
add_dataset_endpoint(
    api,
    "/datasets/orders/query",
    dataset=orders,
    client=client,
    policy=policy,
    include_related={"customer"},
)
```

Without the opt-in, the endpoint refuses those fields with `400 VALIDATION_ERROR`
and leaves them out of its client contract. The same goes for a measure whose
fixed filters read a related field, directly or through a derived measure: the
endpoint refuses it, and a request that omits `measures` selects only the base
measures the endpoint can serve. A metric endpoint for such a measure is refused
when it is created. Include a relationship only when this endpoint's policy is
enough to read the related dataset.

The dataset, registry and client are authored by the host as in the client
examples above. Metric endpoints fix one dataset measure; formula metrics and
portable metric definitions remain a follow-up. Their optional `name` aliases
that measure in results and ordering.

POST a strict JSON body with `dimensions`, `measures` (dataset endpoints only),
`filters`, `having` (dataset endpoints only), `orderBy`, `by`, `limit`, `offset`, and
`includeMeta`. Filters are
`{"field": "country", "operator": "eq", "value": "US"}`; orders are
`{"field": "order_count", "direction": "desc"}`. Unknown request fields,
coercion of numbers/booleans, and attempts to supply tenant, SQL, settings,
roles or scopes are refused. Page sizes are positive, default to 1000, and
clamped to the endpoint and dataset caps. An extra row is fetched to compute
`hasMore`, then removed from returned data and row counts.

Responses are `{ "data": [...] }`, or `{ "data": [...], "meta": {...} }` when
`includeMeta: true` or `x-include-meta: true` is sent. Public metadata contains
`requestId`, `timingMs`, `rowCount`, `pagination: { limit, offset, hasMore }`, and,
when the client has a result cache, `cache: { hit }`. Non-null semantic measure values are strings on the HTTP
wire, matching TypeScript. Local Python client results keep their native values.

`DiagnosticAccess(authorize=..., audit=...)` is an optional server-authored
endpoint setting. Both callbacks run in the threadpool. Only an authenticated
principal authorized by the host receives a separate `diagnostics` object, and
only after the audit callback succeeds. It contains redacted debug `sql`, never
bound values or raw tenant ids. Metadata opt-in alone grants no access.

`QueryEvents(target={"project": "my-project", "environment": "production"},
sink=...)` is an optional endpoint setting; `create_api(events=...)` sets it
for every endpoint that has none of its own. The synchronous host sink receives
validated RFC 0011 events containing identifiers, outcome, duration, and row
count or canonical failure category; never request bodies, rows, SQL, credentials
or tenant values. Sink failures do not fail queries.

Discovery is authenticated unless explicitly registered with
`EndpointPolicy(public=True)`. Its logical catalog matches TypeScript's
`/discovery` projection and has a 256 KiB default budget enforced at startup.
It carries no physical sources, columns, SQL, tenant policy or values.
An API serves no `/docs` or `/openapi.json` unless created with
`development_docs=True`, for deliberate development documentation only. The
OpenAPI 3.1 document is generated from the routes' own Pydantic schemas, as
TypeScript's is from its endpoint definitions, so no web framework is needed
for it; `openapi=OpenApiInfo(title=..., version=...)` describes it, and
`openapi_document(api)` returns it directly.

### Production process

Use the validated production profile and runner for a standalone service:

```python
from hypequery.serve import ProductionProfile, start_server

api = create_api(
    auth=authenticate,
    security=HttpSecurity(
        allowed_hosts=("analytics.example.com",),
        trusted_proxies=("127.0.0.1",),
    ),
    production=ProductionProfile(
        max_concurrency=32,
        timeout_seconds=30,
        max_result_rows=10_001,
        max_result_bytes=8 << 20,
    ),
)

if __name__ == "__main__":
    start_server(api)  # or start_server(to_asgi_app(api, lifespan=...))
```

The runner binds to `127.0.0.1:8000` by default. An IP address outside loopback
requires `allow_external_bind=True`, for example when binding within a container.
It needs the `server` extra and runs one uvicorn worker per process, with reload, access logging, server headers
and WebSockets disabled; keep-alive is five seconds and graceful shutdown allows
the request timeout plus five seconds. A process manager can run multiple
instances; concurrency limits apply independently to each instance.

Terminate TLS at a reverse proxy. List its addresses/networks explicitly in
`HttpSecurity.trusted_proxies`; the default trusts none, and production rejects
all-address networks. The runner disables Uvicorn's own forwarded-header handling
so application policy sees the original peer and controls proxy trust once.
See [Uvicorn settings](https://www.uvicorn.org/settings/) for transport details.

Production requires an `HttpSecurity`, and rejects debug, reload, development
docs, and `from_context(..., same_origin=False)` when the API is created. A
header credential (bearer, API key, JWT) is never read from a cookie; the
host's session is read only by a `from_context` strategy, with its same-origin
check. The profile's budgets apply
wherever the API is served; a host that mounts it in another app owns that
app's process safeguards.

Excess in-flight requests receive canonical `503 SERVICE_UNAVAILABLE` without
queuing. The request timeout covers authentication, body reading, query execution,
response generation and sending, and the admission slot is held until the
response is written; expiry cancels the handler and signals the
dataset executor. Before response headers are sent it returns canonical
`504 GATEWAY_TIMEOUT`; a stalled send after headers closes the connection.
The HTTP deadline returns promptly even when a synchronous query or authentication
callback stalls. Its admission slot remains occupied until the tracked worker
finishes, preventing timed-out requests from accumulating unbounded work.
Work still waiting for a thread-pool slot is cancelled before the host callback
starts; only workers already running retain admission until they stop.
Synchronous executors must honor the cancellation signal; the factory-created
ClickHouse executor uses its control connection, while Python cannot forcibly
stop arbitrary host code running in a thread. Failure telemetry is delivered
asynchronously when the HTTP waiter is cancelled, and is dropped if no worker
slot is immediately available so it cannot delay admission recovery.

Dataset and metric endpoints also pass time, row, byte and thread ceilings into
the compiled query, intersecting them with stricter client settings. The row
budget includes the one-row pagination probe: `max_result_rows=10_001` permits
at most 10,000 returned rows, further bounded by endpoint/dataset policy.
The byte ceiling applies both to ClickHouse results and the complete serialized
HTTP body, including cache hits. Responses are buffered under that ceiling;
oversized bodies return canonical `413 PAYLOAD_TOO_LARGE` without partial data.
This profile does not provide streaming exports.

CI tests the real runner, startup refusals, capacity recovery, synchronous and
asynchronous cancellation, cache/response limits and proxy trust. The same shared
HTTP fixtures run with and without the production profile, and live ClickHouse
CI tests the production HTTP query path. The declared direct dependency floors
(pydantic 2.9.2, raised to 2.12.2 on Python 3.14; anyio 4.14.2; uvicorn 0.30.6;
clickhouse-connect 1.4.2) are installed from wheels and
tested on every supported Python, as well as the locked versions.

Run both implementations' shared HTTP gates after building TypeScript packages:

```bash
pnpm conformance:serve
```

### Definition-only client artifacts

The base install can prepare an RFC 0018 build artifact for frontend/MCP tooling
without importing a server or constructing a database executor:

```python
from hypequery.datasets import (
    ClientEndpointDefinition,
    ClientQueryProfile,
    export_client_contract,
)

artifact = export_client_contract(
    [
        ClientEndpointDefinition(
            dataset=Orders,
            path="/api/datasets/orders/query",
            profile=ClientQueryProfile(default_limit=100, max_limit=100),
        ),
        ClientEndpointDefinition(
            dataset=Orders,
            path="/api/metrics/revenue",
            profile=ClientQueryProfile(default_limit=100, max_limit=100),
            measure="revenue",
            name="sales",  # metric ID and output alias
        ),
    ],
    mount_path="/analytics",
)
# artifact["canonical"] is the complete signed JSON document.
```

Related fields are left out unless a definition names the relationship, as
`include_related` does for an installed endpoint. Pass the same names to both so
the exported schema hash matches the live one; otherwise generated clients get
`409 CLIENT_SCHEMA_CHANGED`:

```python
ClientEndpointDefinition(
    dataset=Orders,
    path="/api/datasets/orders/query",
    profile=ClientQueryProfile(default_limit=100, max_limit=100),
    related={"customer"},  # matches include_related={"customer"}
)
```

Supply a `registry` when definitions reference queryable relationships. Target
filter permissions and safe relationship aggregate rules are resolved directly
from definitions, including filter aliases and filter-only fields. Physical
sources, columns, SQL, tenancy configuration and arbitrary metadata are omitted.
Base-dimension nullability is conservatively unknown; joined dimensions are nullable.

`label` and `description` on the dataset and on advertised dimensions/measures
are exported as each endpoint's `annotations`, which MCP agents and generated
JSDoc read. Whitespace runs are folded to single spaces and blank text is
omitted; text longer than 4096 UTF-8 bytes or with control characters fails
export. Annotations are outside the endpoint schema hash, so rewording one does
not produce `409 CLIENT_SCHEMA_CHANGED`.

These definitions describe intended bindings and do not install HTTP routes.
The host must supply final mount paths and trusted effective ceilings,
reserving the pagination probe row from process/client row budgets, and enforce
the advertised strict client profile. Dataset ceilings can only lower the
profile. API-owned registration, authorized discovery and the export CLI are
separate integrations; this SDK does not infer deployment paths or permission.

### Registered client endpoints

Opt in to the strict client profile when installing a dataset or metric route:

```python
from hypequery.datasets import ClientQueryProfile
from hypequery.serve import add_dataset_endpoint, export_client_contract

add_dataset_endpoint(
    api,
    "/datasets/orders/query",
    dataset=Orders,
    client=client,
    client_profile=ClientQueryProfile(default_limit=100, max_limit=1000),
)
artifact = export_client_contract(api)  # or the to_asgi_app application
```

The export names each endpoint's path under the API's `base_path` and
intersects profile, dataset, endpoint policy, client and production ceilings,
reserving the pagination probe row. For an API mounted inside another
application, configure its external `create_api(client_mount_path=...)`.
Proxy headers never determine artifact paths, nor do ASGI's `root_path` and
WSGI's `SCRIPT_NAME`: the first request served below a prefix that differs from
`client_mount_path` logs a warning on `hypequery.serve` naming the setting. A strict endpoint refuses a path
another POST route already serves. Legacy routes keep their input behavior and
are omitted from this export. `to_asgi_app` exports the contract once when it
builds the app, so a misconfiguration fails at startup.

Consumers can send the endpoint's `schemaHash` in `X-Hypequery-Client-Schema`.
Authentication and current endpoint policy run first. A stale pin returns HTTP 409
with `error.type="VALIDATION_ERROR"`, `error.details.code="CLIENT_SCHEMA_CHANGED"`
and a fixed safe message; no query is executed. Current limits still apply when
the schema hash matches. Strict routes validate typed filters, selections,
combined budgets and metadata before planning, and cannot enable SQL diagnostics.

Two hashes are easy to confuse when debugging a 409. Each endpoint's
`schemaHash` is what requests pin, and it is the same in the build export
(`export client-contract`) and in the live, caller-scoped view at the discovery
route. The whole document's `contentHash` differs between the two: the build
view (`"view": "build"`) lists every endpoint, the live one (`"view":
"authorized"`) only those the caller may use. The generated client's
`clientContractHash` is the build `contentHash`; compare per-endpoint
`schemaHash` values, not `contentHash`, to find a stale endpoint.
Live caller-scoped discovery and frontend/MCP integration follow separately.

### Caller-scoped client discovery

Install live discovery on the API:

```python
from hypequery.serve import add_client_contract_endpoint

add_client_contract_endpoint(api)  # GET /client-contract, under the base path
```

The route authenticates by default and independently applies each installed strict
endpoint's policy to the current principal and tenant. It returns a signed
`view="authorized"` contract; a metric-only caller sees its metric without gaining
a dataset query target. A valid principal with no targets receives an empty view.
Responses are `no-store` and vary by credential transport. The default 256 KiB
response budget fails closed rather than silently dropping capabilities.

Public discovery requires explicit `policy=EndpointPolicy(public=True)` and follows
public-route semantics: it advertises anonymous/public targets only. Query parameters
cannot select a build view, principal, tenant or deployment path. A discovered
contract describes capabilities; query authentication and policy still apply.

### Offline export command

Put a zero-argument definition-only factory in a project module. It should return
`export_client_contract(...)` from `hypequery.datasets`, or its signed `contract`
member. Then run the Python CLI from that project directory:

```bash
python -m hypequery export client-contract --factory client_contract:build
python -m hypequery export client-contract --factory client_contract:build --check
python -m hypequery export client-contract --factory client_contract:build --stdout
```

The default destination is `client-contract.json`; use `--output` to choose another
path, or `--output -` for stdout. Existing artifacts require `--force` to replace;
`--check` reports drift without creating files or directories. Writes are atomic,
preserve existing permissions and refuse symlinks or concurrent changes. Existing
input is bounded to the contract's 1 MiB budget before project code is imported.

The command explicitly imports the named project factory; use a definition-only
module rather than an application module that starts services or opens connections.
The CLI itself loads no database/serving adapter. It verifies supplied identities
and emits only canonical contract JSON in stdout mode; project chatter and import
failures are redacted. It does not infer routes, authenticate a principal or grant
query access. This artifact is the input to the frontend/MCP generation workflow.
