# costQL > Price GraphQL queries before they run: calibrate a live API into a static > pricing pack, then quote any query offline: in Python or JavaScript. Cost-units > only, never dollars. No hosted service; the pack is a plain local file. Install: `pip install costql` (build + quote) · `npm install costql` (quote only) ## Docs - [adapters](https://costql.com/docs/adapters/): --- description: "The one ~90-150 line file you write to onboard a GraphQL API to costQL, with zero engine changes: what it declares and how to write it." --- - [agents](https://costql.com/docs/agents/): --- description: "Hand a GraphQL API to a coding agent (Claude Code, Cursor) and let it write the costQL adapter and build the pricing pack for you." --- - [architecture](https://costql.com/docs/architecture/): --- description: "costQL end to end: introspect a live API, calibrate it into a static pricing pack, then quote any query offline. A deterministic path, no… - [contract](https://costql.com/docs/contract/): --- description: "The frozen v1.0 result shape every costQL quote follows: a billable price in cost-units, safe to bill on, at every tier and on every query."… - [demo-apis](https://costql.com/docs/demo-apis/): --- description: "The three real, unrelated GraphQL APIs costQL is proven against (TMDB, Rick & Morty, Northwind), each onboarded with one small adapter and a… - [evaluation](https://costql.com/docs/evaluation/): --- description: "The model, baseline, and dataset behind every costQL accuracy number, and how calibration and held-out query sets are kept disjoint." --- - [external-calls](https://costql.com/docs/external-calls/): --- description: "When a field calls an outside service (an LLM, a paid API), costQL names the call and observes its host; your app puts the price on it." --- - [faq](https://costql.com/docs/faq/): --- description: "Short answers to the most common costQL questions: does it call your API, what a price is in, dollars vs cost-units, and more." --- - [guides/query-limits](https://costql.com/docs/guides/query-limits/): --- description: "Query-complexity limits, demand control, and DoS protection all need a cost per query to threshold on. costQL measures that cost instead of… - [guides/x402](https://costql.com/docs/guides/x402/): --- description: "x402's upto scheme authorizes a ceiling and settles the actual amount. That is exactly the two numbers costQL already gives you: the… - [instrumentation](https://costql.com/docs/instrumentation/): --- description: "The one response extension (extensions.cost_trace) your GraphQL server emits to let costQL see per-resolver and shared work (T2/T3)." --- - [js](https://costql.com/docs/js/): --- description: "npm install costql gives you the quote side in JavaScript/TypeScript: load a pack and price queries offline in Node, browsers, or edge. Zero… - [limitations](https://costql.com/docs/limitations/): --- description: "Where costQL's typical estimate is least certain — cyclic-recursion and data-dependent queries. In every case the billable ceiling stays… - [pack-format](https://costql.com/docs/pack-format/): --- description: "What is inside a costQL pricing pack: the schema, fitted costs, observed sizes, and hosts, all in one self-contained file with no server or… - [publishing](https://costql.com/docs/publishing/): --- description: "A pack is a static JSON file. This is how to publish it so whoever prices a query — your own app, or a third party's agent — can fetch it… - [quickstart](https://costql.com/docs/quickstart/): --- description: "From a live GraphQL API to your first offline price in about a minute: install costQL, quote a demo pack, then build your own." --- - [quoting](https://costql.com/docs/quoting/): --- description: "What quote() accepts and what the price means: fragments, aliases, variables, and directives are all parsed, and wherever the price can't be… - [results/northwind](https://costql.com/docs/results/northwind/): --- description: "A batch-heavy database backend where entity sharing is heavy: the API shape that needs the tier that watches sharing (T3). Measured against… - [results/rickmorty](https://costql.com/docs/results/rickmorty/): --- description: "costQL priced a live public API it does not own with a 93-line adapter, zero engine changes, and ~96% accuracy at T1." --- - [results/tmdb](https://costql.com/docs/results/tmdb/): --- description: "Three-tier accuracy on the TMDB demo. On this lightly-sharing API there is almost no shared work to watch, so per-resolver timing (T2) and… - [tiers](https://costql.com/docs/tiers/): --- description: "costQL prices in one currency, work-ms, across three tiers of fidelity. T1 works on any API black-box; T2 and T3 see parallel and shared… ## Source - [GitHub](https://github.com/shapemachine/costql): engine, adapters, demos, packs, conformance oracle --- --- description: "The one ~90-150 line file you write to onboard a GraphQL API to costQL, with zero engine changes: what it declares and how to write it." --- # Writing an adapter An adapter is the one file you write to onboard an API, proven at ~90–150 lines across three unrelated APIs, with zero engine changes. It tells costQL what introspection cannot: where the API is, what *real* inputs to query with, how argument names map to those inputs, and which query shapes to calibrate on. This page walks through every part, using [`examples/adapters/rickmorty.py`](https://github.com/shapemachine/costql/blob/main/examples/adapters/rickmorty.py) (the minimal T1 template) as the running example. Two shortcuts before writing anything by hand. `costql probe ` checks the endpoint first and reports the tier and `cost_currency` to declare, plus where real IDs can be harvested. And the whole job delegates well: [agent-assisted onboarding](agents.md) covers handing this page to a coding agent. ## The shape of an adapter An adapter module exports a factory returning an `APIConfig`. Every field is explained on this page; the comments say where: ```python from costql.config import APIConfig, MinedInputs, UNSET def my_config(tier: str = "T1") -> APIConfig: return APIConfig( name="myapi", # labels the pack; default output is pricing_pack_.json graphql_url="https://api.example.com/graphql", # the live endpoint to calibrate input_source=MyInputSource(), # section 1: the real IDs calibration queries with arg_resolver=MyArgResolver(), # section 2: how argument names map to those IDs tokens={}, root_auth={}, field_auth={}, # section 4: auth; all empty for public APIs uncoverable_fields={}, bounded_fields={}, # section 4: skip / sample-in-isolation lists known_loaders=[], size_roots=SIZE_ROOTS, # section 4: declared loaders + list-size bounds default_cap=20, # section 4: page size for lists that declare nothing cost_currency="wall_time_ms", # section 4: copy from `costql probe`, never a guess tier=tier, # section 4: likewise; build downgrades over-claims calibration_queries=calibration_queries, # section 3: the shapes the model is fit on ) ``` You point the CLI at it: `costql build --adapter my_api.py:my_config`. The factory's `tier` parameter exists so `costql build --tier T1` can request a lower fidelity than the adapter's default without editing the file. ## 1. `InputSource`: real inputs, never fabricated costQL calibrates by running real queries, so it needs real, stable IDs. `mine()` returns them: ```python CHARACTERS = {"whale": 1, "small": 100, "heldout": 200} class MyInputSource: def mine(self) -> MinedInputs: return MinedInputs(data={"characters": [CHARACTERS]}, tokens={}, uncovered=[]) ``` Pick three disjoint entities per collection: **whale** (the most densely-connected row you know: worst-case fanout), **small** (a light one), and **heldout** (never used in calibration, so you can evaluate honestly later). If inputs come from a database, `mine()` is where you query for them. ## 2. `ArgResolver`: how argument names map to inputs Called for every argument the calibration queries need. Return a literal, or `UNSET` to let the engine apply generic defaults: ```python class MyArgResolver: def value(self, field_path, arg_name, arg_type_base, mined, size="whale", variant="calib"): key = "heldout" if variant == "heldout" else size if arg_name == "id": return str(CHARACTERS.get(key, CHARACTERS["whale"])) if arg_name == "page": return 1 return UNSET ``` `field_path` (e.g. `"character.episode"`) lets one resolver serve many types. Match substrings to route `id` to the right entity table. ## 3. `calibration_queries`: the shapes the model is fit on The single most important quality lever, and the part most people hand to a coding agent. [Agent-assisted onboarding](agents.md) walks one through it. Supply a callable `(size: "whale" | "small") -> list[str]` returning **clean, predictable, isolating** query strings: ```python def calibration_queries(size: str) -> list[str]: c = CHARACTERS[size] return [ f'{{ character(id:"{c}"){{ name status species }} }}', f'{{ character(id:"{c}"){{ name episode{{ name }} }} }}', '{ characters { results { name } } }', ] ``` Rules of thumb, learned across three APIs: - **How many is derived, not a fixed number.** Start around eight, then add one shape per resolver you price (ideally in two compositions) and ≥3 width-sweep shapes per batched edge (see the next bullet). A black-box T1 API lands near 8–10; a batching T3 API near 20+. The three worked examples run 8 (rickmorty), 12 (tmdb), and 23 (northwind). - **Each list edge crosses into a different type and does not re-enter.** Cyclic shapes (`character{ episode{ characters } }`) corrupt a linear fit. They are what costQL *flags* at quote time, not what it calibrates on. - **Cover every resolver you want priced** at least once, ideally in more than one composition. - **Vary declared sizes** (`first:3` / `first:15` / `first:40`) on batched edges so per-loader size→cost curves get ≥3 distinct widths to fit (see the [Northwind adapter](https://github.com/shapemachine/costql/blob/main/examples/adapters/northwind.py)'s deliberate sweep). - **Most size-sensitive fields get measured for you; one kind does not.** Some fields do more work the bigger their argument gets. Picture a field with `limit: 500` that really processes all 500 rows in one call. If your calibration only ever calls it small, costQL assumes its cost is flat, so a large request against it gets priced too low. If you have a field like this, add a calibration query that calls it with a large argument and name its size argument. It is a [known corner](limitations.md#when-a-fields-cost-grows-with-an-argument) with a simple fix. - Without the hook, `costql build` falls back to a shallow generic coverage sweep. It works, but curated shapes fit measurably better. ## 4. The remaining knobs - **`size_roots`**: list-returning fields whose result size an argument bounds: `{"cast": {"arg": "limit", "offset": 0, "cap": None}}`. `cap` is a server-side clamp (e.g. a fixed 20-item page). - **`default_cap`**: the ceiling for lists that declare nothing (set it to the API's page size). - **`tokens` / `root_auth` / `field_auth`**: auth, all empty for public APIs. `tokens` maps a credential name to its bearer value; `root_auth` maps a root field to the credential it needs; `field_auth` does the same per resolver (`"Movie.privateNotes": "admin"`) for fields stricter than their root. - **`uncoverable_fields`**: resolvers calibration must skip (with reasons). - **`bounded_fields`**: resolvers kept *out* of calibration fanout and sampled once in isolation, e.g. a call to an outside host (`{"Movie.aiSummary": "outside call (api.anthropic.com)"}`). costQL records the host it observed; it never prices the outside call (the consuming app does). See [External calls](external-calls.md). - **`known_loaders`**: only for T2/T3 servers, the loader IDs your cost-trace emits, so dead loaders are detected. Empty for black boxes. - **`one_root_per_op`** (default `True`): generated coverage queries hit one DB-backed root field per operation, for servers that can't run sibling roots concurrently on a shared session. Leave it unless you know your server handles concurrent sibling roots and you want faster calibration. - **`cost_currency` / `tier`**: don't choose these; observe them. Run `costql probe ` and copy what it reports: `"wall_time_ms"` / `"T1"` for any API you don't control, `"work_ms"` / `"T2"`-or-`"T3"` only when the server actually emits the [cost-trace extension](instrumentation.md). `costql build` honestly downgrades to T1 if it observes no trace. ## 5. Build, validate, spot-check ```bash costql build --adapter my_api.py:my_config --out my_api.json costql validate --pack my_api.json costql quote --pack my_api.json '{ ...a query your app actually sends... }' ``` Sanity checks worth a minute: the price of a tiny query should roughly match one real request's latency; a wider `first:` should never price *lower*; a deliberately cyclic query should come back `confidence: low`. ## The three worked examples | Adapter | Lines | Fidelity | What to steal from it | |---|---|---|---| | `rickmorty.py` | ~120 | T1 | the minimal template; black-box public API | | `tmdb.py` | ~150 | T3 | bounded (paid) fields, known loaders, curated shapes | | `northwind.py` | ~160 | T3 | batch-width sweeps for DB loader curves | --- description: "Hand a GraphQL API to a coding agent (Claude Code, Cursor) and let it write the costQL adapter and build the pricing pack for you." --- # Agent-assisted onboarding The fastest way to onboard an API is to hand it to a coding agent (Claude Code, Cursor, or any tool that can read a repo and run a CLI) instead of writing the adapter by hand. Give the agent one skill to follow, [`skills/costql-adapter`](https://github.com/shapemachine/costql/blob/main/skills/costql-adapter), and one CLI command, `costql probe`, that removes the guesswork. Everything else it needs is already in the repo. ## What the human provides Three answers. Everything else is discoverable. 1. **The endpoint URL.** 2. **An auth header**, if the API needs one. 3. **Do you run the server?** If yes and your API's shape calls for an instrumented tier (it batches, caches, or parallelizes work), the agent will point you at [the one trace extension](instrumentation.md) to emit; if no, T1 is the fit and needs nothing from anyone. ## What the agent does ``` costql probe https://rickandmortyapi.com/graphql ``` ```text endpoint : https://rickandmortyapi.com/graphql schema : 14 types · hash d0af9f9975b12932 · 9 root fields cost trace : absent tier today : T1 · cost_currency "wall_time_ms" (set these in the adapter as-is) id sources : real IDs are harvestable without a curated list: { characters { results { id } } } -> Character ids, paginate via page { locations { results { id } } } -> Location ids, paginate via page { episodes { results { id } } } -> Episode ids, paginate via page note : no cost_trace observed: if your server gates tracing (e.g. behind an env var), enable it and re-probe next : write the adapter (skills/costql-adapter walks an agent through it; docs at https://costql.com/docs/adapters/) ``` The probe settles the two things people used to get wrong by hand: - **Tier and currency come from observation.** The probe sends one query and checks the response for `extensions.cost_trace`. No trace means T1 and `wall_time_ms` (one stopwatch on the whole request: clock time). A trace with `work_ms` means T2; loaders on top of that mean T3, both priced in `work_ms` (summed real work). The adapter copies what the probe reports; nobody hand-picks a currency again. (`costql build` double-checks: it downgrades any pack whose server stops emitting the trace.) - **Real IDs without a curated list.** The *id sources* are argument-free root paths that reach id-bearing entities. The agent runs those harvest queries, samples a few candidates to find a densely-connected `whale`, a light `small`, and a reserved `heldout`, and verifies each id resolves live before using it. You can still hand the agent a curated list; you just don't have to. From there the agent follows [the adapter guide](adapters.md): template, arg resolver, calibration shapes, `costql build`, `costql validate`, and the sanity checks (a wider `first:` never prices lower; a cyclic query flags `confidence: low`). ## What ships for agents | where | what | | --- | --- | | `skills/costql-adapter` | write an adapter: probe-first, can self-harvest IDs, runs from just a URL | | `skills/costql-build-pack` | build or rebuild a pack, handle outside-call fields, explain T1 downgrades | | `skills/costql-quote-debug` | interpret a quote: price vs typical, confidence, breakdown, sharing folds | | `AGENTS.md` | repo map, commands, and conventions for any agent working in the repo | | [`llms.txt`](https://costql.com/llms.txt) | this documentation, indexed for tools that read the web | | `.claude-plugin/` | the same skills packaged as a Claude Code plugin | The skills are plain markdown in the [repo](https://github.com/shapemachine/costql): tool-agnostic, no framework required. ## A prompt that works > Onboard `https://api.example.com/graphql` to costQL. Auth header: > `Authorization: Bearer …`. Start with `costql probe`, follow > `skills/costql-adapter`, harvest your own IDs, and finish with a built, > validated pack plus one quoted example query. I run this server, so if the > probe reports T1, show me what to emit for T2/T3 before you build. --- description: "costQL end to end: introspect a live API, calibrate it into a static pricing pack, then quote any query offline. A deterministic path, no LLM." --- # How pricing flows: build → pack → quote This is costQL end to end: a new API arrives, the engine calibrates it into a static **pricing pack**, and from then on any app quotes queries against that pack locally: no server, no network, no re-measurement. The cost **unit** is always *work-ms* (summed real work; see [One currency, three fidelities](tiers.md)); the tiers differ only in how sharply the API lets costQL **see and factor** that work. **Nature of each step:** the engine is 100% **deterministic** code (no LLM in the pricing path). The only non-engine touches are (a) a human-authored adapter at onboarding, and (b) an outside service (e.g. an LLM) that lives *inside the API being priced*, whose call costQL times and whose host it names, but never invokes or prices itself. ```mermaid flowchart TD subgraph LEGEND["LEGEND - nature of each step (the engine has NO agentic / LLM step)"] direction LR L1["DETERMINISTIC engine step
plain code: schema walk, HTTP calls,
a numeric regression, static analysis
reproducible + auditable"] L2["HUMAN-AUTHORED once, at onboarding
the API adapter (real inputs)"] L3["OUTSIDE CALL = a measured COST, not a step
only if the API being priced calls one
(e.g. an aiSummary resolver -> Haiku);
costQL times it + names the host, never invokes or prices it"] end Start(["A new API arrives to be priced"]) --> S1 %% ---------------- BUILD PHASE: learn the cost model ---------------- S1["1 - Introspect the API live
build its cost graph (types + resolvers)
no schema file is kept in costQL's core"] S1 --> S2["2 - Mine real inputs (API adapter, authored once)
real ids / args so the sample queries actually run"] S2 --> S3["3 - Generate the coverage panel
a targeted set of REAL queries:
isolating + varied combinations + several sizes
each run repeatedly under low contention"] S3 --> S4{"4 - What can this API expose?
= the highest tier it affords"} S4 -->|"black box only"| T1 S4 -->|"per-resolver timings"| T2 S4 -->|"timings + sharing trace"| T3 subgraph UNIT["HOW THE COST UNIT IS FACTORED - the unit is ALWAYS work-ms = summed real work (never elapsed wall-clock time)"] direction TB T1["T1 - CHEAP (black box)
----------
Sees ONLY the whole-query wall-clock time
(a low-fidelity stand-in for work-ms)
Each resolver's cost is BACKED OUT by
regression across many different queries
BLUR: work done in parallel or batched
hides inside elapsed time -> under-counts"] T2["T2 - MIDDLE
----------
Sees EACH resolver's own work-ms and
sums the real durations
(the count of calls x each call's weight)
SHARING INFERRED: a call reused by
several fields is guessed, not observed
-> shared work can be double-counted"] T3["T3 - EXPENSIVE
----------
Sees each resolver's work-ms PLUS the
sharing trace (which calls coalesced / deduped)
Shared calls counted ONCE, and each shared loader
priced by a LEARNED batch-size curve work-ms = f(distinct keys)
(a 300-key batch costs more than a 3-key one;
DB loader rises, network loader stays flat)
outside hosts are named (host + call count)
-> exact factoring, nothing hidden"] end T1 --> S5 T2 --> S5 T3 --> S5 S5["5 - Fit the cost model
solve: op_cost = sum over resolvers of
( invocations x unit_cost )
result: one unit_cost per resolver"] S5 --> S6["6 - Observe result sizes
keep BOTH the typical (average) size
and the worst-case size per resolver"] S6 --> S7["7 - Record observed outside calls
for each bounded field that calls an outside host,
the engine saves the HOST it observed (host only, no fee)
surfaced in a quote for the app to price (T3 names the resolver)"] S7 --> S8["8 - Grade accuracy on a HELD-OUT set
predict prices, then run those queries for real,
compare predicted vs measured
= costQL rating its own accuracy"] %% ---------------- HANDOFF: the static pricing pack ---------------- S8 --> PACK[["PRICING PACK - the build-to-use handoff
ONE static, self-contained file: schema + cost model + observed outside hosts
no server · no sidecar · no extra API call · no re-measure
vendor it into the app, or even embed it in the API's own docs"]] %% ---------------- USE PHASE: price a query (app side, local) ---------------- subgraph APPSIDE["APP SIDE - a quote is pure LOCAL computation from the pack (no service)"] direction TB Q(["Price a query (a QUOTE - the query is NOT run)"]) Q --> P1 P1["Predict it from the pack ALONE - EVERY query, seen or unseen
(the pack stores no query prices; there is no lookup)
price = sum of unit_cost x invocations

invocations = fanout counts multiplied down the query tree
size basis: average size (the typical) OR worst-case size (the safe max)
T3 prices each SHARED loader by its learned batch-size curve
-> shared work counted once, a big batch costing more than a small one
(outside calls are named for the app to price; not in this total)"] P1 --> P2{"is the query's size RUNTIME-UNKNOWABLE?
(a) cyclic recursion re-enters a type via a list edge, OR
(b) >=2 un-paginated list edges compound on one path"} P2 -->|"no - size is bounded / declared"| P3["HIGH confidence
quote it"] P2 -->|"yes - size is data-dependent"| P4["LOW confidence
structural quote + FLAG + caveat
(ceiling stays SAFE; for an exact number, run it once ->)"] P3 --> Out(["Priced query + confidence tag
(the seller's app turns cost-units into money)"]) end PACK --> Q P4 -->|"run it once (opt-in)"| P9 P9["Exact cost from a RUN's work-ms receipt (the sharing trace)
- OUTSIDE the local-only zone: this path actually RUNS the query.
Reached ONLY when a caller opts in for an exact number on a
low-confidence quote - never a cached panel price."] P9 --> Out %% ---------------- styling ---------------- %% tiers (measurement fidelity) classDef cheap fill:#7c3f2e,stroke:#e8a87c,color:#fff; classDef mid fill:#3a5a78,stroke:#8fb8d8,color:#fff; classDef exp fill:#2e5e46,stroke:#86c9a0,color:#fff; class T1 cheap; class T2 mid; class T3 exp; %% nature of each step classDef engine fill:#eef2ff,stroke:#7f8fd0,color:#111; classDef human fill:#fff3d1,stroke:#d9a300,color:#111; classDef extcost fill:#f3e0f0,stroke:#b567a4,color:#111; classDef pack fill:#dff3f7,stroke:#1b7f95,color:#111,stroke-width:3px; class S1,S3,S4,S5,S6,S8,P1,P2,P3,P4,P9 engine; class S2,S7 human; class PACK pack; class L1 engine; class L2 human; class L3 extcost; ``` ## The same flow, as commands - **Build** (seller side, once per schema: steps 1–8 above): `costql build --adapter examples/adapters/rickmorty.py:rickmorty_config --out pack.json` - **Quote** (app side, local, the query is not run): `costql quote --pack pack.json ''`, or in Python, `from costql import PricingPack; PricingPack.load("pack.json").quote(query)`. Quote-side is also available in JavaScript via the `costql` npm package. - **Validate** (any result against the frozen contract): `costql validate --pack pack.json` Every quote and receipt follows the frozen [output contract](contract.md); the held-out grading in step 8 is specified in [the evaluation methodology](evaluation.md). --- description: "The frozen v1.0 result shape every costQL quote follows: a billable price in cost-units, safe to bill on, at every tier and on every query." --- # The output contract (v1.0) Every price costQL produces (at any tier, on any query, predicted or measured) follows one frozen, stable shape. This is the contract an application budgets against: it is enforced by `costql.contract.validate()` (dependency-free), and anything that fails validation is, by definition, a contract violation. The contract is demonstrated against the real TMDB demo at every tier in [`packs/contract_examples.json`](../packs/contract_examples.json) (last run: **18 examples, 0 violations**). --- ## The one guarantee that never changes > **`price` is always present, a number `>= 0`, in `currency` cost-units, safe to > bill on**, at every tier and on every query. costQL never refuses to price. `price` is the billable number: a conservative **ceiling** for a predicted quote (it never under-prices) or the **exact total** for a query that ran. Everything else in the result is *explanatory detail*. An app integrates once against the core and simply gains richer breakdowns as the API's instrumentation improves. It never has to change how it reads the number it charges on. Cost-units only, never dollars: the consuming app owns the single rate that turns cost-units into money. costQL prices; the app bills. --- ## The basis: predicted (normal) vs measured (only when a query runs) Almost every result you handle is **`predicted`**: an offline quote computed from the pack, before the query runs. That is the path your app integrates against, and the rest of this page is about it. A **`measured`** result only appears when a query *actually executes*, which is not part of normal offline quoting. It happens in two places: during the build's own accuracy grading (running queries for real to score the pack), and when a caller opts into "run it once for the exact cost" on a low-confidence quote. In day-to-day pricing you never touch it. | `basis` | when | `price` means | |---|---|---| | `predicted` | before the query runs: a **quote** from the static pricing pack (the normal path) | the **safe max** (a ceiling that never under-prices); `typical_price` is the typical everyday cost | | `measured` | only when a query actually runs (build grading, or the opt-in exact path) | the **exact** work the run caused; `confidence` is always `exact` | ## Three tiers = how sharply cost could be resolved A tier is the fidelity the API's instrumentation affords (see [One currency, three fidelities](tiers.md)). It changes what *detail* the result carries, **not** whether you get a billable `price`. | detail section | T1 | T2 | T3 | |---|:--:|:--:|:--:| | `price`, `currency`, `confidence`, `tier`, `basis`, `schema_hash`, `caveats` | ✅ | ✅ | ✅ | | `typical_price` | ✅ | ✅ | ✅ | | `breakdown`: per-resolver cost | | ✅ | ✅ | | `sharing`: observed dedup / cache | | | ✅ | | `external_calls`: named outside hosts + call count | | | ✅ | - **T1**: a single total only. When that is all the API affords, the total is a wall-clock proxy (`currency: wall_time_ms`); work hidden by parallelism/batching is not decomposed and tends to **under-count** (see the genre-hub example: measured T3 156 ms of work → T1 87 ms of elapsed time). - **T2**: per-resolver work (`currency: work_ms`), but sharing is *inferred*, so no observed `sharing` section. (A measured T2 receipt carries no `breakdown` either: the run reported a total without a per-resolver split; a *predicted* T2 quote does carry one, because the model can decompose.) - **T3**: per-resolver work **plus** observed `sharing` (which loads coalesced or hit cache) **plus** `external_calls` (outside hosts named, with the call count; no fee, since costQL can't know what the outside service charges). The validator enforces the gating: e.g. an observed `sharing` section at T1 or T2 is a contract violation. --- ## Field reference Core (mandatory, every result): - `contract_version` (string): `"1.0"`. - `tier` (string): `"T1" | "T2" | "T3"`. - `basis` (string): `"predicted" | "measured"`. - `currency` (string): cost-unit; `"work_ms"` (T2/T3, and measured T1 when work-ms is present) or `"wall_time_ms"` (T1 wall proxy). - `price` (number ≥ 0): the billable number (see the guarantee above). - `typical_price` (number | null): the typical everyday cost; equals `price` for a measured receipt. - `confidence` (string): `"high" | "medium" | "low"` for a quote (predictability, orthogonal to tier; cyclic queries are flagged `low`), `"exact"` when measured. - `schema_hash` (string): which schema/pack produced this. - `caveats` (string[]): human-readable notes (may be empty). Tier-gated detail (optional; present only where the table above allows): - `breakdown` (object[]): `{ resolver_id, cost, invocations, [list_size] }`. - `sharing` (object[]): observed sharing. Inner shape differs by basis (honest asymmetry): **predicted** `{ loader, folds:[resolver…], counted_once }`; **measured** `{ loader, requested, calls, saved, cache_hits, external }`. - `external_calls` (object[]): outside calls costQL observed. Inner shape differs by basis: **predicted** `{ resolver_id, host, calls }`; **measured** `{ host, calls }`. `host` is the outside address; `calls` is the count. No fee: costQL can't know what the outside service charges, so the consuming app prices these (see [External calls](external-calls.md)). A `predicted` result also echoes `query` (convenience, not part of the core). --- ## Real examples (TMDB demo) **Predicted · T1**: total only, wall-clock proxy (`{ person(id:"6193"){ filmography{ movie{ title } } } }`): ```json { "contract_version": "1.0", "tier": "T1", "basis": "predicted", "currency": "wall_time_ms", "price": 56.16, "typical_price": 50.11, "confidence": "high", "schema_hash": "26c786209ec27586", "caveats": [] } ``` **Predicted · T3**: same query, now with per-resolver `breakdown` and observed `sharing`: ```json { "contract_version": "1.0", "tier": "T3", "basis": "predicted", "currency": "work_ms", "price": 69.35, "typical_price": 55.18, "confidence": "high", "schema_hash": "26c786209ec27586", "caveats": [], "breakdown": [ { "resolver_id": "Query.person", "cost": 49.62, "invocations": 1, "list_size": 1 }, { "resolver_id": "Person.filmography", "cost": 0.02, "invocations": 1, "list_size": 20 }, { "resolver_id": "Credit.movie", "cost": 0.29, "invocations": 1, "list_size": 1 } ], "sharing": [ { "loader": "/movie/{id}", "folds": ["Credit.movie"], "counted_once": true }, { "loader": "/person/{id}/movie_credits", "folds": ["Person.filmography"], "counted_once": true } ] } ``` **Predicted · T3 with an outside call** (`{ movie(id:"27205"){ aiSummary } }`): `external_calls` names the host and count; your app prices it: ```json { "contract_version": "1.0", "tier": "T3", "basis": "predicted", "currency": "work_ms", "price": 2393.23, "typical_price": 1722.62, "confidence": "high", "schema_hash": "26c786209ec27586", "caveats": [], "breakdown": [ { "resolver_id": "Query.movie", "cost": 29.68, "invocations": 1, "list_size": 1 }, { "resolver_id": "Movie.aiSummary", "cost": 1690.41, "invocations": 1, "list_size": 1 } ], "external_calls": [ { "resolver_id": "Movie.aiSummary", "host": "api.anthropic.com", "calls": 1 } ] } ``` **Measured · one run, three fidelities** (`{ movie(id:"27205"){ cast(limit:8){ person{ name } } } }`): the same execution downgraded per tier: ```json // T3: per-resolver + observed sharing (8 person loads fully coalesced: requested 8 -> 0 calls) { "tier": "T3", "basis": "measured", "currency": "work_ms", "price": 41.64, "confidence": "exact", "breakdown": [ {"resolver_id":"Movie.cast","cost":41.64,"invocations":1}, {"resolver_id":"Credit.person","cost":0.0,"invocations":8} ], "sharing": [ {"loader":"/movie/{id}/credits","requested":1,"calls":1,"saved":0,"cache_hits":0,"external":false}, {"loader":"/person/{id}","requested":8,"calls":0,"saved":8,"cache_hits":0,"external":false} ] } // T2: request total only (trace carried no per-resolver split) { "tier": "T2", "basis": "measured", "currency": "work_ms", "price": 41.64, "confidence": "exact", "caveats": ["no per-resolver breakdown in trace -> T2 ..."] } // T1: wall-clock elapsed proxy { "tier": "T1", "basis": "measured", "currency": "wall_time_ms", "price": 48.08, "confidence": "exact", "caveats": ["no work-ms in trace -> T1 (wall-clock elapsed proxy) ..."] } ``` Validate any pack's output yourself with `costql validate --pack `, or programmatically via `from costql.contract import validate`. --- ## Stability `contract_version` is `"1.0"`. Additive, backward-compatible changes (new optional fields) keep `"1.0"`. Any change that removes or repurposes a field, or alters the core guarantee, bumps the major version. Consumers should read the core fields by name and treat unknown fields as forward-compatible additions. --- description: "The three real, unrelated GraphQL APIs costQL is proven against (TMDB, Rick & Morty, Northwind), each onboarded with one small adapter and a committed offline pack." --- # The three demo APIs and their packs costQL was proven against three real, unrelated GraphQL APIs: a network passthrough we instrumented (TMDB), a public API we don't own and can't change (Rick & Morty), and a batch-heavy SQLite database we instrumented (Northwind). Each one was onboarded with a single small adapter and zero engine changes, and each ships a committed pricing pack in [`packs/`](../packs) that quotes fully offline. Two of the packs are T3 because we instrumented those demo servers ourselves; Rick & Morty is T1 because it is a black box — each pack at the fidelity its API affords, which is exactly how [tier fit](tiers.md) works in a real adoption. ## Rick & Morty: the "try it right now" one (T1, black box) **What it is:** the live public API at `rickandmortyapi.com/graphql`, not ours, no keys, no server to run. **What it demonstrates:** black-box onboarding. A 93-line adapter ([`examples/adapters/rickmorty.py`](../examples/adapters/rickmorty.py)), zero server changes, ~96% accuracy on held-out queries, with a safe max never under the real cost. The full story is in [the case study](results/rickmorty.md). **Committed pack:** [`packs/rickmorty_t1.json`](../packs/rickmorty_t1.json), tier **T1**, currency **`wall_time_ms`** (the black-box wall-clock proxy). **Try it (offline, right now):** ```bash costql quote --pack packs/rickmorty_t1.json '{ character(id:"1"){ name } }' # -> total-only T1 result, high confidence: price (safe max) + typical_price, # no breakdown/sharing sections. That detail needs T2/T3 instrumentation costql quote --pack packs/rickmorty_t1.json \ '{ character(id:"1"){ episode{ characters{ name } } } }' # -> confidence: low. The character<->episode loop is cyclic; the price is a # structural ceiling with a "run it for the exact cost" caveat ``` ## TMDB: the fully instrumented passthrough (T3) **What it is:** a Strawberry GraphQL passthrough over the live TMDB REST API ([`examples/demos/tmdb`](../examples/demos/tmdb)), with DataLoader batching and a `cost_trace` extension emitting all three fidelities from one instrumentation. Running the server needs free TMDB keys; quoting the committed pack needs nothing. **What it demonstrates:** the full T3 result (observed sharing), plus two deliberately awkward cost dimensions: `Movie.chemistryScore` (local O(n²) compute, zero downstream calls: cost that only work-ms can see) and `Movie.aiSummary` (an **outside** Anthropic call, whose host costQL observes and names for the app to price). Accuracy across the tiers (T1 17% / T2 11% / T3 11%) is in [the case study](results/tmdb.md). **Committed pack:** [`packs/tmdb_t3.json`](../packs/tmdb_t3.json), tier **T3**, currency **`work_ms`**. **Try it:** ```bash costql quote --pack packs/tmdb_t3.json \ '{ person(id:"6193"){ filmography{ movie{ title } } } }' # -> high confidence, per-resolver breakdown, and a "sharing" section showing # which loaders fold to a single counted fetch costql quote --pack packs/tmdb_t3.json '{ movie(id:"27205"){ aiSummary } }' # -> an "external_calls" entry naming api.anthropic.com + the call count (no fee; # your app prices the outside call) costql quote --pack packs/tmdb_t3.json \ '{ movie(id:"27205"){ recommendations{ recommendations{ title } } } }' # -> confidence: low. Cyclic recursion, flagged rather than billed ``` ## Northwind: the batch-heavy database (T3, plus T1/T2 packs) **What it is:** a thin GraphQL passthrough over the real Northwind SQLite reference database (8 categories, 77 products, 609k order-lines) where every entity fetch goes through a batching DataLoader that coalesces a tick's keys into one `SELECT … WHERE id IN (…)` ([`examples/demos/northwind`](../examples/demos/northwind)). Running the server needs a one-command **24 MB reference-DB download**; the committed packs quote offline without it. **What it demonstrates:** heavy entity sharing, a coalescing factor of **38.5×** (963 reads asked → 25 SQL queries), which is exactly the API shape that needs T3's observed sharing and learned **batch-size curves** ([the case study](results/northwind.md)). Packs are committed at all three tiers so you can quote the *same* query at each fidelity and watch the detail sections appear. **Committed packs:** [`packs/northwind_t1.json`](../packs/northwind_t1.json) (T1, `wall_time_ms`), [`packs/northwind_t2.json`](../packs/northwind_t2.json) (T2, `work_ms`), [`packs/northwind_t3.json`](../packs/northwind_t3.json) (T3, `work_ms`). **Try it:** ```bash costql quote --pack packs/northwind_t3.json \ '{ order(id:"15000"){ details(first:15){ product{ category{ name } } } } }' # -> high confidence (sizes declared); T3 prices the batched product/category # reads on their learned size curves instead of charging every repeat costql quote --pack packs/northwind_t2.json \ '{ order(id:"15000"){ details(first:15){ product{ category{ name } } } } }' # -> same query at T2: a breakdown, but no observed sharing and no batch # curves. This database's shape needs the sharing trace; the mismatch is # measured in the case study costql quote --pack packs/northwind_t3.json \ '{ customer(id:"BSBEV"){ orders{ details{ product{ name } } } } }' # -> confidence: low. Two un-paginated list edges compound on one path, so the # size is data-dependent; the ceiling stays safe, the caveat says # "declare sizes or run it" ``` ## Every pack, one contract All five packs produce results in the same frozen shape. Validate any of them with `costql validate --pack `, and see [the output contract](contract.md) for what each tier's result carries. Quoting works in Python (`PricingPack.load(path).quote(query)`) or JavaScript (the `costql` npm package, quote-side). --- description: "The model, baseline, and dataset behind every costQL accuracy number, and how calibration and held-out query sets are kept disjoint." --- # How costQL measures its own accuracy Any accuracy number needs three pieces: a **model** whose prediction is on trial, a **baseline** (ground truth) to compare against, and a **dataset** the comparison runs over. This doc pins down exactly what each is in costQL, and, importantly, what each is *not*. It complements the [tier overview](tiers.md) and the step-by-step [pricing flow](architecture.md); the measured results themselves live in the [TMDB](results/tmdb.md), [Rick & Morty](results/rickmorty.md), and [Northwind](results/northwind.md) case studies. --- ## 1. The three pieces | Piece | In costQL | Produced by | |---|---|---| | **Model (on trial)** | the pricing pack's **prediction** for a query: static analysis, the query is *not* run | `costql/pricer.py` (`Pricer.price`), served via `PricingPack.quote()` (`costql/pack.py`) | | **Baseline (ground truth)** | the query's **actual measured cost** from really running it against the live API | `costql/harness.py` (`Measurement.cost_ms`) | | **Dataset** | real GraphQL queries against a real API | `costql/heldout.py` (calibration + held-out sets) | **Error** = predicted cost vs. measured cost, per query, over the dataset. The baseline is **reality** (measured execution), not a rival estimator we are trying to beat. We are measuring *"how close is the prediction to the truth,"* not *"are we better than some other model."* --- ## 2. Two disjoint datasets: calibration vs. held-out `costql/heldout.py` builds **two deliberately non-overlapping** query sets: | | Calibration set | Held-out set | |---|---|---| | Purpose | **fit** the model | **grade** the model | | Shapes | full-depth coverage ops, depths `[2, 5, 9, 12]`, whale (max) inputs | shallow/mid depths `[3, 7]`, small-vs-whale pagination, alternate inputs, adversarial fixtures | | Seen by the model? | yes (it is fit on these) | **no** (a distribution the model never saw) | Fitting and grading on the same queries would flatter the model. The held-out set proves it generalizes to shapes it was **not** fit on. (Generalization is also shown across *APIs*: a brand-new API ([Rick & Morty](results/rickmorty.md)) is priced with only a ~90-line adapter and zero core changes.) --- ## 3. How the model is built (calibration → rates, once) At build time only (`costql build`, or `build_pack()` from Python): 1. Run every calibration query and record `(invocations_by_resolver, measured_cost)`. 2. Solve, by non-negative least squares (`costql/pricer.py`): ``` op_cost ≈ Σ_resolver invocations[resolver] × unit_cost[resolver] ``` → **one reusable `unit_cost` per resolver.** Only resolvers that do real work carry cost; scalar leaf reads are ~0. The regression is needed because it *separates* fixed per-request overhead from marginal per-call cost across many query shapes. An adapter can supply curated calibration shapes via the `APIConfig.calibration_queries` hook (a callable taking a size, `"whale"` or `"small"`, and returning query strings). **What ships is the rate table, not the queries.** The pricing pack contains schema + `unit_cost` table + batch curves + observed sizes + observed outside hosts. It does **not** contain the calibration queries or their measured prices. The calibration queries dissolve into the rate table; they do not survive as retrievable entries. --- ## 4. How the baseline (ground truth) is measured, per tier To grade a held-out query, `Pricer` predicts it (no run) and the harness **runs it for real** and reads its total cost (`costql/harness.py`, `Measurement.cost_ms`). What "total cost" means gets more specific with the tier: | Tier | Ground-truth total = | Note | |---|---|---| | **T1** (black box) | trimmed-mean whole-request **wall-clock ms** | the only signal a black-box consumer can see; a blurrier proxy for work-ms | | **T2** (per-resolver timings) | **sum of every fired resolver's work-ms** + fixed per-query overhead | complete accounting of the real work of that run | | **T3** (timings + sharing trace) | same sum, with shared/batched calls counted **as they actually coalesced** | real sharing, observed not inferred | Key properties of the baseline, at T2/T3: - **It includes every resolver's cost.** The total is the sum over *all* invocations that fired, plus parse/validate/serialize overhead. We don't *surface* the per-resolver breakdown for held-out grading, but it is all baked into the number. - **It is measurement, not estimation.** There is no model inside the baseline. That is what makes it trustworthy as ground truth. - **It reflects real sharing.** Batched/deduped calls are counted the way the real loader actually coalesced them, which is exactly the thing the T2 *prediction* only *infers*. That gap is what the held-out comparison is designed to expose. Repeated rounds + a trimmed mean cancel sub-ms measurement jitter. --- ## 5. Why there is no "already priced this" lookup A recurring misconception: that a query already seen in calibration gets served its known measured price. **It does not. There is no query→price lookup anywhere.** - `PricingPack.quote()` has one path: parse → fanout → ceiling sum → **predict**. It never checks "did we measure this one before," because the pack stores no query prices. - A calibration query fed back through the pricer is re-derived as a *predicted ceiling* from scratch. It does **not** get its stored measurement. (The predicted ceiling will even differ from its calibration measurement: calibration is fit at the observed operating point, pricing evaluates worst-case.) - The only way to get a measured number for a specific query is to **run it**. That is execution, not a lookup. This is the opt-in exact path (`costql.exact`, which reads a real run's cost-trace receipt), reached only when a caller wants an exact figure on a low-confidence quote. The model collapses infinitely many possible queries into a few dozen resolver rates. That compression is the product; a lookup table can only remember what already happened. --- ## 6. What "accurate" means here (and its honest scope) The held-out baseline is accurate **by construction**. It is the real summed work of the run. Two scoping caveats worth stating plainly: - **That run, that data.** The measured total is the true cost of *this* execution against *today's* data. Against a larger table the true total changes, which is why the model predicts a worst-case **safe max** (the billable number) separately from a **typical** everyday cost, and why data-dependent-size queries are confidence-flagged (see [Honest limitations](limitations.md)). - **Jitter.** A single timing has sub-ms noise; the ground truth is a trimmed mean over repeated rounds, not one stopwatch reading. --- ## 7. Where this lives in code | Concern | File | |---|---| | Calibration + held-out set construction (disjoint) | `src/costql/heldout.py` | | Static prediction (fanout × unit_cost, ceiling/typical) | `src/costql/fanout.py`, `src/costql/pricer.py` | | Model fit (NNLS regression → unit costs) | `src/costql/pricer.py` (`CostModelBuilder.build`) | | Ground-truth measurement (work-ms / wall-clock, trimmed mean) | `src/costql/harness.py` | | Local quote from the pack (no run, no lookup) | `src/costql/pack.py` (`PricingPack.quote`) | | Opt-in exact price (reads a real run's receipt) | `src/costql/exact.py` | --- ## In one paragraph costQL is graded like any predictor: the **model** is the pricing pack's static prediction for a query; the **baseline** is that query's real measured cost from actually running it; the **dataset** is a held-out set of real queries, deliberately disjoint from the calibration set the model was fit on. Ground truth at T2/T3 is the complete sum of every resolver's measured work-ms for the run (real sharing included), so it is trustworthy by construction: it contains no model. There is no query→price lookup: every query, seen or unseen, is predicted from the rate table, and the only measured numbers come from actually executing a query. --- description: "When a field calls an outside service (an LLM, a paid API), costQL names the call and observes its host; your app puts the price on it." --- # External calls costQL prices your API by timing it. But some of your fields call an **outside service** for you: an LLM, a licensed data feed, another paid API. costQL can't time what leaves your account there, and it can't know what that service charges you. So it doesn't guess. It **names the call**, and your app puts the price on it. **If none of your fields call an outside service, skip this page: nothing here is required.** This is only for fields that reach a host that isn't yours (a call to `api.anthropic.com`, say). A database query is your own work, and costQL measures it for you. ## Step 1: flag the field in your adapter List the field under `bounded_fields`. This tells the build to sample it once, on its own, instead of fanning it out during calibration. ```python bounded_fields={ "Movie.aiSummary": "outside call (api.anthropic.com); " "sampled in isolation, host observed, priced by the app", } ``` See [the adapter guide](adapters.md) for what every field does. ## Step 2: build Build as usual: ``` costql build --adapter tmdb.py:build --out tmdb.json ``` When costQL samples that field, it watches the call and records the **host** it saw. That host is now saved in the pack (in `model.external_hosts`). Nothing else changes; no number is invented. ## What shows up in a quote At **T3** (the only tier that names the host), a quote that hits the field carries an `external_calls` line: ```json "external_calls": [ { "resolver_id": "Movie.aiSummary", "host": "api.anthropic.com", "calls": 1 } ] ``` - `host` is the outside address costQL saw. - `calls` is how many times this query hits it (the safe ceiling count). - There is **no fee**. costQL never knows what the outside service charges. See [the output contract](contract.md) for the full field shape. ## Your app puts the price on it The pack tells your app *where* the outside call is and *how many* there are. Your app already knows the rest: it is the one making the call, so it knows the request, and it knows what that host charges. So your app reads `external_calls`, prices each one, and adds it to the quote's `price`. That split is on purpose. costQL gives you the true cost it can measure; the money for an outside call is yours to add, because only you can know it. ## One limit `external_calls` is a **T3** thing: T3 is the only tier that names the host. And to match an outside call to the field that made it, your app reads the per-resolver `breakdown`, which is **T2 or T3**. At **T1** there is no per-resolver detail at all, so app-side pricing of outside calls needs at least T2. --- description: "Short answers to the most common costQL questions: does it call your API, what a price is in, dollars vs cost-units, and more." --- # FAQ Short answers to the questions that come up most. Each links to the page with the full story.
Does costQL call my API when I quote a query? No. Quoting is fully offline. The build makes real calls once, to learn your API, and saves what it learned as the pricing pack. After that, your app prices queries against that static file with no network calls. See [Quickstart](quickstart.md).
What is a price in? Is it dollars? Work-time: how much real work a query causes on your server, in milliseconds (the pack calls this a cost-unit). It is not dollars. You map cost-units to whatever you charge in your own app. This keeps costQL honest about *cost* and leaves *pricing* to you.
Do I have to change my server? Not to start. Your first pack (T1) times whole queries from the outside and needs no server changes at all. The instrumented tiers (T2, T3) ask your server to report per-resolver work; that's the one change, covered in [Instrumenting for T2/T3](instrumentation.md). Which tier fits is a fact about your API, not a ranking: see [Tier fidelity](tiers.md).
Can it price a call to a paid API, like an LLM? The *work* a paid call takes is timed automatically, like any other field. But costQL can't know what an outside service charges you, so it doesn't guess: it names the call (the host, and how many) and your app puts the price on it. Here is how: [External calls](external-calls.md).
What happens when my schema changes? Rebuild the pack (minutes of measurement). Every quote carries a `schema_hash`, so a consumer comparing hashes notices drift. Any fees you authored survive the rebuild.
What is the difference between typical and safe max? (the two numbers on every quote) Every quote gives you two numbers, because a query's real cost depends on how many items its lists return, which you cannot know for sure until you run it. - **Typical** (the `typical_price` field) is what the query *usually* costs. costQL assumes each list comes back at its average size. Use it to understand normal, everyday cost. - **Safe max** (the `price` field) is the *most* it could cost. costQL assumes the largest sizes it has seen, and it is guaranteed never to fall below the real cost. Price on it whenever never undercharging matters. They are **equal** when a query's size is fixed (bounded lists, single objects) and differ only when a query could balloon in size. Rideshare rule: *"usually $12, never more than $18."* See [the output contract](contract.md).
What about queries costQL can't predict well? It says so. Hard-to-predict shapes (for example, cyclic queries) come back with `confidence: "low"` rather than a falsely precise number. The [limitations](limitations.md) page lists what costQL does not try to do.
--- description: "Query-complexity limits, demand control, and DoS protection all need a cost per query to threshold on. costQL measures that cost instead of making you hand-author per-field weights." --- # Limiting expensive queries Query-complexity limits, demand control, cost-based rate limiting, DoS protection: every guard against expensive GraphQL queries needs the same thing, a cost per query to threshold on. Today you hand-author that cost with `@cost` directives or per-field weights and hope the numbers are right. costQL measures it instead. ## Same mechanism, measured weights The mechanism here is mature and well-trodden: score the query statically before it runs, bound the pagination, reject anything over budget before a resolver fires. `graphql-query-complexity`, `graphql-cost-analysis`, GraphQL Armor, Apollo Router demand control, HotChocolate's `MaxFieldCost` — they agree on all of that. costQL agrees too. They also all leave one thing to you: the cost of each field, declared by hand. That declaration is a guess, and it is the only part costQL replaces — with a number timed from your real API. ## Write the gate; costQL supplies the number costQL prices; it does not block. You keep the gate, a one-liner, and feed it a measured price: ```python from costql import PricingPack pack = PricingPack.load("packs/your_pack.json") def admit(query, variables=None, budget=250): quote = pack.quote(query, variables) if quote["price"] > budget: # safe max: never below the real cost raise TooExpensive(quote["price"], budget) return quote ``` `price` is the safe ceiling — [guaranteed never below what the query actually costs](../contract.md) — so a query that clears the budget really is within it. Bill on that number or block on it; it is the same measured number either way. The same call works [in JavaScript](../js.md) and [from the CLI](../quoting.md), so the check can live in a gateway, a resolver, a CI step, or an agent's planning loop. ## Why measured beats hand-authored, right here Two query shapes are where hand-authored weights fail, and they are the two a limit exists to catch: - **Batching over-blocks the good resolvers.** A field behind a DataLoader resolves a list of 100 in one round-trip, not 100. Per-field-times-count math scores it at 100× and rejects exactly the well-built resolver you want people to use. costQL prices shared work once; on our share-heaviest test that cut error from 315% to 12% (see the [Northwind case study](../results/northwind.md)). - **Recursion slips under-blocked.** A cyclic query is the classic GraphQL DoS vector, and a static hand-authored weight never sees it coming — the usual fix is a penalty bolted on after an incident. costQL detects cycles up front, flags them `confidence: low`, and prices them at a structural ceiling rather than a too-low guess (auto-flagged unprompted on the [Rick & Morty API](../results/rickmorty.md)). A number tuned to what the server actually does is the difference between a limit that holds and one that punishes your best resolvers while waving the dangerous ones through. ## Your first pack needs nothing from the server You do not have to instrument anything to start. **T1** prices any GraphQL endpoint black-box, from the outside, and still returns a safe ceiling — enough to threshold on today. If your API batches or caches heavily and you want the limit to stop over-blocking those resolvers, [instrument for T2/T3](../instrumentation.md); until then T1 errs high, which is the safe direction for a guard. See [tier fidelity](../tiers.md) for what each tier buys you. --- description: "x402's upto scheme authorizes a ceiling and settles the actual amount. That is exactly the two numbers costQL already gives you: the predicted price is a safe ceiling that never under-prices (authorize on it), the measured price is the exact receipt (settle on it)." --- # Paying per query with x402 [x402](https://x402.org/) lets an HTTP server charge for a request in stablecoin: the server answers with `402 Payment Required`, the client signs a payment, a facilitator settles it. Its experimental **`upto`** scheme splits the charge in two — the client authorizes a **maximum** up front, and the server settles the **actual** amount consumed, which must be less than or equal to that maximum. That is the same two numbers costQL already returns for every query. This guide is the seam between them. It adds nothing to the pricing engine; it just points the two numbers costQL gives you at the two fields x402 asks for. ## The fit is exact The `upto` scheme reuses one field, `amount`, in two phases: at **verification** it is the ceiling the client authorizes; at **settlement** it is the actual amount to charge (`≤` the ceiling). costQL's [output contract](../contract.md) returns a `price` under two bases that line up one-to-one: | x402 `upto` phase | costQL `price` | the guarantee | |---|---|---| | **authorize** — `amount` = max the client will allow | `basis: "predicted"` — a **quote**, before the query runs | the safe **ceiling**; [never under-prices](../contract.md) | | **settle** — `amount` = actual consumed (`≤` max) | `basis: "measured"` — an **exact receipt**, after it ran | the real work the run caused; `confidence: "exact"` | The predicted price is what makes an `upto` authorization *safe*: because it is guaranteed never to fall below the real cost, you never authorize too little and get a legitimate query rejected at settlement. The measured price is what makes settlement *fair*: the payer is charged for the work their query actually caused, not a hand-guessed sticker price. The gap between them — the headroom costQL leaves above true cost — is simply never settled, and the client keeps it. ## The one thing you own: the cost-unit → stablecoin rate costQL prices in **cost-units, never dollars** (`work_ms`, or `wall_time_ms` at [T1](../tiers.md)). x402 settles a stablecoin `amount` in atomic units. So you own exactly one number: the rate that turns a cost-unit into atomic units of your asset. Pick it once, apply it **identically** to the ceiling and the settle amount. Because the same rate multiplies the same cost-units, `ceiling ≥ settle` holds by construction — costQL's guarantee carries straight through the conversion. ``` RATE = 100 # atomic units of USDC (6 decimals) per work_ms # -> 1000 work_ms = 100_000 atomic = $0.10 ``` Keeping the rate app-side is deliberate: costQL never needs to know your margin, your currency, or your business model, and the same pack prices the query whether you bill in USDC, credits, or nothing at all. ## Authorize: price the query, answer 402 When a request arrives, quote it with your pack and hand the **predicted** `price` to x402 as the authorized maximum. This is the shipped, one-call path, and it works black-box at T1 on any GraphQL API — no server instrumentation needed to start. ```python # server: return 402 with a costQL-derived ceiling from costql import PricingPack pack = PricingPack.load("packs/your_pack.json") RATE = 100 # atomic units per work_ms def payment_required(query, variables=None): quote = pack.quote(query, variables) # basis: "predicted" max_amount = round(quote["price"] * RATE) # safe ceiling -> atomic units return { "scheme": "upto", "network": "eip155:8453", # e.g. Base "amount": str(max_amount), # the MAX the client authorizes "asset": USDC_ADDRESS, "payTo": YOUR_ADDRESS, "maxTimeoutSeconds": 60, } ``` The same call in TypeScript, using the [npm `costql`](../js.md) package (the quote side ports one-to-one): ```ts import { PricingPack } from "costql"; const pack = PricingPack.fromObject(packJson); const RATE = 100n; // atomic units per work_ms function paymentRequired(query: string, variables?: Record) { const quote = pack.quote(query, variables); // basis: "predicted" const maxAmount = BigInt(Math.ceil(quote.price)) * RATE; // safe ceiling return { scheme: "upto", network: "eip155:8453", amount: maxAmount.toString(), // the MAX authorized asset: USDC_ADDRESS, payTo: YOUR_ADDRESS, maxTimeoutSeconds: 60, }; } ``` Round the ceiling **up** (`ceil`), never down: rounding is the one place you could accidentally authorize below cost, and up keeps the ceiling a ceiling. ## Settle: measure the run, charge the actual After the query runs, settle at what it actually cost. The measured number is the total real work from the response's [`extensions.cost_trace`](../instrumentation.md) — the same seam that powers [T2/T3](../tiers.md). Its `work_ms` total *is* the `price` of the `basis: "measured"` receipt (see the measured examples in the [contract](../contract.md)). Convert it with the **same** `RATE` and pass it back to the facilitator's settle step as the new `amount`. ```python # server: after executing the query with COSTQL_TIER on def settlement_amount(response): trace = response["extensions"]["cost_trace"] # emitted by your instrumented server measured_ms = trace["work_ms"] # the exact work this run caused return round(measured_ms * RATE) # actual -> atomic units, <= the ceiling ``` ```ts function settlementAmount(response: GraphQLResponse): bigint { const measuredMs = response.extensions.cost_trace.work_ms; // exact work return BigInt(Math.round(measuredMs * RATE)); // actual, <= ceiling } ``` You then set this as the `amount` in the `PaymentRequirements` you pass to the facilitator's `/settle` endpoint — per the `upto` scheme, that field carries the actual amount at settlement time. It is `≤` the ceiling you authorized, so the facilitator accepts it and the client is charged only for real work. Round the settle amount to nearest; the ceiling already covers any rounding slack. ## Why a measured basis beats charging per token or byte x402's own `upto` examples charge *per token generated* or *per byte transferred* — proxies you multiply by a hand-set unit price. costQL settles on the query's **measured cost** instead, which is the honest basis for a GraphQL API and the two places hand-authored proxies break: - **Batching.** A field behind a DataLoader resolves a list of 100 in one round-trip. A per-item price over-charges it 100×; costQL prices the shared work once (on our share-heaviest test that cut error from 315% to 12% — see the [Northwind case study](../results/northwind.md)). The `upto` ceiling stays honest and the settle stays fair. - **Recursion.** A cyclic query is the classic way to make a cheap-looking request expensive. costQL detects the cycle up front, flags it `confidence: "low"`, and authorizes at a structural ceiling rather than a too-low guess ([Rick & Morty case study](../results/rickmorty.md)) — so the authorization covers the blow-up before a token is spent. ## What ships today, and what you wire - **The ceiling (authorize) is one call, today.** T1 prices any GraphQL endpoint black-box and returns a safe ceiling — enough to authorize an `upto` payment right now, in [Python or JS](../js.md), with no server changes. - **The exact settle needs the trace.** A `basis: "measured"` receipt reads `extensions.cost_trace`, which means [instrumenting for T2/T3](../instrumentation.md). Until you do, you have two honest options: settle at the ceiling (the plain `exact` scheme — safe, just not generous), or settle on the T1 wall-clock proxy. Both stay at-or-above nothing the client didn't authorize. - **`upto` is experimental in x402.** If your facilitator doesn't support it yet, the same mapping works with the stable `exact` scheme by authorizing *and* settling on the predicted ceiling — you lose the measured refund, not the safety. costQL prices; it does not move money. x402 moves money; it does not know what a query costs. The pricing engine is the product, and it stands on its own — this guide is just the adaptor that lets one feed the other. --- description: "The one response extension (extensions.cost_trace) your GraphQL server emits to let costQL see per-resolver and shared work (T2/T3)." --- # Instrumenting your server for T2/T3 T1 needs nothing from your server: costQL times whole requests from the outside. The instrumented tiers (T2/T3) need the server to *tell* costQL what work a request actually caused, via one extension field on the GraphQL response. This page specifies that seam. The two demo servers ([`examples/demos/tmdb`](https://github.com/shapemachine/costql/tree/main/examples/demos/tmdb), [`examples/demos/northwind`](https://github.com/shapemachine/costql/tree/main/examples/demos/northwind)) are complete reference implementations (Strawberry/Python, ~150 lines of tracing each), but the seam is JSON over HTTP. Any server language can emit it. ## The seam: `extensions.cost_trace` ```json { "data": { "...": "..." }, "extensions": { "cost_trace": { "work_ms": 48.7, "resolver_work_ms": { "Query.movie": 12.1, "Movie.cast": 36.6 }, "invocations": { "Query.movie": 1, "Movie.cast": 1, "Credit.person": 8 }, "loaders": { "/person/{id}": { "requested_keys": 8, "batch_calls": 1, "batched_keys": 8, "cache_hits": 0, "work_ms": 31.2 } } } } } ``` ## What each tier requires **T2: per-resolver work.** Emit `work_ms`: the **summed duration of the real work** the request caused (downstream call durations + local compute), *not* wall-clock elapsed time. Concurrent calls add their durations. Emit `invocations` (how many times each resolver fired) and, if you can, `resolver_work_ms`. This removes the parallelism blur: work hidden inside concurrent elapsed time becomes visible. **T3: observed sharing.** Additionally emit `loaders`: one entry per batching loader (DataLoader, SQL `IN (...)` reader, HTTP client with request coalescing), with - `requested_keys`: how many times resolvers *asked* for a row this request, - `batch_calls`: how many physical calls actually went out, - `batched_keys`: distinct keys actually fetched, - `cache_hits`: asks served from the per-request cache, - `work_ms`: that loader's own summed time. From this costQL learns which resolvers fold onto shared loaders (so repeated work is counted once) and fits each loader's **batch-size → cost curve** (a flat curve for per-id HTTP calls, a rising one for `IN`-list SQL: learned, never assumed). Declare your loader IDs in the adapter's `known_loaders` so a loader that never fires is reported as dead. ## Practical notes - **Keying:** loader IDs are arbitrary strings. Endpoint templates (`"/person/{id}"`) or table names (`"products:byCategory"`) both work; they just have to be stable. - **Overhead:** the demos time with monotonic clocks around existing loader calls; the trace adds microseconds and is only assembled when tracing is on. - **Gating:** emit the trace only for calibration traffic if you like. The demo servers gate on a `COSTQL_TIER` env var. Packs are built rarely (once per schema change); production requests never need the extension unless you also want exact post-execution receipts. - **Honesty is automatic:** if `costql build` sees no `work_ms` in responses, it downgrades the pack to T1 and says so. An adapter cannot claim fidelity the server doesn't emit. ## Do you need this? Only if your API's shape calls for it. If your resolvers fire downstream work **in parallel**, per-resolver timing (T2) is what makes that work visible. If your server **batches, coalesces, or caches reads**, the sharing trace (T3) is the only way costQL can watch that happen — a tier that can't see sharing can't price those queries, and the size of that mismatch is measured in [the Northwind case study](results/northwind.md). If your work is serial and unshared, T1 already measures it well and this page is optional reading. Start at T1 either way. It ships today. --- description: "npm install costql gives you the quote side in JavaScript/TypeScript: load a pack and price queries offline in Node, browsers, or edge. Zero runtime deps." --- # The JS package `npm install costql` gives you the **quote side** of costQL in JavaScript/TypeScript: load the same pack file the Python engine writes and price queries offline in Node, browsers, or edge runtimes. Zero runtime dependencies. Building packs stays in Python (`pip install 'costql[build]'`) by design: that side needs a live API and numerical fitting; quoting is pure traversal and belongs everywhere your app runs. ## Usage ```ts import { PricingPack, validate } from "costql"; // Node const pack = await PricingPack.load("packs/tmdb_t3.json"); // Browser / edge: fetch the pack like any static asset const pack = PricingPack.fromObject(await (await fetch("/packs/tmdb_t3.json")).json()); const quote = pack.quote('{ movie(id:"27205"){ cast(limit:8){ person{ name } } } }'); quote.price // 50.5384 (safe max, cost-units) quote.typical_price // 36.3769 (typical everyday cost) quote.confidence // "high" | "medium" | "low" quote.caveats // e.g. the cyclic-recursion explanation, when flagged quote.breakdown // per-resolver cost lines (T2/T3 packs) quote.sharing // folded shared loaders (T3 packs) quote.external_calls // named outside hosts + call count (T3 packs) validate(quote) // [] (contract v1.0 violations, if any) ``` The result object is the [frozen output contract v1.0](contract.md): the identical shape the Python engine emits, tier-gating included. `PricingPack.fromObject` / `fromJSON` throw `PackVersionError` on a pack written by a newer costql, a missing section, or a non-pack, the same gate as the Python loader. ## The conformance guarantee "Identical to the Python engine" is a tested claim, not a hope. The repo freezes an oracle ([`conformance/quotes.json`](https://github.com/shapemachine/costql/blob/main/conformance/quotes.json), 56 full quote results spanning simple, fanout, sharing-heavy, external-call, cyclic, and sugared (fragments/aliases/variables) queries across the five demo packs plus a synthetic union-schema pack) and CI runs both engines against it on every PR. Numbers must agree within `max(1e-6, 1e-9 · |expected|)`; every other field must be deep-equal. Even the caveat *strings* match. Pinning: `costql@0.1.x` (npm) conforms to `costql` 0.1.x (PyPI), contract v1.0, `pack_version` 1. ## Shared parser, shared behavior The JS parser is a deliberate line-for-line port of the Python one, so the two engines accept the same query surface (fragments, aliases, variables, directives: see [Quoting queries](quoting.md)) and price it identically. To pass variable values, hand them to `quote` directly: ```ts pack.quote('query($n: Int!){ movie(id:"27205"){ cast(limit:$n){ person{ name } } } }', { n: 4 }); ``` If you hit an edge where the two engines disagree, that is a bug. Please file it with the pack + query. ## What's deliberately absent - No `build`/calibration APIs: Python-only. - No network access in `quote()`: a pack in, a contract result out. - No dollars: cost-units only; currency conversion is your app's concern. --- description: "Where costQL's typical estimate is least certain — cyclic-recursion and data-dependent queries. In every case the billable ceiling stays safe: costQL degrades gracefully to a priced quote plus an honest confidence tag, never a refusal." --- # Honest limitations costQL gives you **two numbers per quote, and they fail differently.** The *typical* estimate is a best guess for a normal-sized case. The **billable ceiling** is the safe maximum — it never under-prices, and it is the number costQL bills on. Every soft spot below can bend the *typical* estimate on some hard query. In each one the **ceiling still holds**, and costQL tags the query `confidence: low` so you know to lean on the ceiling, not the typical. So read these as limits on the typical estimate's *precision*, not on costQL's guarantee — a pricing tool you can't trust about its own blind spots isn't worth trusting about prices. The one exception is called out where it lives (the single-resolver size dimension below), because honesty is the whole point of this page. Everywhere else, the designed behavior is **graceful degradation, never refusal**: a contract-valid price plus an honest confidence tag, every time. ## Cyclic-recursion queries A query that re-enters a type through a list edge (movie → recommendations → recommendations…; character → episodes → characters…) fans out combinatorially, and the real backend de-duplicates by an amount only *running* the query reveals. costQL does not fabricate a dedup guess. It prices the query **structurally** (a safe max), flags it `confidence: low`, and attaches a caveat: run it once for the exact cost. On the [TMDB demo](results/tmdb.md), the 4 cyclic held-out queries averaged ~92% error on the typical estimate — which is exactly why the typical is flagged, not trusted as the price. The number you are billed is the structural safe max, and it stays above the real cost. On [Rick & Morty](results/rickmorty.md), every loop-shaped query was auto-flagged. ## Data-dependent result sizes A query with **two or more un-paginated list edges compounding on one path** ("this customer's orders, and every line-item of each") has a cost that depends on the data (how many orders *that* customer has), not just the query's shape. The confidence classifier detects this pattern and returns `low` with a "declare sizes or run it" caveat. The typical estimate can drift (a ~39% miss on the worst such query in the [Northwind study](results/northwind.md)); the **ceiling stays safe** (verified there: 2.65 vs a real 1.95–2.40 across every customer, including the heaviest). Declaring sizes (pagination arguments) restores high confidence. ## T1-only (black-box) APIs If an API emits no cost-trace instrumentation, costQL still prices it. That is the T1 fidelity, and it is [the designed starting point](tiers.md). The difference is in *detail*, not in the guarantee: a T1 result carries the total only (`currency: wall_time_ms`, a wall-clock proxy for work-ms) with no per-resolver `breakdown`, no observed `sharing`, and no `external_calls`. Work hidden by parallelism or batching is not decomposed and tends to be under-counted in the proxy. Measured honestly, T1 still performed well where the cost is dominated by what a black-box caller actually experiences: ~96% accuracy on the public [Rick & Morty API](results/rickmorty.md). ## When a field's cost grows with an argument costQL learns how a cost grows with size by **measuring the same field at several sizes** during calibration. It does this for the two size-sensitive shapes that dominate real APIs — and that writing an adapter naturally exercises: **batched loaders** (a shared read's cost against how many rows it pulls; the [Northwind study](results/northwind.md) fit this curve and verified it stays ceiling-safe under heavy sharing) and the **list fields** you already vary `first:` / `limit:` across in your calibration queries. One shape isn't swept by default: a **single resolver whose own per-call work grows with an argument** — a field that takes, say, `limit: 500` and does real work on all 500 rows in a single call. If calibration only ever measured it small, costQL prices it flat, and a much larger request against it can come in low. Two reasons this is a corner, not a cliff: - **In every case study, its measured effect was ~0%.** On passthrough-style APIs the list items ride inside the parent's single fetch, so there is no per-item cost to scale. It takes an uncommon shape — a field doing heavy per-item local work — to matter at all. - **The fix is one calibration query, not a redesign.** If such a field ever surfaces, list it in your calibration queries at a large argument, name its size argument (a [`size_root`](adapters.md)), and rebuild the pack. Building is offline and one-time; the pack is just a file you regenerate. From then on the quote scales correctly. costQL prices what your calibration exercises. The size-sensitive fields you would naturally reach for are swept for you; the rare one you would not think of is a cheap, known thing to fold in the moment it shows up. ## Polymorphic branches price as an upper bound Before a query runs, nobody knows which `... on Type` branch each object resolves to, so [the quote](quoting.md) walks every branch. At most one fires per object, so the price is a safe max, and the quote says so in a caveat naming the branched paths. Run the query for the exact cost. ## A missing variable value prices at the worst case A `$variable` with no supplied value and no declared default loses its argument, so that field prices at the ceiling's worst-case bound: possibly higher than needed, never an under-price. Passing values ([`quote(query, variables)`](quoting.md)) restores the exact bound. ## Non-goals (by design, not omission) - **No hosted service.** The pricing pack is a static, local file; there is no sidecar, pricing endpoint, or extra API call in the quote path. See [the architecture](architecture.md). - **No dollars, no billing.** costQL speaks cost-units only; the consuming app owns the single rate that turns cost-units into money. - **No load or traffic model.** A quote prices **one execution** of a query. What you multiply that by — requests per second, concurrent callers, total volume — is your own infrastructure dimension. Pricing *that* (a rate limit, a throughput tier) is the API owner's call, and costQL leaves it to you. - **No buyer-facing transparency mechanism.** How much of a quote's breakdown a seller shows their customers is the seller's design call, not costQL's. --- description: "What is inside a costQL pricing pack: the schema, fitted costs, observed sizes, and hosts, all in one self-contained file with no server or network." --- # Price Pack Format A **pricing pack** is the single file costQL produces, and the only thing your app needs to price queries. It is fully self-contained: the schema, the fitted costs, the observed sizes, and any observed outside hosts, with no server, no sidecar, and no network call. This page documents what is inside one, so you can inspect, diff, or debug a pack directly. You never hand-edit a pack; apps read it through `PricingPack.load()`. What the pack *produces*, the quote result, is a separate shape specified in [the output contract](contract.md). This page is the other half: what goes *in*. ## Top-level keys | key | type | what it is | |---|---|---| | `pack_version` | number | pack format version (currently `1`). | | `schema_hash` | string | a fingerprint of the API's schema. Every quote echoes it, so a consumer can detect that a pack no longer matches the live schema. | | `tier` | string | `"T1"`, `"T2"`, or `"T3"`: the fidelity this pack was built at (see [tier fidelity](tiers.md)). | | `currency` | string | the cost-unit every price is in: `"work_ms"` (T2/T3) or `"wall_time_ms"` (the T1 wall-clock proxy). Never dollars. | | `introspection` | object | the API's GraphQL introspection result, stored so the pack can walk the schema and price any query with no live endpoint. | | `model` | object | the cost model: the actual pricing payload (below), including any observed outside hosts (see [External calls](external-calls.md)). | | `note` | string | a human-readable reminder of what the pack is (offline, cost-units, never dollars). | ## Inside `model`: the pricing payload This is where a query's price actually comes from. Every price is computed from these fields alone. The pack stores no per-query prices and does no lookup: `price = sum over the query of unit_cost x invocations`. | field | type | what it does | |---|---|---| | `unit_cost` | `{resolver_id: number}` | the cost of one invocation of each resolver, in cost-units. The core of every price. | | `typical_size` | `{resolver_id: number}` | the **average** list size observed for each list-returning resolver during calibration. Price the query with these and you get the **typical** number. | | `max_size` | `{resolver_id: number}` | the **worst-case** (largest) list size observed. Price with these and you get the **safe max**. Typical vs safe max is exactly this one swap of sizes (see [the FAQ](faq.md)). | | `default_cap` | number | the list size assumed for an edge that declares no size and was never observed. A conservative fallback. | | `safety` | number | a calibration-derived multiplier (`>= 1`) applied so the safe max never lands below a measured calibration cost. | | `noise_buffer_ms` | number | a small additive allowance for measurement noise, in ms. Usually `0`. | | `external_hosts` | `{resolver_id: host}` | **T3 only.** For a bounded field that calls an outside service, the host costQL observed at build time (e.g. `api.anthropic.com`). Surfaced in a quote as `external_calls` for your app to price (see [External calls](external-calls.md)). Empty when there are none. | | `batch_groups` | `{resolver_id: loader_key}` | **T3 only.** Which resolvers are served by a shared loader, so their repeated work is counted once. Empty at T1/T2. | | `loader_fns` | `{loader_key: curve}` | **T3 only.** The learned batch-size curve for each shared loader (below). Empty at T1/T2. | | `scan_before_paginate` | `[resolver_id]` | resolvers whose backend scans a full set before paginating, so a small page can still cost like a large scan. Usually empty. | | `uncovered_edges` | `[resolver_id]` | schema edges the calibration panel did not exercise, listed for honesty. Usually empty. | | `cost_currency`, `schema_hash` | | mirror the top-level `currency` and `schema_hash`; the model is self-describing. | ### A `loader_fns` curve (T3) Each shared loader carries a small curve learned from calibration: cost as a function of how many distinct keys a batch pulls. ```json "": { // e.g. a database loader that pulls N rows per batch "root": "", "kind": "linear", // const or linear: the shape fit from the size sweep "base": 12.5, // cost at the smallest batch "slope": 0.4, // added cost per extra distinct key "cap": 12, // largest batch size ever observed (clamps the input) "safety": 1.2, // multiplier keeping the curve a safe upper bound "typical": 9.0, // the typical batch size "points": [[1, 12.5], [8, 15.7]] // the measured (size, cost) samples it was fit from } ``` A network loader tends to fit **flat** (`const`): a batched call costs about the same as a single one. A database loader fits a **rising** curve: a 300-key batch costs more than a 3-key one. Which one it is comes from the data, never assumed. ## What differs by tier - **T1** (black box): `unit_cost`, `typical_size`, `max_size`, `default_cap`, and `safety`, in `wall_time_ms`. `batch_groups` and `loader_fns` are empty; a black box affords no view of shared work. - **T2** (per-resolver work): the same shape in `work_ms`, with per-resolver costs that no longer hide parallel work. Sharing is still inferred, so no observed `loader_fns`. - **T3** (work plus sharing trace): adds `batch_groups` and `loader_fns` (observed coalescing, priced once on the learned curve), and names any observed outside hosts in `external_hosts`. ## Inspecting a pack A pack is plain JSON. To see a resolver's cost and observed sizes: ```bash python -c "import json; m=json.load(open('packs/tmdb_t3.json'))['model']; \ print(m['unit_cost']['Movie.cast'], m['typical_size']['Movie.cast'], m['max_size']['Movie.cast'])" ``` Or validate the result a pack produces against the frozen shape with `costql validate --pack ` (see [the output contract](contract.md)). --- description: "A pack is a static JSON file. This is how to publish it so whoever prices a query — your own app, or a third party's agent — can fetch it before the call." --- # Publishing a pack A pack is one static JSON file (see [the pack format](pack-format.md)). Once it's built, someone has to be able to *get* it before they can price a query. That someone is either your own app, or — if you want callers to know the cost before they call you — a third party's client or agent. costQL doesn't serve packs; it builds them. Where the file lives is yours to decide. This page recommends how, from the simplest case to the one that lets an agent find the price with no human in the loop. ## Vendor it (your own app) If the only thing pricing queries is an app you control, you don't publish anything. Commit the pack into that app's repo and load it from disk. This is the default the [quickstart](quickstart.md) shows. ```python pack = PricingPack.load("packs/tmdb_t3.json") ``` Nothing below is needed unless you want *other people* to read the price. ## Serve it as a static file To let callers price a query before they hit your API, put the pack somewhere they can fetch it — an S3 bucket, a CDN, your docs site, any static host. It's plain JSON; both engines load a fetched object directly (see [the JS package](js.md)). ```ts const pack = PricingPack.fromObject(await (await fetch( "https://api.example.com/costql/pack.json")).json()); ``` Two things to get right: - **Version the URL** (`…/costql/pack-v3.json`) or set cache headers, so a consumer isn't stuck on a stale copy or fighting your CDN cache. - **Every quote echoes `schema_hash`.** A consumer compares it against your live schema to detect that the pack no longer matches the API — build a fresh pack and publish it whenever the schema moves. ## Publish it at a discoverable location (recommended) The step that turns "price before you call" from a manual copy into something a client or agent can do on its own: serve the pack at a **well-known path** off your API's origin, so it's findable from the endpoint URL alone. ``` https://api.example.com/.well-known/costql.json ``` Serve either the pack itself, or a small pointer to it: ```json { "pack_url": "https://cdn.example.com/costql/pack-v3.json", "tier": "T3", "schema_hash": "26c786209ec27586" } ``` This is a convention costQL recommends, not something the library enforces — there's no wire protocol to implement, just a file at a predictable place. An agent that knows your GraphQL URL can then find the price without being handed a link. ## Ship it as a package When the consumer is another codebase rather than an ad-hoc client, publish the pack as a versioned npm or PyPI package (`@example/costql-pack`). It then updates through normal dependency tooling, with a changelog and pinned versions. Good for known integrators; overkill for a public "here's what a call costs" page. ## What a published pack *is* A pack is **your stated prices, measured by costQL** — the schema, the fitted per-resolver costs, and any observed outside hosts, nothing more. costQL doesn't sign, attest, or audit a pack, and there is no baked-in step that edits the numbers: a costQL pack reports what it *measured* (see [external calls](external-calls.md) for the one thing left to the app, and why). So a consumer who fetches your pack is trusting your published prices the same way they already trust your bill — reasonable, because you're the one billing them. If you post-process the JSON before serving it, that's your own layer, outside costQL, and costQL's "the price errs high — the ceiling stays a ceiling" guarantee is then yours to keep. Marking a price *up* keeps the ceiling a ceiling; marking it *down* does not. ## If the price is sensitive Nothing says a pack must be public. Put it behind the same auth as the rest of your API, or hand it only to integrators under contract. The distribution choices above all work behind a login; discoverability is a convenience, not a requirement. --- description: "From a live GraphQL API to your first offline price in about a minute: install costQL, quote a demo pack, then build your own." --- # Quickstart costQL turns a live GraphQL API into a **pricing pack** (one self-contained JSON file) and then quotes any query against that pack fully offline. Build once in Python; quote forever in Python or JavaScript. This page gets you from zero to your first quote in about a minute, and to your first *own* pack in about fifteen. ## 1. Quote a committed demo pack (offline, 60 seconds) ```bash pip install costql git clone https://github.com/shapemachine/costql && cd costql costql quote --pack packs/tmdb_t3.json '{ movie(id:"27205"){ cast(limit:8){ person{ name } } } }' ``` ``` pricing pack: schema 26c786209ec27586 · tier T3 · currency work_ms · offline query : { movie(id:"27205"){ cast(limit:8){ person{ name } } } } tier/basis : T3 · predicted price : 50.5 work_ms (safe max, never under real cost) typical : 36.4 work_ms (typical everyday cost) confidence : high ``` No server is running. Nothing touched the network. The pack file carries the schema, the fitted per-resolver costs, and any observed outside hosts: everything a quote needs. The same works from Python: ```python from costql import PricingPack pack = PricingPack.load("packs/tmdb_t3.json") quote = pack.quote('{ movie(id:"27205"){ cast(limit:8){ person{ name } } } }') quote["price"] # 50.5384 (safe max, in cost-units) ``` …and from JavaScript (`npm install costql`): ```ts import { PricingPack } from "costql"; const pack = await PricingPack.load("packs/tmdb_t3.json"); // or fromObject(await fetch(...).json()) pack.quote('{ movie(id:"27205"){ title } }').price; ``` The JS package is conformance-tested against the Python engine on every CI run: same pack, same query, same result. See [the JS package](js.md). ## 2. Build your first pack against a real API The Rick & Morty public API needs no keys, so you can do this right now: ```bash pip install 'costql[build]' costql build --adapter examples/adapters/rickmorty.py:rickmorty_config --out rickmorty.json costql quote --pack rickmorty.json '{ character(id:"1"){ name episode{ name } } }' ``` `costql build` introspects the endpoint, measures a set of clean calibration queries against it (this takes a couple of minutes: you calibrate by measuring), fits the cost model, and writes the pack. From then on, quoting is offline. Because the Rick & Morty API is a black box we can't instrument, the pack is **T1**: wall-clock currency, total-only quotes — and for this API, the fit. On its held-out queries T1 measured ~96% accuracy ([case study](results/rickmorty.md)). The instrumented tiers (T2/T3) see per-resolver and shared work and need one server-side change; whether your API's shape calls for them is in [tier fidelity](tiers.md). ## 3. Point it at your own API Two ways in. The fast one: hand the job to a coding agent. [Agent-assisted onboarding](agents.md) gives it one skill to follow (`skills/costql-adapter`) and a prompt that works; the agent probes the endpoint, harvests real IDs, builds, and validates the pack for you. To write it yourself, an adapter is ~90 lines (where the API is, what real IDs to query with, and a set of curated calibration queries): ```bash cp examples/adapters/rickmorty.py my_api.py # the minimal T1 template # edit: endpoint, ids, arg resolution, calibration shapes costql build --adapter my_api.py:rickmorty_config --out my_api.json ``` The [adapter guide](adapters.md) walks through every field. Sanity-check the result with `costql validate --pack my_api.json` and a few spot quotes. ## 4. Ship the pack The pack is a plain file. Vendor it into the app that needs to budget queries; load it with either language's `PricingPack`; call `quote()` before running a query. Every result follows the [frozen output contract](contract.md): `price` is always present, always a number, always a safe max; cost-units only, never dollars (converting to money is your app's business). Cyclic queries (a type re-entering itself through a list edge) are priced as a structural ceiling and flagged `confidence: low`, never silently billed. See [limitations](limitations.md) for the full honest list. --- description: "What quote() accepts and what the price means: fragments, aliases, variables, and directives are all parsed, and wherever the price can't be exact it errs high." --- # Quoting queries `PricingPack.quote()` takes the query your client actually sends. Nothing needs rewriting before quoting: the parser covers the executable query surface — fields and arguments, aliases, named and inline fragments, variables, and directives. ```python from costql import PricingPack pack = PricingPack.demo("tmdb_t3") pack.quote('{ movie(id:"27205"){ title } }') # variables travel alongside the query, like in any GraphQL request pack.quote( 'query($n: Int!){ movie(id:"27205"){ cast(limit:$n){ person{ name } } } }', {"n": 4}) ``` Same call in JS (see [the JS package](js.md)), and from the CLI: costql quote --demo tmdb_t3 --variables '{"n": 4}' 'query($n: Int!){ movie(id:"27205"){ cast(limit:$n){ person{ name } } } }' Every result is a [contract v1.0](contract.md) quote. One rule governs everything below: **where the price can't be exact, it errs high and says so** — the ceiling stays a ceiling. ## What each construct means for the price - **Aliases cost nothing.** An alias renames a response key; the server does the same work. The aliased field is priced under its schema name. The same field requested under *two* aliases is priced twice — that *is* extra work. - **Fragments cost nothing.** A fragment is a reusable spelling of the same selections, so a query written with fragments prices **exactly** like its hand-flattened equivalent (this equality is pinned by tests in both engines). Unknown fragment names and fragment cycles raise instead of mispricing silently. - **Polymorphic branches price as an upper bound.** Before a query runs, nobody knows which `... on Type` branch each object resolves to, so the price walks every branch. At most one fires per object; the quote carries a caveat naming the branched paths. See [limitations](limitations.md#polymorphic-branches-price-as-an-upper-bound). - **Variables** take their values from the `variables` argument or the declared default. A variable with neither loses its argument, so the field prices at the ceiling's worst-case bound — possibly higher than needed, never an under-price. See [limitations](limitations.md#a-missing-variable-value-prices-at-the-worst-case). - **Directives are priced as included.** `@skip` and `@include` can only remove work at runtime, so ignoring them never under-prices. ## Two notes on strictness - The tokenizer is lenient: it accepts the common GraphQL query surface rather than enforcing the full spec grammar. - A document must contain exactly one operation (plus any number of fragment definitions); multiple operations raise. --- description: "A batch-heavy database backend where entity sharing is heavy: the API shape that needs the tier that watches sharing (T3). Measured against a real SQLite store, no fabricated numbers." --- # Case study: a batch-heavy database backend On the [TMDB demo](tmdb.md), per-resolver timing (T2) and the sharing trace (T3) priced queries identically — TMDB shares entities only lightly, so there was almost nothing for the sharing trace to watch. To find out what happens on an API whose shape is the opposite, we pointed costQL at a very different backend: a real **Northwind** store database (products, orders, customers, SQLite), deliberately shaped so a single query hammers the same tiny set of entities over and over. The finding: **when sharing is light the two fidelities see the same thing; when sharing is heavy, only the tier that watches the sharing can price the queries.** Which tier an API needs is a property of its schema. Everything below is measured against the real database: real SQL, real rows, no fabricated numbers, zero paid calls. ## What we tested it on Northwind funnels a lot onto a little: **only 8 product categories and 77 products**, but **609,000 order-lines**. So a query like "for these 40 orders, each line-item's product's category" asks for a category **hundreds of times** while there are only 8 of them. A store database that batches its reads (as this one does, and as most real ones do) serves all those repeats from a handful of actual reads. That repetition is the "sharing," and it's the whole point. We priced a set of held-out queries the engine had never seen ([methodology](../evaluation.md)), split into a predictable ("billable") band and flagged-uncertain ones, and compared each tier's predicted cost against the real measured cost. ## How much sharing actually happened Across the predictable held-out queries, the requests genuinely piled onto a few entities and the database coalesced them: | measured across the billable held-out set | value | |---|---| | entity reads the queries **asked for** | **963** | | distinct rows actually **fetched** | 405 | | real **SQL queries** run (after batching) | **25** | | reads **saved** by coalescing | **558** | | coalescing factor (asked ÷ SQL queries) | **38.5×** | A single hub query asked for a category **107 times and the database read it once** (8 distinct categories, 99 repeats served from cache). This is heavy sharing, not a token amount, so the tier comparison is a fair test of the claim. ## The result: tier fit is sharing-dependent On the predictable, billable queries, mean error vs. real measured cost, first with the naive sharing rule that simply folds every shared read to "counted once": | | T2 (sharing inferred) | T3 (sharing observed), flat fold | mismatch | |---|---:|---:|---:| | **light-sharing queries** | **6%** | **6%** | **~0%** | | **heavy-sharing queries** | **315%** | **75%** | **+239%** | | all predictable (mixed) | ~160% | ~41% | ~+120% | - **When sharing is light, the two fidelities tie**: with nothing to coalesce, inferring the sharing and observing it see the same work. This reproduces the TMDB result on a completely different, database-backed schema. - **When sharing is heavy, only the tier that watches can price it.** T2 never sees the sharing happen, so it charges for *every* repeated request and over-prices by ~3× — not a defect of T2, but the measured cost of pointing a sharing-blind fidelity at a sharing-heavy schema. T3, which *observes* the coalescing, is far closer. **The mismatch widens with sharing.** ## Why "counted once" isn't enough for a database, and the batch curve that fixes it Even with the mismatch established, the flat fold left T3 imperfect, and in the **unsafe** direction: on the heaviest queries it **under-priced** (predicting ~0.04 vs a real ~0.33). The reason is specific. On TMDB, "sharing" only ever meant "the same single item asked for twice," so counting it once was exactly right. A store database instead reads *many different* rows in **one** batched SQL query, and that one query costs more the more rows it pulls. So costQL prices each shared loader with a **learned batch-size curve**: from the calibration measurements it fits each read's cost as a function of how many rows the batch pulls, and prices a batch at that curve. A database's loaders come out on a **rising** curve; a network API's come out **flat**: learned from data, never assumed (nothing hard-codes "database vs. network"). The four heaviest hub-fanning queries, measured: | query | real cost | T3, flat fold | T3, size-aware curve | |---|---:|---:|---:| | customer → orders → lines → products | 2.72 | 1.50 (−45%) | 1.66 (−39%) | | orders → lines → product → category | 0.32 | 0.03 (**−89%**) | 0.31 (−5%) | | orders → lines → product → supplier | 0.28 | 0.04 (**−86%**) | 0.29 (−4%) | | orders → lines → product → cat+supplier | 0.27 | 0.03 (**−87%**) | 0.27 (−2%) | The pagination-bounded batches went from **~88% under-priced to within ~5%**, and the pack's **ceiling is genuinely safe** on them (it sits above the real cost, where the flat fold sat ~10× below). Re-measuring the whole predictable band: | | T2 (sharing inferred) | T3, flat fold | T3, size-aware curve | |---|---:|---:|---:| | light-sharing queries | 11% | 13% | **10%** | | heavy-sharing queries | 346% | 77% | **12%** | | all predictable | 178% | 45% | **11%** | (These re-measured T2 figures differ slightly from the first table's run: live measurement, two separate runs. The shape is identical.) Note what the fix did *not* do: it did not shrink the mismatch. A fidelity that never watches the sharing genuinely cannot price coalesced reads; that is irreducible, and it is why this API shape needs T3. Fixing the fold made T3 accurate, which made the measured mismatch **wider** (+269% → +334% on the heavy queries): the flat rule had been *understating* what watching the sharing is worth here, by crippling T3 itself. ## The honest residue One held-out query still misses by ~39% on its typical estimate: "for this customer, all their orders and line-items." Its cost depends on **how many orders that specific customer has**, knowable only by running the query, not from its shape. costQL handles this the same way it handles cyclic queries: the confidence classifier detects the pattern (two or more un-paginated list edges compounding on one path), returns **low confidence** with a "declare sizes or run it" caveat, and the ceiling stays safe: **2.65 vs a real 1.95–2.40 across every customer**, including the 210-order heaviest one (the 77-product / 8-category hubs bound the batch), so there was never an under-billing risk. Queries whose batch size is fixed by the query itself (pagination, or a small hub table like the 8 categories) are priced accurately and stay high-confidence. See [Honest limitations](../limitations.md). ## No regression on the network API Re-measured on TMDB: every network-loader curve fits **flat** (a batched call ≈ a single call there), so the size-aware step adds nothing and T3 is unchanged. The T2→T3 gap stays ~0 (−0.3%), and packs still pass the frozen contract with 0 violations. The batch curve kicks in exactly where it should (a real database that batches many rows) and is inert where it shouldn't matter (a network passthrough). ## And costQL generalized, again Onboarding this third, non-movie, database-backed schema took only a ~90-line adapter ([`examples/adapters/northwind.py`](../../examples/adapters/northwind.py)) plus the demo server itself; not a line of the shared pricing engine changed. On this schema the engine built a working cost model from a small calibration panel, priced unseen queries, automatically flagged the unpredictable (cyclic) ones as low-confidence, saw and reported the 38.5× coalescing through the same observation path it used on TMDB, and produced **static, self-contained pricing packs at all three tiers** ([`packs/northwind_t1.json`](../../packs/northwind_t1.json), [`packs/northwind_t2.json`](../../packs/northwind_t2.json), [`packs/northwind_t3.json`](../../packs/northwind_t3.json)), each passing the [frozen output contract](../contract.md) with **zero violations**, and each quoting queries **with the server switched off**. ## Bottom line 1. **Tier fit is a property of the schema.** When a schema shares entities lightly (TMDB, and Northwind's light queries), T2's sight already covers everything that happens. When it shares heavily (Northwind's hub queries), only the tier that watches the sharing can price the work. This is a measured number, not an assertion. 2. **Batched reads are priced by size, safely.** A batch of *N* distinct rows is priced on a learned size→cost curve, closing the under-pricing where the batch size is knowable and restoring the ceiling guarantee on database backends. 3. **The engine generalizes.** A third real API, a different kind of backend, one small adapter, contract-valid offline packs at all three tiers. ## Reproducing it The demo server lives at [`examples/demos/northwind`](../../examples/demos/northwind) (it needs a one-command 24 MB reference-database download to run; see its README); building against it with the adapter above regenerates the packs. Quoting the committed packs requires nothing: ```bash costql quote --pack packs/northwind_t3.json \ '{ order(id:"15000"){ details(first:15){ product{ category{ name } } } } }' ``` --- description: "costQL priced a live public API it does not own with a 93-line adapter, zero engine changes, and ~96% accuracy at T1." --- # Case study: pricing a stranger's API (Rick & Morty, T1) Does costQL work on an API it has never seen, that we don't own and can't change? This experiment pointed it at the public **Rick & Morty API** (`rickandmortyapi.com/graphql`): no new server, no fake data, no special access, just the real, live, public endpoint anyone on the internet can hit. The result: a **93-line adapter**, **zero engine changes**, **~96% accuracy** on held-out queries at T1, with a safe max that never under-charged, and one offline pack in the standard contract format. ## What it took to onboard: one small file To teach costQL about a brand-new API, we wrote **one file**: [`examples/adapters/rickmorty.py`](../../examples/adapters/rickmorty.py), **93 lines** (and about half of that is just the list of real example IDs and the endpoint address; the only actual logic is a ~15-line function that says "this argument is an ID, this one is a page number"). **Nothing else changed.** The engine itself (the part that does the introspecting, measuring, modelling and pricing) was not touched at all. That is the whole point: adopting a new API is a small, self-contained plug-in, not a rebuild. costQL read the Rick & Morty schema live, learned its shape (characters, episodes, locations and how they connect), and started pricing, with no schema file written by hand. ## Did it actually price accurately? Yes. costQL measured a set of real queries against the live API to learn its costs, then **graded itself** on a *different, held-out* set of queries it had not calibrated on (different characters, episodes and locations: a genuine "unseen" test; see [the evaluation methodology](../evaluation.md)). - On the **predictable** queries (the ones a customer would actually want a price for), costQL's quote was **96% accurate on average**, and its safe "you will never pay more than this" ceiling was **never once too low** (5 out of 5). - Every query got a price. costQL never refused, never crashed, never guessed at data it didn't have. (For context, the number here is small because a public API like this is dominated by a steady network round-trip, which is exactly the cost a black-box, outside observer feels, and exactly what the T1 fidelity is meant to capture honestly. See [One currency, three fidelities](../tiers.md).) ## Did it know what it *couldn't* predict? Yes. Rick & Morty's data has a loop in it: a character points to its episodes, and each episode points back to its characters. Asking for "a character's episodes, and all the characters in each of those" balloons in a way that only *running* it reveals. costQL **automatically flagged every one of these loop-shaped queries as low-confidence** (the headline character↔episode loop came back "low", flagged as 100% inside the loop), while still handing back a safe upper-bound price and a plain note: *"this is a worst-case estimate; run it for the exact cost."* It priced what it could stand behind and was honest about what it couldn't. It never made up a number to look confident. ## Is it shippable? Yes, as one portable file. The output is a single self-contained **pricing pack** (a 66 KB file, committed at [`packs/rickmorty_t1.json`](../../packs/rickmorty_t1.json)) that an app can carry around and use to price queries **completely offline**: no server, no network call, no dependency on costQL being "up." We confirmed a real app-side quote runs straight from that file with nothing else running. And every price it produces comes out in costQL's **frozen, stable format** (verified: zero contract violations against [the v1.0 output contract](../contract.md)), so an app that already reads TMDB prices reads Rick & Morty prices the exact same way. ## Bottom line costQL is **not** a one-API trick. Pointed at a second, unrelated, live API it had never seen, it: 1. figured the API out by itself (a 93-line adapter, zero engine changes), 2. priced unseen queries to ~96% accuracy with a safe max that never under-charged, 3. knew which queries it couldn't safely predict and said so, and 4. shipped the whole thing as one offline file in its standard, stable format. All with **zero paid calls** and **zero fabricated data**. ## Try it yourself This is the "try it right now" API (public, no keys, no demo server to run): ```bash # quote against the committed pack, fully offline costql quote --pack packs/rickmorty_t1.json '{ character(id:"1"){ name } }' # or rebuild the pack from scratch against the live public endpoint costql build --adapter examples/adapters/rickmorty.py:rickmorty_config --out rickmorty.json ``` --- description: "Three-tier accuracy on the TMDB demo. On this lightly-sharing API there is almost no shared work to watch, so per-resolver timing (T2) and the sharing trace (T3) price it the same." --- # Case study: three-tier accuracy on the TMDB demo Measured against the **real** TMDB demo API (live data, work-ms currency, zero Anthropic calls), this experiment answers a standing question head-on: **does this API's shape need the sharing trace (T3), or does per-resolver timing (T2) already see everything that happens?** On this lightly-sharing passthrough API the two fidelities tie — there is almost no shared work for T3 to watch. See the [Northwind case study](northwind.md) for an API shape where there is. ## How it was measured - **Robust held-out panel, disjoint from calibration by entity** (calibration uses Inception/DiCaprio/Action + Fight Club/Pitt/Drama; held-out uses Interstellar/Cruise/Comedy/"star"). Held-out queries are *never* seen at build time: the numbers grade prediction of unseen data, not memorisation. (Full methodology: [evaluation](../evaluation.md).) - **Split by confidence band.** 9 predictable (distinct-type fanout) high-confidence queries (the billable band) and 4 cyclic (recommendations-of-recommendations, genre-hub) low-confidence queries that get *flagged*, not billed. - **Priced three ways against the real measured cost:** - **T1** (black-box): only whole-query wall-clock, regressed onto resolvers. - **T2** (per-resolver work): sharing *inferred* (no dedup credit). - **T3** (work + sharing trace): sharing *observed* (dedup folded). - **Average-size pricing.** A request that doesn't declare its size is priced at the *typical* observed size, not the worst case, so the comparison is not polluted by worst-case over-charging. Where the caller declares a size (`limit: N`), it is priced exactly. ## Result: predictable (high-confidence) queries, n = 9 | tier | what it needs from the API | mean error vs real cost | |---|---|---:| | **T1** black-box | nothing (wall-clock only) | **17%** | | **T2** per-resolver work | the cost-trace extension | **11%** | | **T3** work + sharing trace | the cost-trace extension + loader keys | **11%** | **T2 → T3 difference: ~0 (−0.8%, within measurement noise).** **On this API, T2's sight already covers everything that happens to quotable queries.** With almost no shared work in the schema, observing sharing exactly (T3) has nothing extra to see before execution. The sharing trace matters only on the deep/repeated-load queries that *no* tier can quote pre-execution anyway, and those get an exact price the moment they actually run. One important scope note: TMDB shares entities only *lightly*. Under heavy entity sharing, only the tier that watches the sharing can price the work. That is the [Northwind result](northwind.md), and it is why the tier an API needs is a property of its schema, not a universal claim. ## On result-size effects Average-size pricing is the basis for these numbers. On this passthrough API the isolated worst-case-vs-average size effect is **~0%**: a passthrough returns list items inside the parent's single fetch, so the marginal work of one more item is essentially zero. Size uncertainty bites hardest on APIs that do *real* per-item work (scan-before-paginate), which is exactly the case the work-ms currency is designed to catch. Larger apparent over-charges in early measurement rounds traced not to size but to fitting the model on cyclic-recursion queries, whose combinatorial work totals don't fit a linear model; calibrating on clean, predictable queries (and flagging the cyclic ones instead of fitting them) removes the artifact entirely. ## Cyclic (low-confidence) queries, n = 4 Priced structurally and **flagged** (mean error ~92%: recommendations-of- recommendations fan out combinatorially, and the real backend de-duplicates by an amount only running the query reveals). costQL does not fabricate a dedup guess; it prices structurally, tags the query low-confidence, and says "run it for the exact cost." This is the honest handling, not a modelling failure. See [Honest limitations](../limitations.md). ## Reproducing it The committed pack is [`packs/tmdb_t3.json`](../../packs/tmdb_t3.json). The demo server ([`examples/demos/tmdb`](../../examples/demos/tmdb)) and its adapter ([`examples/adapters/tmdb.py`](../../examples/adapters/tmdb.py)) reproduce the setup: the server emits all three fidelities from one instrumentation (`COSTQL_TIER=T1|T2|T3` gates how much of the cost trace it publishes), and `costql build` against it at each tier regenerates the comparison. Note the demo requires free TMDB API keys; quoting the committed pack requires nothing. --- description: "costQL prices in one currency, work-ms, across three tiers of fidelity. T1 works on any API black-box; T2 and T3 see parallel and shared work through a server trace. The right tier is a fact about your API." --- # One currency, three fidelities costQL prices everything in one currency, **work-ms** (the summed duration of the real work a query causes), and offers three *tiers* that are fidelities of one engine, not three different products or units. A tier is simply how sharply the API's instrumentation lets costQL see and factor that work: each tier removes a specific *blur* between what is observable and the true work. The tier your API affords is the correct one — no tier is better than another, and every tier produces the same billable result shape under the same [output contract](contract.md). ## The currency: work-ms, not elapsed time **Work-ms = the summed durations of the real work a query causes** (downstream call durations plus local compute), not the wall-clock time the request took. The distinction matters: a request that fires ten parallel 50 ms calls *elapses* ~50 ms but *costs* ~500 ms of work. Elapsed time is what the caller waited; work-ms is what the server spent. costQL charges for the latter. One currency at every tier. T1, which cannot see inside the request, falls back to wall-clock as a low-fidelity **proxy** for work-ms (its results carry `currency: wall_time_ms` so the proxy is never silent). And always cost-units, never dollars: converting cost-units into money is the consuming app's job. ## The three fidelities | Tier | What it sees | Blur it removes | |---|---|---| | **T1** | one stopwatch on the whole request (wall-clock); per-resolver costs recovered by regression across many queries | none (the starting fidelity) | | **T2** | each resolver's invocations + each downstream call's duration → summed work-ms | **parallelism**: no longer fooled by concurrent calls; sharing still *inferred* | | **T3** | the above **plus** each call's key + cache status | **sharing**: dedup/coalescing observed exactly, batch sizes priced on learned curves, outside hosts named | - **T1 (black box).** Sees only whole-query elapsed time. Work done in parallel or in batches hides inside elapsed time, so T1 tends to **under-count**: e.g. a genre-hub query whose measured T3 work was 156 ms elapsed as only 87 ms at T1. - **T2 (per-resolver work).** Sums each resolver's real durations, so parallelism no longer hides work. But a call reused by several fields is *guessed*, not observed: shared work can be double-counted. - **T3 (work + sharing trace).** Observes exactly which calls coalesced or hit cache; shared calls are counted once and each shared loader is priced by a **learned batch-size curve** (a 300-key batch costs more than a 3-key one; a database loader's curve rises, a network loader's stays flat: learned, never assumed). Outside hosts are named, with the call count; costQL doesn't price the outside call (it can't know what that host charges), so the consuming app does. What each tier's *result* carries (breakdown, sharing, external calls) is specified and validator-enforced in [the output contract](contract.md). ## What each tier requires, honestly **T1 works against any GraphQL API, today, with no cooperation from the server.** The [Rick & Morty case study](results/rickmorty.md) priced a live public API that we don't own and can't change to **~96% accuracy** with a **93-line adapter and zero server changes**. **T2 and T3 require seller-side instrumentation**: the API server must emit costQL's cost-trace extension (per-resolver timings for T2; plus loader keys and cache status for T3). The demo packs in this repo are T3 *because we instrumented the demo servers ourselves*. That is the honest reason they can show observed sharing. **Your first pack will be T1, and that is the designed starting point.** It already gives you the full contract-shaped result with a safe max; adding instrumentation later moves the same pack pipeline to the fidelity your server now emits, without changing how your app reads the price. ## Which tier fits your API? Not a ranking — a fact about your API's shape. Ask, in order: 1. **Can your server emit costQL's cost-trace at all?** If you can't change the server, **T1 is the fit**: the only tier that requires nothing from anyone, and the honest fidelity for a black box (the [Rick & Morty case study](results/rickmorty.md) is exactly this). 2. **Does your server batch, coalesce, or cache reads — or does your schema funnel many lookups onto a few hub entities?** Then your API needs the tier that watches sharing: **T3**. A tier that never sees the sharing happen cannot price those queries, however well it does everything else; that mismatch is measured in the [Northwind case study](results/northwind.md). 3. **Do your resolvers fire downstream work in parallel inside one request?** Then your API needs per-resolver timing: **T2**. With no sharing to observe, there is nothing extra for T3 to see — on the lightly-sharing [TMDB demo](results/tmdb.md), T2 and T3 priced the billable band identically. 4. **Neither?** Serial, unshared work is exactly what one stopwatch measures well: **T1 fits**, even though you could instrument. The remaining reason to instrument is detail in the quote itself — a per-resolver `breakdown` arrives at T2, observed `sharing` and named `external_calls` at T3 (the [contract's tier table](contract.md) lists exactly what appears when). Whatever the destination, your first pack is still T1. That is a sequence, not a rank. Prefer ticking boxes? The same questions run interactively on [the landing page](https://costql.com/#tiers). ## One more axis: confidence (orthogonal to tier) Tier is about the *API's* observability; **confidence** is about the *query's* predictability. At every tier, a query whose result size is runtime-unknowable (cyclic recursion, or compounding undeclared list sizes) is flagged `confidence: low` and priced as a structural ceiling rather than silently billed. See [Honest limitations](limitations.md).