diff --git a/CHANGELOG.md b/CHANGELOG.md index b013c8e034..db4ce2298a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +**Breaking: `dbt_cost_estimate` is BigQuery only, so Snowflake and Databricks are no longer gated by `maxScanBytes`.** The tool used to give a scan figure on Snowflake and Databricks from the warehouse planner's EXPLAIN (bytes assigned there count partitions before runtime pruning and usually overstate what runs). It now answers `supported: false` on every warehouse but BigQuery and compiles nothing, so the Claude plugin's scan check (`maxScanBytes`, 10 GiB by default) no longer holds a `dbt run`, `build` or `show` on those two warehouses; the command runs with a line saying why. On BigQuery the scan figure is unchanged, and `history: true` now also reads what a model's earlier runs cost (billed `INFORMATION_SCHEMA.JOBS` queries; see the dbt tools page). + ## [0.12.12] - 2026-11-20 **dbt Power User features now work from the command line, and an owner can send a workspace request back for changes.** Nine new tools estimate what a dbt model or query would scan before it runs (BigQuery dry run, Snowflake and Databricks from the planner's EXPLAIN), read the last dbt run, check a model's docs coverage, report DataPilot project health, time a model's CTEs, draw its SQL graph, map raw SQL tables to `ref()` and `source()`, read the defer setting, and reply to comments on shared dbt docs. Call them with `altimate-code tool run` or from another coding agent through `mcp serve`. The new `altimate-code integrations` command connects GitHub, Jira and Linear with your own credentials. On workspaces with review on, a request can be sent back with a comment, then changed and sent again. The TUI says what changed in the workspace's skills and knowledge since your last session. Also in this release: stricter SQL checks in the tool CLI and MCP server, the agent keeps your changes instead of reverting them, `altimate review` reviews only the PR's own changes, and Snowflake key-pair login reads every private-key format. diff --git a/docs/docs/configure/config.md b/docs/docs/configure/config.md index 737d0e03ef..d3e5f07711 100644 --- a/docs/docs/configure/config.md +++ b/docs/docs/configure/config.md @@ -63,6 +63,7 @@ Configuration is loaded from multiple sources, with later sources overriding ear | `plugin` | `string[]` | Plugin specifiers | | `instructions` | `string[]` | Glob patterns for instruction files | | `telemetry` | `object` | Telemetry settings (see [Telemetry](../reference/telemetry.md)) | +| `cost` | `object` | Rates `dbt_cost_estimate` prices BigQuery usage at: `bigqueryUsdPerTib`, `bigquerySlotHourUsd` (see [dbt tools](../data-engineering/tools/dbt-tools.md#dbt_cost_estimate)) | | `compaction` | `object` | Context compaction settings (see [Context Management](context-management.md)) | | `experimental` | `object` | Experimental feature flags | diff --git a/docs/docs/data-engineering/guides/using-with-claude-code.md b/docs/docs/data-engineering/guides/using-with-claude-code.md index 9773be5183..4189b72c5f 100644 --- a/docs/docs/data-engineering/guides/using-with-claude-code.md +++ b/docs/docs/data-engineering/guides/using-with-claude-code.md @@ -145,7 +145,7 @@ The helpers read `manifest.json` and `run_results.json` from the `target-path` t The rest of the plugin's panes and commands call Altimate Code's tools through `altimate tool run`, and make no model-provider call of their own. The dbt Power User ones need altimate-code 0.12.12 or later, the release with the [dbt Power User tools](../tools/dbt-tools.md#dbt-power-user-tools); with an older one most say so where their answer would be, while `/runs` records nothing and `/defer` adds no flags. Cost, health, the SQL graph and CTE timing start the project's dbt adapter, so the plugin runs them with `altimate tool run --allow-write` itself, without asking. The commands are listed by the bare names the plugin registers. - **Lineage pane** (`/lineage [.column]`). The dbt model Claude reads or edits, with every model upstream and downstream, its exposures (dashboards and other consumers), each output column's sources and, for a picked column, the downstream models and dashboards that read it, from `dbt_lineage` and `impact_analysis` on `target/manifest.json`. When a task changed a model, a band above the prompt sums up each changed column's downstream reach, and **Open report** or `/lineage-report` builds an offline HTML report of it. Claude Code opens the pane on its own only in a terminal at least 144 columns wide; `/lineage` opens it at any width. -- **Scan cost check** (`/scan-cost `, `/allow-scan`). Before a `dbt run`, `build` or `show` that Claude runs names one model or an inline query, `dbt_cost_estimate` says what it would scan: a BigQuery dry run, or the planner's `EXPLAIN` on Snowflake and Databricks. Over the plugin's `maxScanBytes` setting (10 GiB by default; 0 never holds) the command is refused with the estimate until you run `/allow-scan`, which lets that same command through once. A query with no estimate runs, with a line saying why, and other warehouses are never held. On Databricks the `EXPLAIN` can start a stopped SQL warehouse, which is billed while it runs. +- **Scan cost check** (`/scan-cost `, `/allow-scan`). Before a `dbt run`, `build` or `show` that Claude runs names one model or an inline query, `dbt_cost_estimate` says what it would scan from a BigQuery dry run. The scan check uses the dry run only and sends no `INFORMATION_SCHEMA` query. A model's earlier run cost is read only when `dbt_cost_estimate` is asked with `history: true`, and each such call runs up to eight billed `INFORMATION_SCHEMA.JOBS` queries (three normally: capacity, history and boundary; one more for the earlier jobs of labelled invocations, which reads back to the 180 days JOBS keeps and can scan far more query text than the history; one more when a script matched, for its children; up to eight if your role cannot list every user's jobs, since the capacity, history and children reads each run again on `JOBS_BY_USER`, which scans only your own jobs, so service-account and other users' runs are left out and the answer says so first; the project-wide read needs `bigquery.jobs.create` and `bigquery.jobs.listAll`, the fallback `bigquery.jobs.create` and `bigquery.jobs.list`): a capacity check (7 days of jobs), the history (30 days, scanning the query text of every query job in the project, so the bytes grow with the project's activity, not the model, and its 500-row cap does not cap the bytes), the boundary (one more query, which also finds the model's jobs that are queued, running, or have no end time) and, when a script matched, the script's children. Each is billed on demand (at least 10 MiB) or uses reservation slots, and `INFORMATION_SCHEMA` is never cached. It works on BigQuery only. Over the plugin's `maxScanBytes` setting (10 GiB by default; 0 never holds) the command is refused with the estimate until you run `/allow-scan`, which lets that same command through once. A query with no estimate runs, with a line saying why, and other warehouses, Snowflake and Databricks included, are never held. - **Project health** (`/health`). At session start `dbt_health` (DataPilot) records the project's existing insights; after a turn in which Claude changed model files, the check runs again and the new issues on those models show in a band. With `healthBlocksPush` on, `git push` is refused while the check of your latest changes is not in or finds new issues. `healthConfigPath` names a DataPilot config file by a path inside the dbt project. A check can take minutes, and it needs the `altimate-datapilot-cli` package in the project's Python. - **Team comments** (`/comments`). The open comment threads on dbt docs your team shared through Altimate, fetched at session start and, in an interactive session, every `commentsPollSeconds` (15 minutes by default). When Claude reads or edits a model that has open threads, they are added to its context as quoted data (`commentsInContext`), so it sees the review before it changes the model. Reply and resolve are buttons you press in the pane; Claude has no way to post. Needs an Altimate sign-in. - **dbt runs** (`/runs`). The dbt commands Claude ran that wrote `run_results.json`, with their per-node results from `dbt_run_results`, up to 50 runs per project, kept on this machine across sessions. From the pane a run can be opened, run again, or its failures run again through the prompt. diff --git a/docs/docs/data-engineering/tools/dbt-tools.md b/docs/docs/data-engineering/tools/dbt-tools.md index 62f9726882..12fc8e8c53 100644 --- a/docs/docs/data-engineering/tools/dbt-tools.md +++ b/docs/docs/data-engineering/tools/dbt-tools.md @@ -77,6 +77,98 @@ Source Freshness: --- +## dbt_cost_estimate + +What a BigQuery dbt model's compiled query would scan before it runs and, when asked with `history: true`, what the model cost the last times it ran. Pass `model` (a model name, as dbt's `ref()` takes it) or `sql`. It starts the dbt adapter, so it needs write permission: pass `--allow-write` on `tool run` or the MCP server, and leave plan mode, or a read-only call is refused. + +BigQuery only: on any other warehouse (Snowflake, Databricks, Redshift, Postgres, DuckDB and the rest) the tool answers `supported: false` with the adapter's name and the text "cost estimates are only available on BigQuery", and compiles nothing. + +### Default call + +Without `history: true` the tool compiles and dry runs only, sends no `INFORMATION_SCHEMA` query and returns the scan figure with no `cost`. The figure comes from a BigQuery dry run (`bytes`, `maxBytes`, `lowerBound`). The byte count is parsed from the dry run's display, which has one decimal ("4.2 TiB"), so it can be off by up to half a tenth of its unit; `maxBytes` gives the upper end. A script's dry run can skip statements or omit work that happens at run time, so `lowerBound` marks it, and a zero estimate is marked too. + +```bash +altimate-code tool run dbt_cost_estimate --allow-write --args '{"model":"fct_revenue"}' +``` + +### With `history: true` + +Pass `history: true` when you ask what a model costs or what its runs cost. The answer then has a `cost` block, first in the text. It reports the last run, the typical (median) run and the highest, in money and in BigQuery's own unit (bytes billed or slot-hours), from the model's runs in the last 30 days, priced at a stated rate (`cost.rate`: `config` or `default`). That is reported usage at a rate, an estimate and not an invoice amount, and the tool never invents a cost when no history was read. A history that mixes on-demand and reservation runs has no single native unit, so `cost.native` is omitted. `cost.attribution` is `bytes_billed`, `slot_time` or `mixed`, and `cost.scope` is `project` or `user` (see below). + +- **Current target.** The jobs are split by target before they are grouped, so a run never mixes targets, and the figures are of the runs of the dbt target the adapter is using (`target.name`, matched with `"target_name"` in dbt's query comment). Runs of other targets (dev, CI) and runs whose comment names no target are not in the figures: they are listed in `cost.otherTargets` (`target`, `runs`, `typical`; the latter under "unknown target") and in one note. If the current target has no runs but others do, nothing is the headline cost and the answer says so. +- **Only your own jobs.** When the role cannot list every user's jobs (it lacks `bigquery.jobs.listAll`), the tool reads `JOBS_BY_USER`, which returns only the caller's own jobs. The first line of the answer then says "Only your own jobs were read (no bigquery.jobs.listAll): service-account and other users' runs are missing", and `cost.scope` is `user`. +- **Reservations.** A run in a reservation is priced by its slot time, which is attributed, not billed: the first line says "reservation runs are attributed slot time, not the bill". Autoscaled slots are billed in steps of 50, by default with a one-minute minimum (reservations with fluid scaling have none), and baseline slots are always charged, so slot time is an allocation, not the bill. The default 0.06 USD per slot-hour is the BigQuery Enterprise pay-as-you-go rate (Standard is 0.04, commitments are lower): set `cost.bigquerySlotHourUsd`. +- **When cost cannot be known**, `cost.unknownReason` says why (`basis` is `none` and the answer contains a "Cost unknown: " line, after the own-jobs notice when there is one; a dry-run price, when there is one, stays in `cost.selectOnly` and in its own line, "Pre-run scan estimate (not the model's run history)", and is never the headline): no runs in the window, a role without access (it needs `bigquery.jobs.create` and `bigquery.jobs.listAll` on the project, or `bigquery.jobs.create` and `bigquery.jobs.list` for its own jobs), a `sql` input (it has no history), a model name that matches several nodes, an ephemeral model (it never runs on its own; its SQL is inlined into the models that ref it), or a Python model (it runs on Dataproc and never appears in `INFORMATION_SCHEMA.JOBS`; no query is sent for it). Every no-runs message names the location read: a target with no `location` reads `region-us`, and the message says so. When the model's runs and the 7-day check disagree on reservation versus on-demand pricing, or the newest run differs from older ones, a note says so. +- **Runs left out** are counted with the cause: a non-cached job with no bytes billed (a cache hit is a known $0 run), a reservation job with no slot time, a script whose child jobs were not found, may be cut off at the query's limit, or whose start time could not be read. + +```bash +altimate-code tool run dbt_cost_estimate --allow-write --args '{"model":"fct_revenue","history":true}' +``` + +### How runs are counted + +The tool finds the model's jobs by dbt's query comment (`"node_id": ""`, matched as exact text), so every user and every dbt target that use the same execution project are found. The matched jobs are the top-level jobs that carry the comment, of any statement type (builds, hooks, SELECTs, DELETE and UPDATE; the tool's own reads are excluded by a marker), those that finished and those still queued or running, newest 500. When a query returns all 500, the answer says only the newest 500 were read. + +- **By invocation.** dbt-bigquery labels every job it runs with `dbt_invocation_id`, which the history and boundary reads select from `INFORMATION_SCHEMA.JOBS` (`labels`). Jobs with the same id are one run, however far apart they are, and two invocations by one user within a minute are two runs. +- **Without the label** (an older adapter, a job dbt did not run) jobs are grouped by user and time: the matched top-level jobs by one user form a run while each job starts within 60 seconds after the previous job of the run ended. That covers pre- and post-hooks, DELETE and UPDATE, and every batch of a microbatch model. Jobs are split by target first, so within one target, invocations by one user that overlap or follow within 60 seconds (for example two CI runs from one service account) are then one run; jobs whose comment names no target are grouped among themselves. +- **A run needs a build job** (create, insert, merge, script). A group of reads, such as `dbt show`, is not a run and is not priced. +- **Temporary relation.** A CREATE TABLE AS SELECT into dbt's temporary relation (a table ending in `__dbt_tmp`) pairs, for unlabelled jobs, with the MERGE, INSERT or script by the same user, in the same destination dataset, that starts within 10 minutes after it ends: each such CTAS takes the first qualifying build no other CTAS has taken, since dbt makes one temporary relation per build. +- **Scripts** are priced from their child jobs, each by its own pricing mode (bytes billed on demand, slot time in a reservation), never the script row beside them. The child jobs are read from the earliest matched script's creation onward, so they cannot slide out of the 30-day window while the scripts are read. +- **Runs still going.** A run with a job still queued or running, or whose last job ended within 60 seconds of the instant read, or within 10 minutes after a temporary-table CTAS that no final build has taken (whatever ran after it), is left out and counted in a note. +- **Boundary jobs and targets.** Boundary and still-going jobs carry their `target_name` like the history: a job can drop or hold a run of its own target only, and a job naming no target only a run naming none. +- **Runs that began before the period.** A second query (the boundary) reads the jobs before the period read (the oldest job returned, else the 30-day edge) that could belong to a run: for a run whose jobs carry an invocation id, an unread job with the same id (every finished job of the invocations read, as far back as `INFORMATION_SCHEMA.JOBS` keeps jobs, 180 days, since an invocation has no span limit, so a labelled run is complete exactly when all its jobs were read; the 96-hour-10-minute fallback of a full or unknown read is for unlabelled runs only) or a job still going with the same id; labelled and unlabelled jobs are never one run, so neither meets the other here; otherwise a job by the same user that ended at or after 60 seconds before the run's start, or a temporary-relation CTAS by the same user, into the dataset of a final build, that ended within 10 minutes before it. Such a run is dropped and the answer counts the runs dropped. Jobs still going (queued, running, or with no end time) are listed first, so finished jobs cannot crowd them out, and a run one of them could join is left out wherever it is. If the read is full, runs starting within 96 hours 10 minutes of the cutoff are also dropped, and every unlabelled run by a user with a job still going (a labelled run is judged by its own invocation: left out only when a job of the same id is still going, or when the invocation read is full). If the boundary read fails or times out, the tool cannot tell which runs are still going or were cut, so no run is priced: the history is unknown ("could not check for runs still in progress: ...") and the scan fields stay. +- **The 96 hours 10 minutes** is BigQuery's longest job span plus the longest join gap: a query waits in the queue 6 hours when interactive and 24 hours when batch by default, and the queue timeout can be set up to 48 hours; it then runs up to 6 hours per attempt with up to three attempts, but a CREATE MODEL statement (BigQuery ML) times out at 24 hours, or 48 hours for time series, AutoML and hyperparameter tuning, so at most 48 + 48 = 96 hours in flight, and a temporary-table CTAS joins its final job up to 10 minutes after it ends. A job that was queued and running longer than that, for example under a queue timeout raised in the project's settings, and has since finished, is not covered. A job still going is read from no further back than that span either. + +### What each number means + +- **History, on demand:** bytes billed per job (`total_bytes_billed`, the charged amount) per TiB at the on-demand rate. A BigQuery ML job (`CREATE_MODEL`, at the top level or among a script's children) that ran on demand is the exception: model training bills at its own price, not the query rate, so its cost is unknown and its run is left out, with a cause naming BigQuery ML. In a reservation its slot time is priced like any job's. A cached job bills nothing; a non-cached job with no bytes billed (BigQuery hides them for tables under a row access policy) is unknown and its run is left out. +- **History, reservation:** attributed slot time at the slot-hour rate (see Reservations above). When a model has both kinds of run, `cost.rate` is the newest run's and a note names the on-demand rate. +- **Pre-run scan price** (`cost.selectOnly.estimate`, on on-demand pricing only): the dry run's byte count, at least BigQuery's 10 MiB per-query minimum, times the on-demand rate. It is an estimate, not a bound, and the text says so: the bill can differ, because a cached or BI Engine result bills nothing, clustered tables often bill less after runtime pruning, and external sources and some queries are not fully counted. It covers the SELECT only; depending on its strategy, an incremental model can also write a temp table and read the target, which the history shows. +- **A zero estimate** is not priced: BigQuery also reports 0 bytes for row-level security, external (federated) tables and cached results, and the note says so. A script's dry run is not priced either. +- **Capacity pricing:** if the project is on capacity pricing the dry run is not priced, and neither is it when the pricing mode can't be read (the project's jobs, then your own, show no query job in 7 days or can't be listed). + +### Queries and their cost + +Each `history: true` call runs up to eight billed `INFORMATION_SCHEMA.JOBS` queries: three normally (capacity, history and boundary), one more to read the earlier jobs of labelled invocations (the invocation read), one more when a script matched (its children), so up to five, and up to eight when the role cannot list every user's jobs, since the capacity, history and children reads each run again on `JOBS_BY_USER`. + +| Query | Reads | +|---|---| +| Capacity check | 7 days of jobs, to tell on-demand from reservation pricing | +| History | 30 days: `strpos` on the query text scans the query text of every query job in the project, so the bytes grow with the project's activity, not the model, and the 500-row cap limits the rows returned, not the bytes billed | +| Boundary | one query: finished jobs from the 96 hours 10 minutes before the period read, plus the model's jobs still queued or running from no further back than that; it scans query text like the history, over that shorter span | +| Invocation jobs | only when runs carry an invocation label: the jobs of those invocations from before the cutoff, back to the 180 days JOBS keeps, in a read of their own with its own 500-row limit; if it is full, no labelled run is known to be complete and every labelled run is left out | +| Children | the child jobs of matched scripts, by parent id | + +Each is billed on demand (at least 10 MiB per query) or uses reservation slots, and `INFORMATION_SCHEMA` results are never cached, so you are charged each time. Leave `history` off for a routine pre-run check. The queries run through dbt's `run_query`, which cannot set `maximum_bytes_billed` per query: if the profile sets `maximum_bytes_billed`, the queries follow it. All queries read the same instant, taken once per call and written as a literal into the history, boundary and capacity queries (the children query starts at the earliest matched script's creation instead), so those queries describe one period. + +The pre-run scan runs first and completes before the history queries start (the dbt Python bridge serialises adapter calls). The history has its own 60 s deadline, which only stops the tool waiting: the warehouse may keep running a history query. The history never changes the scan figure. + +### Config + +Set your own rates in the config (see [Configuration](../../configure/config.md)): + +```json +{ + "cost": { + "bigqueryUsdPerTib": 6.25, + "bigquerySlotHourUsd": 0.06 + } +} +``` + +A rate you set replaces the default: `bigqueryUsdPerTib` prices on-demand jobs, `bigquerySlotHourUsd` prices jobs that ran in a reservation. Each should be a positive number of at most 1,000,000; the config accepts any number, and the tool ignores any other value and names the key in its notes, using the default rate instead. + +### Not covered + +- Warehouses other than BigQuery (no estimate is given). +- Continuous queries: dbt submits none, and every read (capacity, history, boundary, invocation and children) leaves out jobs that `INFORMATION_SCHEMA.JOBS` marks `continuous`; one that carried the model's query comment anyway would not be covered by the in-progress checks. +- Python models (they run on Dataproc, not as query jobs). +- Jobs that were in flight longer than 96 hours 10 minutes and have finished, and runs outside the 30-day window or beyond the newest 500 jobs. +- The reservation bill itself: slot time is attributed, not the invoice. +- Figures not yet compared with real billing: the tests use a mocked adapter, so compare dry-run bytes with billed bytes, and the history totals with your billing export, over a few dozen dbt runs before relying on them. + +--- + ## dbt_unit_test_gen Generate dbt unit tests (v1.8+) from a compiled manifest. Analyzes model SQL for testable logic (CASE/WHEN, JOINs, NULLs, window functions, division, incremental), generates type-correct mock inputs, and assembles complete YAML. @@ -150,7 +242,7 @@ Some of them start the project's dbt integration (the dbt adapter), which runs ` | Tool | What it returns | Parameters | What it runs on the warehouse | | --- | --- | --- | --- | -| `dbt_cost_estimate` | The bytes a model or a query would scan, without running it. | `model` or `sql` (may use Jinja), not both | BigQuery: a dry run. Snowflake: `EXPLAIN USING JSON`, bytes left after pruning: an upper bound when the plan can size every source it reads. When it can't (an external table, a stage, a secure view, or a scan sized at zero), the answer says the figure is not a cap. Databricks: `EXPLAIN COST`, the sizes of the tables it reads, which can start a stopped SQL warehouse (billed while it runs). A query that may hold a second statement, or that reads files on Databricks, is refused rather than planned. | +| `dbt_cost_estimate` | The bytes a BigQuery model or a query would scan, without running it; with `history: true`, also what the model cost its earlier runs. Any other warehouse answers `supported: false`. | `model` or `sql` (may use Jinja), not both; optional `history` (default false): `true` also reads what earlier runs cost | A BigQuery dry run for the scan; with `history: true`, billed `INFORMATION_SCHEMA.JOBS` queries. | | `dbt_health` | DataPilot project health insights per model, such as hard-coded references, missing tests or documentation, and naming and structure issues. | `config_path` (optional DataPilot config) | Nothing. It needs the `altimate-datapilot-cli` Python package in the project's Python. | | `dbt_cte_profile` | Without `cte` or `position`: the model's CTEs in source order, including `reads`, the positions of earlier CTEs each body names directly. These approximate dependencies let clients estimate own time by subtracting dependency times once, rather than subtracting the preceding sibling. Quoted-name case rules and backslash strings vary by warehouse; this dialect-independent scan can miss or overcount reads, as can aliases and Jinja-generated names. With one: that CTE's row count and its warehouse time in milliseconds (`queryMs`, without dbt's start-up; `timing` says how it was measured, and `wall` means neither measure was available, so the time includes dbt's start-up). | `model` (name, unique_id or `.sql` path), `cte`, `position` | Listing runs nothing and works read-only. Timing runs `SELECT COUNT(*)` over that CTE and the CTEs before it, so a model of N CTEs costs N queries. | | `dbt_sql_graph` | A model's CTEs, joins and filters as a graph, each relation tied to the dbt node it stands for. | `model` | Reads the column metadata of the model's parent relations. Runs no query on their data. | @@ -174,6 +266,7 @@ Some of them start the project's dbt integration (the dbt adapter), which runs ` ```bash altimate-code tool run dbt_run_results altimate-code tool run dbt_cost_estimate --allow-write --args '{"model":"fct_revenue"}' +altimate-code tool run dbt_cost_estimate --allow-write --args '{"model":"fct_revenue","history":true}' altimate-code tool run docs_share_comments --args '{"action":"list"}' ``` diff --git a/packages/core/src/v1/config/config.ts b/packages/core/src/v1/config/config.ts index b6fe79e97a..f022349594 100644 --- a/packages/core/src/v1/config/config.ts +++ b/packages/core/src/v1/config/config.ts @@ -100,6 +100,18 @@ export const Info = Schema.Struct({ }), ).annotate({ description: "Anonymous usage telemetry settings" }), // altimate_change end + // altimate_change start — rates dbt_cost_estimate prices BigQuery usage at + cost: Schema.optional( + Schema.Struct({ + bigqueryUsdPerTib: Schema.optional(Schema.NullOr(Schema.Number)).annotate({ + description: "BigQuery on-demand price in USD per TiB billed; a positive number, at most 1e6; other values, null included (a saved infinity becomes null), are ignored and named in the output (default 6.25)", + }), + bigquerySlotHourUsd: Schema.optional(Schema.NullOr(Schema.Number)).annotate({ + description: "BigQuery capacity price in USD per slot-hour, used for jobs that ran in a reservation; a positive number, at most 1e6; other values, null included (a saved infinity becomes null), are ignored and named in the output (default 0.06)", + }), + }), + ).annotate({ description: "Prices dbt_cost_estimate uses to turn BigQuery usage into money" }), + // altimate_change end mode: Schema.optional( Schema.StructWithRest( Schema.Struct({ build: Schema.optional(ConfigAgentV1.Info), plan: Schema.optional(ConfigAgentV1.Info) }), diff --git a/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts b/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts index 8195d9bc68..fa77de385e 100644 --- a/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts +++ b/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts @@ -1,6 +1,19 @@ import z from "zod" import { Tool } from "../../tool/tool" import { dbtAdapterFor } from "./dbt-adapter-access" +import { + bigqueryOnDemandRate, + cleanRates, + costHistoryInternals, + costText, + ignoredRateNotes, + loadHistory, + manifestPathFor, + MIN_BILLED_BYTES, + onDemandEstimate, + type CostConfig, + type History, +} from "./dbt-cost-history" /** * Every dbt integration but the Python bridge writes the SQL into a `{{ validate_sql('...') }}` Jinja @@ -14,12 +27,6 @@ export function forDryRun(sql: string, integration: unknown): string { /** The units dbt-bigquery's `format_bytes` writes, smallest first; each is 1024 times the one before. */ const UNITS = ["Bytes", "KiB", "MiB", "GiB", "TiB", "PiB"] as const -/** - * The byte count in a dry run's `bytes_processed`, which dbt-bigquery formats as text ("4.2 TiB", - * "512.0 Bytes"), and the most it can be. The text carries one decimal, so a figure past a byte is - * rounded: the true count is within half a tenth of its unit. Undefined for anything else, so a changed - * format is reported, never read as a count. - */ /** Whether the SQL is a script (more than one statement, or EXECUTE IMMEDIATE): a dry run only sees its first statements. */ export function isScript(sql: string): boolean { // One pass over comments and quoted text together: a quote inside a comment, or a comment marker inside a quote, is not either. @@ -29,6 +36,12 @@ export function isScript(sql: string): boolean { return bare.includes(";") || /\bexecute\s+immediate\b/i.test(bare) } +/** + * The byte count in a dry run's `bytes_processed`, which dbt-bigquery formats as text ("4.2 TiB", + * "512.0 Bytes"), and the most it can be. The text carries one decimal, so a figure past a byte is + * rounded: the true count is within half a tenth of its unit. Undefined for anything else, so a changed + * format is reported, never read as a count. + */ export function parseBytesProcessed(display: unknown): { bytes: number; maxBytes: number } | undefined { if (typeof display === "number") { if (!Number.isFinite(display) || display < 0) return undefined @@ -54,378 +67,6 @@ export function parseBytesProcessed(display: unknown): { bytes: number; maxBytes return { bytes, maxBytes: Math.max(bytes, maxBytes) } } -/** Bytes in the units the BigQuery dry run writes them in: "4.2 TiB". */ -export function formatBytes(bytes: number): string { - let n = bytes - let i = 0 - while (n >= 1024 && i < UNITS.length - 1) { - n /= 1024 - i++ - } - return `${n.toFixed(1)} ${UNITS[i]}` -} - -/** - * A plan with no size for a leaf: `relation` names it when the plan does, and `unread` marks a leaf that printed no - * size this parser could read (as opposed to Spark's default size for a table without statistics). - */ -export type NoStats = { noStats: true; relation?: string; unread?: true } - -/** A scan estimate from the warehouse's query planner: what EXPLAIN says the query reads, without running it. */ -export type PlanEstimate = { - bytes: number - partitionsAssigned?: number - partitionsTotal?: number - /** Snowflake: the total may leave out a source it cannot size (an external table, a stage, a secure view), so it is not a cap. */ - unsized?: true -} - -const count = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined) - -/** - * The bytes Snowflake's `EXPLAIN USING JSON` says the query will scan: `GlobalStats.bytesAssigned`, the - * micro-partitions left after compile-time pruning. Takes the `content` column as text or parsed JSON. - * Undefined for anything without a readable `bytesAssigned`, so a changed format is reported, never read as a count. - */ -export function parseSnowflakeExplain(content: unknown): PlanEstimate | undefined { - let plan = content - if (typeof plan === "string") { - try { - plan = JSON.parse(plan) - } catch { - return undefined - } - } - const stats = (plan as { GlobalStats?: Record } | null)?.GlobalStats - if (!stats || typeof stats !== "object") return undefined - const bytes = count(stats.bytesAssigned) - if (bytes === undefined) return undefined - const partitionsAssigned = count(stats.partitionsAssigned) - const partitionsTotal = count(stats.partitionsTotal) - // A total of 0 beside a scan (or with no operations to read), or a scan of an external table or stage, a secure view (its scanned size is hidden), or one with no or a zero - // size of its own, may leave data out of it. A 0 with no scan at all is a query that reads nothing. - const operations = (plan as { Operations?: unknown }).Operations - const scans = (Array.isArray(operations) ? operations.flat(2) : []).filter( - (op): op is { operation: string; bytesAssigned?: unknown } => typeof (op as { operation?: unknown } | null)?.operation === "string", - ) - const unsized = - (bytes === 0 && (!Array.isArray(operations) || scans.some((op) => /scan/i.test(op.operation)))) || - scans.some((op) => /external|stage|secure/i.test(op.operation) || (/scan/i.test(op.operation) && !count(op.bytesAssigned))) - return { - bytes: Math.round(bytes), - ...(unsized && { unsized: true as const }), - ...(partitionsAssigned !== undefined && { partitionsAssigned }), - ...(partitionsTotal !== undefined && { partitionsTotal }), - } -} - -/** Spark's `Utils.bytesToString` units, each 1024 times the one before; Spark 2 wrote "KB" for "KiB". */ -const SPARK_UNITS: Record = { B: 0, KIB: 1, MIB: 2, GIB: 3, TIB: 4, PIB: 5, EIB: 6, KB: 1, MB: 2, GB: 3, TB: 4, PB: 5, EB: 6 } -/** - * A relation Spark has no size for is given `spark.sql.defaultSizeInBytes`, Long.MaxValue unless set ("8.0 EiB"): - * a leaf at or past this is no size at all. - */ -const SPARK_NO_SIZE = 2 ** 62 - -/** The headers Spark writes between the sections of an EXPLAIN. */ -const SPARK_SECTION = /^== (Parsed Logical Plan|Analyzed Logical Plan|Optimized Logical Plan|Physical Plan) ==\s*$/ - -/** A `sizeInBytes=` figure read back into bytes: "12.3 MiB", "16.0 B", or past a long "1.23E+21 B". */ -function sparkBytes(figure: string): number | undefined { - const match = /^(\d+(?:\.\d+)?(?:E[+-]?\d+)?)\s*([A-Za-z]+)$/i.exec(figure.trim()) - if (!match) return undefined - const unit = SPARK_UNITS[match[2].toUpperCase()] - if (unit === undefined) return undefined - const value = Number(match[1]) * 1024 ** unit - return Number.isFinite(value) ? value : undefined -} - -/** - * The bytes Databricks' `EXPLAIN COST` says the query reads: the sum of `Statistics(sizeInBytes=…)` over the - * leaves of the Optimized Logical Plan, the relations it scans. Their sizes are table (or file) sizes from the - * catalog and the Delta log, before column pruning and runtime file skipping. `noStats` when a leaf carries no - * size or Spark's default for a relation without statistics (with the relation's name when the leaf gives one); - * undefined when there is no plan to read. - */ -export function parseDatabricksExplainCost(plan: unknown): PlanEstimate | NoStats | undefined { - if (typeof plan !== "string") return undefined - const lines = plan.replace(/\r\n?/g, "\n").split("\n") - const start = lines.findIndex((line) => /^\s*==\s*Optimized Logical Plan\s*==\s*$/i.test(line)) - if (start < 0) return undefined - const nodes: { depth: number; text: string }[] = [] - for (let i = start + 1; i < lines.length; i++) { - const line = lines[i] - const previous = i > start + 1 ? lines[i - 1] : undefined - // Only Spark's own section headers end the plan: a line of a multi-line node could look like one. Spark sets - // each section off with an empty line, which the line of a literal holding a line break does not have before it. - // A literal built to hold an empty line, a heading and a statistics suffix would still end the plan early; the - // SQL is the agent's own, so that is not defended against. - if (SPARK_SECTION.test(line) && (previous === undefined || !previous.trim())) break - if (!line.trim()) continue - // Each level of the tree is three characters: ": " or " " for an ancestor, ":- " or "+- " for the node itself. - const prefix = /^(?:: | )*(?:[:+]- )?/.exec(line)![0] - // A tree has one root: a later line with no prefix is the rest of the node above it (a literal with a line break). - if (!prefix && nodes.length > 0) { - nodes[nodes.length - 1].text += `\n${line}` - continue - } - nodes.push({ depth: prefix.length / 3, text: line.slice(prefix.length) }) - } - if (nodes.length === 0) return undefined - // A node has a child when a later node sits one level below it before the tree comes back up to its level. An inner - // plan (a subquery) is printed two levels below, so a node holding one and no child is still a leaf. - const hasChild = nodes.map(() => false) - const open: number[] = [] - nodes.forEach((node, i) => { - while (open.length > 0 && nodes[open[open.length - 1]].depth >= node.depth) open.pop() - if (open.length > 0 && nodes[open[open.length - 1]].depth === node.depth - 1) hasChild[open[open.length - 1]] = true - open.push(i) - }) - let bytes = 0 - for (let i = 0; i < nodes.length; i++) { - if (hasChild[i]) continue - // Only the suffix Spark appends to the node: a column can be named anything, "Statistics(sizeInBytes=…)" too. - const figure = /, Statistics\(sizeInBytes=([^,()]+)(?:, [^()]*)?\)\s*$/.exec(nodes[i].text)?.[1] - const size = figure === undefined ? undefined : sparkBytes(figure) - if (size === undefined || size >= SPARK_NO_SIZE) { - // "Relation main.sales.orders[…] parquet": Spark prints the name unquoted, so only a plain one (letters, digits, - // underscores, dots) right before the column list is surely the whole name; any other gives none. - const relation = /^Relation ([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)\[/.exec(nodes[i].text)?.[1] - const unread = size === undefined ? { unread: true as const } : {} - return { noStats: true, ...(relation && { relation }), ...unread } - } - bytes += size - } - return { bytes: Math.round(bytes) } -} - -/** The data source formats Spark reads a path with (`json.`/path``). */ -const FILE_FORMATS = "json|csv|parquet|avro|orc|text|binaryfile|xml|libsvm|image" - -/** - * Whether a Databricks query reads files rather than tables (read_files, cloud_files, a path such as json.`…`): - * planning one can read the files to infer their schema. Read on the code `scanSql` leaves (comments and quoted text - * as spaces, backtick-quoted names kept), with any spacing between a name and what follows. Anything the scanner - * does not read counts. - */ -export function readsFiles(sql: string): boolean { - const { script, code, literals, calls } = scanSql(sql, "databricks") - if (script) return true - if (fileSource(code)) return true - // IDENTIFIER(expr) names a function or relation from a string, which the scan blanked: allow a lone string literal - // that is a plain table name, and count any other argument (a variable, :param, concatenation, adjacent literals, escapes) as a read. - // Upper-cased as Spark's lexer folds keywords (a dotless ı spells IDENTIFIER too). - const bare = code.replace(/`[^`]*`/g, " ").toUpperCase() - // A qualified clause (system.builtin.IDENTIFIER('read_files')) or one a name continues past (IDENTIFIER('json').`p`) - // is assembled from parts this does not read. - if (/\.\s*IDENTIFIER\s*\(/.test(bare) || /IDENTIFIER\s*\(\s*\u0000\s*\)\s*\./.test(bare)) return true - let plain = 0 - const format = new RegExp(`^(${FILE_FORMATS})$`, "i") - for (const lit of literals) { - plain++ - // Only a plain dotted name of up to three parts is a table: anything quoted, escaped, commented, substituted, - // non-ASCII or longer is not read (Spark resolves it by rules this does not model), nor is a read_files or - // cloud_files part, or a format before the path (json.raw). - const parts = lit.text.split(".") - if (parts.length > 3 || !parts.every((part) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(part))) return true - if (parts.some((part) => /^(read_files|cloud_files)$/i.test(part)) || format.test(parts[0])) return true - } - return calls > plain -} - -/** Whether code (as `scanSql` leaves it) names a file source: a read_files or cloud_files call, a format or path over backticks. */ -function fileSource(code: string): boolean { - // A function call, qualified or not (system.builtin.read_files). - if (/(^|[^a-z0-9_])`?(read_files|cloud_files)`?\s*\(/i.test(code)) return true - // A known format over any backtick-quoted name, unless the format word is the middle of a dotted name (main.json.`t`). - // Where a relation goes cannot be told from a column without parsing (FROM (json.`x`), FROM`json`.`x`), so a - // column qualified by an alias named like a format (json.`order-id`) is refused too: no estimate, never a missed read. - if (new RegExp(`(?:(^|[^a-z0-9_.\`])(${FILE_FORMATS})|(^|[^.\`])\`(${FILE_FORMATS})\`)\\s*\\.\\s*\``, "i").test(code)) return true - // Any backtick-quoted name that looks like a path ("/" or ":", as in s3://…, dbfs:/…, /Volumes/…), whatever the source - // before it (a format, a provider class) or a doubled backtick inside it, unless it directly follows Delta's own - // provider: a source over files can infer its schema from them. - const rest = code.replace(/(^|[^a-z0-9_.`])`?delta`?\s*\.\s*`[^`]*`/gi, "$1 ") - return /`[^`]*[/:][^`]*`/.test(rest) -} - -/** - * The warehouses with no dry run whose planner still says what a query reads, the EXPLAIN that asks it, and the - * reader of its one row. - */ -const PLANNERS: Record PlanEstimate | NoStats | undefined }> = { - snowflake: { owner: "Snowflake's", explain: "EXPLAIN USING JSON", read: parseSnowflakeExplain }, - databricks: { owner: "Databricks'", explain: "EXPLAIN COST", read: parseDatabricksExplainCost }, -} - -/** - * Inline Jinja that runs the EXPLAIN through dbt's own connection (`run_query`) while dbt compiles it, and - * renders the first column of its answer as JSON. Compiling, not `dbt show`, since show wraps the query in a - * limit, which an EXPLAIN can't take. dbt renders an inline query twice: at parse, where `execute` is false and - * `run_query` returns nothing, the template renders `[]` and runs nothing. The SQL is written into a Jinja - * string, so its quotes and backslashes are escaped. - */ -export function explainJinja(explain: string, sql: string): string { - const statement = `${explain}\n${sql.replace(/[\s;]+$/, "")}` - const literal = `'${statement.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'` - return `{%- if execute -%}{%- set altimate_plan = run_query(${literal}) -%}{{ tojson(altimate_plan.columns[0].values() | list) }}{%- else -%}[]{%- endif -%}` -} - -/** - * The SQL up to its first semicolon outside quotes and comments. Past one `mayBeScript` allows only whitespace, - * semicolons and comments, which the driver would still split off and send as a statement of their own - * (`select 1; /* a\nb *\/`, `select 1;; -- c`): none of it is sent. Read for SQL `mayBeScript` accepted, so the - * quotes and comments it models are the only ones there are. - */ -export function firstStatement(sql: string, type: string): string { - const databricks = type === "databricks" - let i = 0 - while (i < sql.length) { - const c = sql[i] - const two = sql.slice(i, i + 2) - if (two === "--") { - const end = sql.indexOf("\n", i) - if (end < 0) break - i = end + 1 - } else if (two === "/*") { - const end = sql.indexOf("*/", i + 2) - if (end < 0) break - i = end + 2 - } else if (c === "'" || c === '"' || (databricks && c === "`")) { - let j = i + 1 - while (j < sql.length && sql[j] !== c) j += c !== "`" && sql[j] === "\\" ? 2 : 1 - i = j + 1 - } else if (c === ";") { - return sql.slice(0, i) - } else i++ - } - return sql -} - -/** - * Whether the SQL may be more than one statement, as the warehouse's driver splits it: dbt-snowflake runs each - * statement it splits off, so a second one after the EXPLAIN would run for real. One pass, left to right, that - * reads only what it models exactly: single- and double-quoted text (a backslash escapes, as the Snowflake - * connector's splitter reads it), backticks on Databricks, `--` and block comments. Anything else that could hide or - * fake a separator (Snowflake's `$$` text, `//` comments and `!` commands at a line's start, raw strings, nested - * comments, an unclosed quote or comment, EXECUTE IMMEDIATE) counts as a script, as does a semicolon with anything but whitespace after it: a doubt is no estimate, never a run. - */ -export function mayBeScript(input: string, type: string): boolean { - return scanSql(input, type).script -} - -/** - * The one reading of the SQL both checks share: whether it may be a script (see `mayBeScript`), and its code with - * comments and quoted text as spaces and Databricks' backtick-quoted names kept as written, and (Databricks) the lone - * string literals an IDENTIFIER( call holds. - */ -export function scanSql(input: string, type: string): { script: boolean; code: string; literals: { text: string }[]; calls: number } { - const script = { script: true, code: "", literals: [], calls: 0 } - // Read with the line breaks Jinja renders: every \r\n and lone \r is \n. - const sql = input.replace(/\r\n?/g, "\n") - const databricks = type === "databricks" - // The Snowflake splitter yields a line starting with "!" as a command of its own, wherever it sits: never read. - if (!databricks && /(^|\n)!/.test(sql)) return script - let code = "" - // The last of `code` with its whitespace collapsed to one space: what an IDENTIFIER( call is read from. - let tail = "" - const emit = (text: string) => { - code += text - tail = (tail + text.slice(-40)).replace(/\s+/g, " ").slice(-40) - } - // Databricks: the text of each string literal that opens an IDENTIFIER( call, and where it sits in `code`. - const literals: { text: string }[] = [] - let calls = 0 - // Past a semicolon only whitespace and comments may follow: anything else, quoted or not, is a second statement. - let ended = false - let i = 0 - while (i < sql.length) { - const c = sql[i] - const two = sql.slice(i, i + 2) - if (two === "--") { - const end = sql.indexOf("\n", i) - // Spark continues a line comment past a backslash at its end: not read. - if (databricks && end >= 0 && sql[end - 1] === "\\") return script - if (end < 0) break - i = end + 1 - emit(" ") - continue - } - if (two === "/*") { - const end = sql.indexOf("*/", i + 2) - // Databricks nests block comments, and an unclosed one hides the rest: neither is read, on either warehouse. - // The closer's star counts too: in "/*/*/" an opener overlaps it. - if (end < 0 || sql.slice(i + 2, end + 1).includes("/*")) return script - i = end + 2 - emit(" ") - continue - } - if (two === "$$" || (!databricks && two === "//")) return script - // Databricks raw strings (r'…', R"…") do not escape with a backslash: not read. - if (databricks && /[rR]/.test(c) && /['"]/.test(sql[i + 1] ?? "") && !/[A-Za-z0-9_]/.test(sql[i - 1] ?? "")) return script - if (ended && !/[\s;]/.test(c)) return script - if (c === ";") ended = true - const close = c === "'" || c === '"' || (databricks && c === "`") ? c : null - if (close) { - // A backslash escapes in quotes, as the splitter has it (only before a quote or a backslash, which skipping the - // next character always matches); Databricks' backticks take none. - const escapes = c !== "`" - let j = i + 1 - while (j < sql.length && sql[j] !== close) j += escapes && sql[j] === "\\" ? 2 : 1 - if (j >= sql.length) return script - let blank = " " - // Only a single-quoted string is a literal name: "…" may be a quoted identifier or a variable. - if (databricks && c !== "`" && opensIdentifier(tail)) { - // Marked, so a second literal after it does not read as the call's first. - blank = "\u0000" - // Only a literal the call's parenthesis closes is plain: a following literal, operator or name is not. - if (c === "'" && closesCall(sql, j + 1)) literals.push({ text: sql.slice(i + 1, j) }) - } - // A backtick-quoted name is code; quoted text is not. - emit(c === "`" ? sql.slice(i, j + 1) : blank) - i = j + 1 - continue - } - emit(c) - if (databricks && c === "(" && opensIdentifier(tail)) calls++ - i++ - } - return { script: /\bexecute\s+immediate\b/i.test(code), code, literals, calls } -} - -/** Whether `tail` (the last of `scanSql`'s code, whitespace collapsed to one space) ends in `IDENTIFIER(`. */ -function opensIdentifier(tail: string): boolean { - let t = tail.replace(/ $/, "") - if (!t.endsWith("(")) return false - t = t.slice(0, -1).replace(/ $/, "") - // Upper-cased as Spark's lexer folds keywords (a dotless ı spells IDENTIFIER too). - if (t.length < 10 || t.slice(-10).toUpperCase() !== "IDENTIFIER") return false - return t.length === 10 || !/[A-Za-z0-9_$]/.test(t[t.length - 11]) -} - -/** Whether, past whitespace and comments, the next character of `sql` from `at` is `)`. One pass, no backtracking. */ -function closesCall(sql: string, at: number): boolean { - let i = at - while (i < sql.length) { - if (/\s/.test(sql[i])) i++ - else if (sql.startsWith("--", i)) { - const end = sql.indexOf("\n", i) - if (end < 0) return false - i = end + 1 - } else if (sql.startsWith("/*", i)) { - const end = sql.indexOf("*/", i + 2) - if (end < 0) return false - i = end + 2 - } else return sql[i] === ")" - } - return false -} - -/** Test seams. */ -export const dbtCostEstimateInternals = { - /** How long a call waits for a planner's EXPLAIN before it gives up; the plugin's own wait is 120 s. */ - explainTimeoutMs: 90_000, -} - /** Starts `start` and waits for it, but gives up as soon as the call is cancelled; a cancelled call starts nothing. */ export function untilAbort(start: () => Promise, signal: AbortSignal): Promise { if (signal.aborted) return Promise.reject(signal.reason) @@ -439,116 +80,132 @@ export function untilAbort(start: () => Promise, signal: AbortSignal): Pro }) } +/** The only warehouse that is estimated. */ +const ADAPTER = "bigquery" + function failure(title: string, message: string, extra: Record = {}) { return { title: `dbt_cost_estimate: ${title}`, metadata: { success: false, error: message, ...extra }, output: message } } -/** The planner's estimate of a compiled query on a warehouse with no dry run: an EXPLAIN, which compiles the query and runs none of it. */ -async function explainEstimate( - adapter: { unsafeCompileQuery(sql: string, model?: string): Promise }, - type: string, - planner: (typeof PLANNERS)[string], - compiled: string, - model: string | undefined, - signal: AbortSignal, -) { - const extra = { adapter: type, source: "explain" } - // Jinja turns every \r\n and lone \r in a string into \n: the check reads the SQL exactly as the driver will get it. - const sql = compiled.replace(/\r\n?/g, "\n") - if (mayBeScript(sql, type)) { - return failure( - "no estimate", - `The query is more than one statement (or may be): ${planner.explain} takes one, and a second would run for real, so it is not estimated.`, - extra, - ) - } - // Databricks infers the schema of files a query reads directly by reading them, while it plans: an EXPLAIN would. - if (type === "databricks" && readsFiles(sql)) { - return failure( - "no estimate", - "The query reads files directly (read_files, cloud_files or a path such as json.`…`): Databricks infers their schema by reading them while it plans, so an EXPLAIN is not run for it.", - extra, - ) - } - let row: unknown - // The EXPLAIN is bounded like the dbt adapter's start: a call that outlasts the deadline stops waiting for it (the - // adapter takes no signal, so the statement itself runs on) and a cancelled call stops at once. - const deadline = new AbortController() - const timer = setTimeout( - () => deadline.abort(new Error(`${planner.explain} did not answer within ${dbtCostEstimateInternals.explainTimeoutMs / 1000} s`)), - dbtCostEstimateInternals.explainTimeoutMs, - ) +/** The pre-run scan figure for the compiled model or SQL: a BigQuery dry run. */ +async function scanEstimate(adapter: any, args: { model?: string; sql?: string }, signal: AbortSignal) { + let compiled: unknown try { - const rendered = await untilAbort( - () => adapter.unsafeCompileQuery(explainJinja(planner.explain, firstStatement(sql, type)), undefined), - AbortSignal.any([signal, deadline.signal]), + // A model compiles by name, so its node context (`this`, config) is kept; SQL compiles inline. + compiled = await untilAbort( + () => (args.model ? adapter.unsafeCompileNode(args.model) : adapter.unsafeCompileQuery(args.sql!, undefined)), + signal, ) - const rows = typeof rendered === "string" ? JSON.parse(rendered.trim()) : undefined - if (!Array.isArray(rows) || rows.length === 0) throw new Error(`${planner.explain} returned no plan`) - row = rows[0] } catch (e) { if (signal.aborted) throw e - return failure("explain failed", `${planner.owner} ${planner.explain} failed: ${e instanceof Error ? e.message : String(e)}`, extra) - } finally { - clearTimeout(timer) + return failure("compile failed", e instanceof Error ? e.message : String(e), { adapter: ADAPTER }) } - const parsed = planner.read(row) - if (parsed && "noStats" in parsed) { - const table = parsed.relation ?? "" - // A leaf that printed no readable size (rather than Spark's default) is not known to lack statistics: no advice. - if (parsed.unread) { - return failure( - "no estimate", - `${planner.owner} ${planner.explain} printed no size this tool can read for ${parsed.relation ?? "a table this query reads"}, so it is not estimated.`, - extra, - ) + if (typeof compiled !== "string" || !compiled.trim()) { + return failure("compile failed", "The query compiled to nothing.", { adapter: ADAPTER }) + } + let display: unknown + try { + const integration = await untilAbort(async () => { + const { dbtAdapterInternals } = await import("../native/connections/register") + const read = dbtAdapterInternals.readConfig ?? (await import("../../../../dbt-tools/src/config")).read + return ((await read()) as { dbtIntegration?: unknown } | null)?.dbtIntegration + }, signal) + const result = await untilAbort(() => adapter.validateSQLDryRun(forDryRun(compiled as string, integration)), signal) + if (result == null) { + return failure("dry run failed", "The dry run returned no estimate: dbt-core before 1.6 can't dry run.", { adapter: ADAPTER }) } - return failure( - "no estimate", - `${planner.owner} planner has no size for ${parsed.relation ?? "a table this query reads"} (it shows Spark's default for a table without statistics). ANALYZE TABLE ${table} COMPUTE STATISTICS NOSCAN records its size from file metadata without reading the data; without NOSCAN, ANALYZE scans the whole table.`, - extra, - ) + display = (result as { bytes_processed?: unknown }).bytes_processed + } catch (e) { + if (signal.aborted) throw e + return failure("dry run failed", e instanceof Error ? e.message : String(e), { adapter: ADAPTER }) } + const parsed = parseBytesProcessed(display) if (!parsed) { - return failure("unreadable estimate", `${planner.owner} ${planner.explain} answered a plan this tool can't read.`, extra) - } - const shown = formatBytes(parsed.bytes) - const partitions = - parsed.partitionsAssigned !== undefined && parsed.partitionsTotal !== undefined - ? `${parsed.partitionsAssigned} of ${parsed.partitionsTotal} partitions after pruning; ` - : "" - // Snowflake may give 0 for a source it cannot size when it compiles (an external table, a stage, a secure view): not a cap. - const unsized = type === "snowflake" && parsed.unsized === true - const accuracy = unsized - ? "Snowflake can leave a source it cannot size at compile time (an external table, a stage, a secure view) out of this figure, or report 0, so it is not a cap" - : type === "snowflake" - ? `${partitions}an upper bound: runtime pruning can scan less, and a cached result none` - : "table sizes before column pruning and file skipping, which usually read less; not a bound either way" + return failure("unreadable estimate", `The dry run returned an amount this tool can't read: ${JSON.stringify(display)}.`, { + adapter: ADAPTER, + }) + } + const name = args.model + const shown = typeof display === "number" ? `${parsed.bytes} Bytes` : String(display) + // A dry run can report 0 for a query that still reads data (BigQuery federated sources), and it skips + // what a script runs after its first statement or inside EXECUTE IMMEDIATE: those figures are lower + // bounds and carry no upper bound. + const zero = parsed.bytes === 0 + const lower = zero || isScript(compiled as string) return { title: `dbt_cost_estimate: ${shown}`, metadata: { success: true, supported: true, - adapter: type, - source: "explain", - // Snowflake documents bytesAssigned as an upper bound; Spark's sizes are the planner's guess, either way. - bound: unsized ? "unknown" : type === "snowflake" ? "upper" : "estimate", - bytes: parsed.bytes, + adapter: ADAPTER, + ...(lower ? { bytes: parsed.bytes, lowerBound: true } : parsed), display: shown, - ...(parsed.partitionsAssigned !== undefined && { partitionsAssigned: parsed.partitionsAssigned }), - ...(parsed.partitionsTotal !== undefined && { partitionsTotal: parsed.partitionsTotal }), - ...(model && { model }), + ...(name && { model: name }), }, - output: `${model ? `${model} ` : "The query "}would scan about ${shown}, by ${planner.owner} plan estimate (${accuracy}).`, + output: `${name ? `${name} ` : "The query "}would process ${shown} ${ + lower + ? "(a dry run can undercount a script or a zero estimate, so it is not priced)." + : `(bytes processed by the dry run; its display is rounded, so the count can be up to ${parsed.maxBytes}).` + }`, + } +} + +/** The scan result with the cost put in front: what earlier runs cost, and on BigQuery on-demand what the SELECT would. */ +function withCost( + scan: { title: string; metadata: Record; output: string }, + loaded: { cfg: CostConfig; history: History }, +) { + const { cfg, history } = loaded + const cost = { ...history.cost, notes: [...history.cost.notes] } + const meta = scan.metadata + if (meta.success === true && typeof meta.bytes === "number") { + if (history.capacity === true) { + cost.notes.push("The project is on capacity pricing (slots): scanned bytes do not set the cost, so the dry run is not priced.") + // With no priced run there is no cost to state a rate for, and the on-demand rate does not apply to a reservation. + if (cost.basis === "none") cost.rate = null + } else if (history.capacity === undefined) { + // Neither the project's jobs nor the caller's own could say which pricing applies: a price would be a guess. + const why = "BigQuery pricing mode could not be read (on-demand vs reservations)" + if (cost.basis === "none") cost.unknownReason = cost.unknownReason ? `${cost.unknownReason} ${why}.` : why + else cost.notes.push(`${why}, so the dry run is not priced.`) + } else if (meta.lowerBound === true || typeof meta.maxBytes !== "number") { + // A zero estimate is not a size (BigQuery reports 0 for a federated or external source); a script's dry run saw only its first statement. + cost.notes.push( + meta.bytes === 0 + ? "The dry run reported 0 bytes, which BigQuery also reports for row-level security, external (federated) tables and cached results, so it is not priced." + : "A script's dry run can skip statements or omit work that happens at run time, so it is not priced.", + ) + } else { + const demand = bigqueryOnDemandRate(cfg) + // BigQuery bills at least 10 MiB per query, so a tiny scan is not shown as free. + cost.selectOnly = { estimate: onDemandEstimate(Math.max(meta.bytes, MIN_BILLED_BYTES), demand.rate.value) } + if (!cost.rate) { + cost.rate = demand.rate + if (demand.note) cost.notes.push(demand.note) + } + cost.notes.push("The price covers the SELECT only.") + } + if (history.materialized === "incremental") + cost.notes.push( + "This model is incremental: depending on its strategy (merge, delete+insert, insert_overwrite) a run can also write a temp table and read the target, which a scan figure for the SELECT leaves out.", + ) } + // The history's answer stays the headline, an unknown one included; the dry run's price is its own labelled line. + return { ...scan, metadata: { ...meta, cost }, output: `${costText(cost, meta.display as string | undefined)}\n${scan.output}` } } export const DbtCostEstimateTool = Tool.define("dbt_cost_estimate", { description: - "Estimate the bytes a dbt model or a SQL query would scan, without running it. BigQuery answers from a dry run (`maxBytes` bounds it, or `lowerBound` marks a floor); Snowflake (`EXPLAIN USING JSON`, bytes left after pruning) and Databricks (`EXPLAIN COST`, the sizes of the tables it reads) answer from the planner (`source: \"explain\"`; `bound` is \"upper\" on Snowflake (\"unknown\" when the plan leaves out a source it cannot size: it reports 0 for one, or a scan of an external table, a stage or a secure view, or a scan with no size), \"estimate\" on Databricks), and none when Databricks has no table statistics. EXPLAIN compiles the query on the warehouse and scans no data: on Snowflake it needs no running warehouse (cloud-services time only); on Databricks it runs on the SQL warehouse or cluster the profile connects to, and starts it (billed while up) if it is stopped. A query that may be more than one statement is never EXPLAINed, nor on Databricks one that reads files directly (read_files, cloud_files, json.`path`), whose planning reads the files to infer a schema. Any other warehouse answers `supported: false` and nothing is compiled. Starts the dbt adapter (which runs `dbt deps`), so it needs write permission (`--allow-write` on `tool run` or the MCP server). The dry run never executes the final query, but compiling either input can render Jinja, and macros such as `run_query` can run real queries that are billed. Pass `model` (a model name, compiled as dbt would) or `sql` (may use Jinja).", + "Estimate the bytes a BigQuery dbt model or a SQL query would scan, and optionally what the model's earlier runs cost, without running it. BigQuery only: any other warehouse answers `supported: false` and nothing is compiled. By default (`history` false) it compiles and dry runs only and sends no INFORMATION_SCHEMA query: the answer is the bytes (`bytes`, `maxBytes`, `display`; `lowerBound` marks a script or zero estimate) and no `cost`. Pass `history: true` when the user asks what a model costs or what its runs cost. It then also reads the warehouse's reported usage for the model's runs in the last 30 days (bytes billed or slot time from INFORMATION_SCHEMA.JOBS) and prices it at a stated rate, which can be a default or a configured rate, so it is an estimate and not an invoice amount; it is never invented when no history exists; only on-demand pricing prices the dry run, as an estimate for the SELECT only (`cost.selectOnly.estimate`: the dry run's bytes at the on-demand rate; the bill can differ, for a cached or BI Engine result bills nothing and external sources are not fully counted); a `sql` input has no history. With `history: true` the figures are of the current dbt target's runs (other targets' runs are in `cost.otherTargets`), reservation runs are attributed slot time and not the bill (`cost.attribution`), an on-demand BigQuery ML (CREATE MODEL) job has no known price and leaves its run out, and `cost.scope` is `user` when the role lacks bigquery.jobs.listAll and only its own jobs were read; a Python model runs on Dataproc and has no history. `history: true` runs up to eight billed INFORMATION_SCHEMA.JOBS queries per call (three normally: capacity, history and boundary; one more for the earlier jobs of labelled invocations, which reads back to the 180 days JOBS keeps and can scan far more query text than the history; one more when a script matched, for its children; up to eight when the role cannot list every user's jobs, since the capacity, history and children reads each run again on JOBS_BY_USER, which scans only the caller's own jobs, so other users' runs are left out; JOBS needs bigquery.jobs.create and bigquery.jobs.listAll, JOBS_BY_USER bigquery.jobs.create and bigquery.jobs.list): a capacity check over 7 days of jobs, the history over 30 days (it scans the query text of every query job in the project, so the bytes grow with the project's activity, not with the model, and its 500-row limit does not limit the bytes), a boundary read (finished jobs of the 96 hours 10 minutes before, and jobs queued, running, or with no end time from no further back than 96 hours 10 minutes before the period read), and, when a script matched, its children. Each is billed on demand (at least 10 MiB) or uses reservation slots, and INFORMATION_SCHEMA is never cached, so do not pass it for a routine pre-run check. Starts the dbt adapter (which runs `dbt deps`), so it needs write permission (`--allow-write` on `tool run` or the MCP server). The dry run never executes the final query, but compiling either input can render Jinja, and macros such as `run_query` can run real queries that are billed. Pass `model` (a model name, compiled as dbt would) or `sql` (may use Jinja).", parameters: z.object({ model: z.string().optional().describe("Model name to compile and estimate"), sql: z.string().optional().describe("SQL (may use Jinja) to compile and estimate"), + history: z + .boolean() + .optional() + .describe( + "Default false. Pass true to also read what the model's earlier runs cost; this runs billed INFORMATION_SCHEMA.JOBS queries (see the tool description)", + ), }), async execute(args, ctx) { if (!args.model && !args.sql) return failure("nothing to estimate", "Pass a model name or SQL.") @@ -557,74 +214,27 @@ export const DbtCostEstimateTool = Tool.define("dbt_cost_estimate", { if (!access.adapter) return failure("not available", `No estimate: ${access.reason}.`, { refusal: access.refusal }) const adapter = access.adapter const type: string | undefined = adapter.getAdapterType?.() - // Every dbt-integration refuses the dry run off BigQuery; elsewhere only a planner EXPLAIN tells the scan. Nothing is compiled for any other warehouse. - const planner = type ? PLANNERS[type] : undefined - if (type !== "bigquery" && !planner) { + // Every dbt integration refuses the dry run off BigQuery, so nothing is compiled for any other warehouse. + if (type !== "bigquery") { const adapterName = type ?? "unknown" return { title: "dbt_cost_estimate: no estimate", metadata: { success: true, supported: false, adapter: adapterName }, - output: `No cost estimate: scan estimates are only available on BigQuery, Snowflake and Databricks (this project uses ${adapterName}).`, + output: `No cost estimate: cost estimates are only available on BigQuery (this project uses ${adapterName}).`, } } const signal = ctx.abort - let compiled: unknown - try { - // A model compiles by name, so its node context (`this`, config) is kept; SQL compiles inline. - compiled = await untilAbort( - () => (args.model ? adapter.unsafeCompileNode(args.model) : adapter.unsafeCompileQuery(args.sql!, undefined)), - signal, - ) - } catch (e) { - if (signal.aborted) throw e - return failure("compile failed", e instanceof Error ? e.message : String(e), { adapter: type }) - } - if (typeof compiled !== "string" || !compiled.trim()) { - return failure("compile failed", "The query compiled to nothing.", { adapter: type }) - } - if (planner) return explainEstimate(adapter, type!, planner, compiled, args.model, signal) - let display: unknown - try { - const integration = await untilAbort(async () => { - const { dbtAdapterInternals } = await import("../native/connections/register") - const read = dbtAdapterInternals.readConfig ?? (await import("../../../../dbt-tools/src/config")).read - return ((await read()) as { dbtIntegration?: unknown } | null)?.dbtIntegration - }, signal) - const result = await untilAbort(() => adapter.validateSQLDryRun(forDryRun(compiled as string, integration)), signal) - if (result == null) { - return failure("dry run failed", "The dry run returned no estimate: dbt-core before 1.6 can't dry run.", { adapter: type }) - } - display = (result as { bytes_processed?: unknown }).bytes_processed - } catch (e) { - if (signal.aborted) throw e - return failure("dry run failed", e instanceof Error ? e.message : String(e), { adapter: type }) - } - const parsed = parseBytesProcessed(display) - if (!parsed) { - return failure("unreadable estimate", `The dry run returned an amount this tool can't read: ${JSON.stringify(display)}.`, { - adapter: type, - }) - } - const name = args.model - const shown = typeof display === "number" ? `${parsed.bytes} Bytes` : String(display) - // A dry run can report 0 for a query that still reads data (BigQuery federated sources), and it skips - // what a script runs after its first statement or inside EXECUTE IMMEDIATE: those figures are lower - // bounds and carry no upper bound. - const zero = parsed.bytes === 0 - const lower = zero || isScript(compiled as string) - return { - title: `dbt_cost_estimate: ${shown}`, - metadata: { - success: true, - supported: true, - adapter: type, - ...(lower ? { bytes: parsed.bytes, lowerBound: true } : parsed), - display: shown, - ...(name && { model: name }), - }, - output: `${name ? `${name} ` : "The query "}would process ${shown} ${ - lower ? "(a dry run can undercount a script or a zero estimate, so this is a lower bound, not a cap)." : `(at most ${parsed.maxBytes} bytes).` - }`, - } + // The Python bridge serialises adapter calls: the scan figure completes first, then the history is read + // within its own deadline, which can never affect the figure already computed. + const scan = await scanEstimate(adapter, args, signal) + // The history is opt-in: its INFORMATION_SCHEMA queries are billed, so a call that did not ask for it sends none. + if (!args.history) return scan + const rawCfg = await costHistoryInternals.readCostConfig() + const cfg = cleanRates(rawCfg) + const { getDbtProjectRoot } = await import("../native/connections/register") + const manifestPath = manifestPathFor(adapter, await getDbtProjectRoot().catch(() => undefined)) + const history = await loadHistory({ adapter, model: args.model, manifestPath, signal, cfg }) + history.cost.notes.push(...ignoredRateNotes(rawCfg)) + return withCost(scan, { cfg, history }) }, }) diff --git a/packages/opencode/src/altimate/tools/dbt-cost-history.ts b/packages/opencode/src/altimate/tools/dbt-cost-history.ts new file mode 100644 index 0000000000..687cbf7a6b --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-cost-history.ts @@ -0,0 +1,1200 @@ +import path from "path" +import { sanitizeBqRegion } from "../native/finops/bq-utils" +import { loadRawManifest } from "../native/dbt/helpers" + +/** What a model's previous runs cost, read from the warehouse's own billing tables, and the rates that turn usage into money. */ + +export const HISTORY_DAYS = 30 +export const HISTORY_LIMIT = 500 +const DAY_MS = 86_400_000 +/** INFORMATION_SCHEMA.JOBS keeps the last 180 days of jobs (BigQuery's documented retention): the furthest back any read can reach. */ +export const JOBS_RETENTION_DAYS = 180 +/** The start of a read's window: `days` before the instant the whole call reads as of. */ +export const windowStartMs = (asOfMs: number, days = HISTORY_DAYS) => asOfMs - days * DAY_MS +/** A matched job by the same user joins the run of the job before it when it starts within this long after that job ended. */ +export const BQ_CHAIN_MS = 60_000 +/** The largest rate the tool uses, in USD; a larger configured value is ignored and named. */ +export const MAX_RATE = 1e6 +/** The most child jobs of matched scripts the children query returns. */ +export const BQ_CHILD_LIMIT = 10000 +const LIMIT_NOTE = `Only the newest ${HISTORY_LIMIT} statements were read, so older runs are not counted.` +const boundaryNote = (dropped: number) => + `${dropped} run${dropped === 1 ? "" : "s"} that may have started before the period read ${dropped === 1 ? "was" : "were"} left out.` +const TIB = 1024 ** 4 + +export type CostConfig = { + bigqueryUsdPerTib?: number + bigquerySlotHourUsd?: number +} + +export const DEFAULT_RATES = { bigqueryUsdPerTib: 6.25, bigquerySlotHourUsd: 0.06 } + +export type CostRate = { + value: number + unit: string + source: "config" | "default" +} +export type NativeUnit = "bytes_billed" | "slot_hours" + +export type CostInfo = { + basis: "history" | "dry_run" | "none" + currency: "USD" + lastRun?: number + typical?: number + highest?: number + runs?: number + windowDays?: 30 + /** BigQuery on-demand: the dry run's bytes (at least BigQuery's 10 MiB per-query minimum) at the on-demand rate, `estimate`. It is an estimate, not a bound: a cached or BI Engine result bills nothing, and external sources and some queries are not fully counted. */ + selectOnly?: { estimate: number } + /** `user`: only the caller's own jobs were read (no bigquery.jobs.listAll); `project`: every user's. */ + scope?: "user" | "project" + /** How the history was priced: attributed slot time for reservation runs, bytes billed on demand, or both. */ + attribution?: "slot_time" | "bytes_billed" | "mixed" + /** The dbt target the statistics are of, when the runs could be told apart by target. */ + target?: string + /** Runs of other targets (and of an unknown one), left out of the statistics. */ + otherTargets?: { + target: string + runs: number + typical: number + /** How its runs were priced, and the rate behind `typical` (the on-demand rate; `slotRate` too when the runs mix both). */ + attribution: "slot_time" | "bytes_billed" | "mixed" + rate: CostRate + slotRate?: CostRate + }[] + native?: { unit: NativeUnit; lastRun?: number; typical?: number; highest?: number } + rate: CostRate | null + notes: string[] + unknownReason?: string +} + +const RATE_KEYS = ["bigqueryUsdPerTib", "bigquerySlotHourUsd"] as const +const usableRate = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v) && v > 0 && v <= MAX_RATE + +/** The config's rates that are usable numbers: positive, finite and at most MAX_RATE. */ +export function cleanRates(raw: unknown): CostConfig { + const out: CostConfig = {} + if (!raw || typeof raw !== "object") return out + const given: Record = { ...raw } + for (const key of RATE_KEYS) { + const v = given[key] + if (usableRate(v)) out[key] = v + } + return out +} + +/** A note for each configured rate that `cleanRates` ignores, so a default is never taken for the configured value. */ +export function ignoredRateNotes(raw: unknown): string[] { + if (!raw || typeof raw !== "object") return [] + const given: Record = { ...raw } + return RATE_KEYS.filter((key) => given[key] !== undefined && !usableRate(given[key])).map( + (key) => `cost.${key} is ignored: it must be a positive number up to ${MAX_RATE}; the default rate is used.`, + ) +} + +function rateOf(config: number | undefined, fallback: number, unit: string, key: string): { rate: CostRate; note?: string } { + if (config !== undefined) return { rate: { value: config, unit, source: "config" } } + return { + rate: { value: fallback, unit, source: "default" }, + note: `Rate ${fallback} ${unit} is a default rate${key === "bigquerySlotHourUsd" ? " (BigQuery Enterprise pay-as-you-go; Standard is 0.04)" : ""}; set cost.${key} to your contract rate.`, + } +} + +// ---- Matching a model's runs ---- + +/** dbt's default query comment carries `"node_id": ""`; the closing quote keeps `model.a.b` from matching `model.a.bc`. */ +export function needleFor(uniqueId: string): string { + return `"node_id": "${uniqueId}"` +} + +/** A single-quoted SQL string literal: backslash and quote escaped. */ +export function sqlString(value: string): string { + return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'` +} + +export type ModelRef = { uniqueId: string; materialized?: string; language?: string } + +/** + * The one model node a name stands for: a unique_id, a plain name, or a package-qualified or versioned + * name (`shop.orders`, `orders.v2`). Several nodes, or none, is an error that names them. + */ +export function resolveModel(nodes: Record, name: string): ModelRef | { error: string } { + const models = Object.entries(nodes).filter(([, n]) => n?.resource_type === "model") + let hits = models.filter(([id]) => id === name) + if (!hits.length) hits = models.filter(([, n]) => n.name === name) + if (!hits.length && name.includes(".")) hits = models.filter(([id]) => id.endsWith(`.${name}`)) + if (hits.length === 1) + return { uniqueId: hits[0][0], materialized: hits[0][1]?.config?.materialized, language: hits[0][1]?.language } + if (hits.length === 0) return { error: `no model named ${name} in the manifest` } + const ids = hits.map(([id]) => id).sort() + return { error: `${name} is ambiguous: it matches ${ids.join(", ")}; pass a unique_id` } +} + +/** The model the manifest the adapter wrote holds under `name`. */ +export function modelFromManifest(manifestPath: string, name: string): ModelRef | { error: string } { + let manifest: any + try { + manifest = loadRawManifest(manifestPath) + } catch (e) { + return { error: `the manifest at ${manifestPath} could not be read: ${e instanceof Error ? e.message : String(e)}` } + } + if (!manifest?.nodes) return { error: `no manifest at ${manifestPath}; run dbt parse or dbt compile first` } + return resolveModel(manifest.nodes, name) +} + +export function manifestPathFor(adapter: any, projectRoot: string | undefined): string | undefined { + const given = typeof adapter.getManifestPath === "function" ? adapter.getManifestPath() : undefined + if (typeof given === "string" && given) return given + const root = (typeof adapter.getProjectRoot === "function" ? adapter.getProjectRoot() : undefined) ?? projectRoot + return root ? path.join(root, "target", "manifest.json") : undefined +} + +// ---- History SQL ---- + +/** The statements that build the model's relation: a run holds at least one. Hooks, deletes, updates and reads around them join the run but are not one on their own. */ +const BQ_BUILD_TYPES = ["CREATE_TABLE_AS_SELECT", "CREATE_TABLE", "CREATE_VIEW", "CREATE_MATERIALIZED_VIEW", "INSERT", "MERGE", "SCRIPT"] +/** Marks the history tool's own queries, whose text carries the model's needle and which the reads must not match. */ +const OWN_MARK = "altimate_cost_read" +const notOwn = `strpos(query, '${OWN_MARK}') = 0` +/** A continuous query runs for as long as it is left running and is not a dbt run (dbt submits none): JOBS marks it with the documented `continuous` column. */ +const notContinuous = `coalesce(continuous, false) = false` +/** dbt-bigquery labels every job it runs with the id of the dbt invocation (`dbt_invocation_id`); the jobs of one invocation are one run. */ +export const INVOCATION_LABEL = "dbt_invocation_id" +/** The dbt target the job ran as, from the JSON in dbt's default query comment. */ +const targetColumn = `regexp_extract(query, r'"target_name": "([^"]*)"') as target_name` +const invocationColumn = `(select value from unnest(labels) where key = '${INVOCATION_LABEL}') as dbt_invocation_id` +/** A job that finished successfully, or one that is still queued or running (its run is not complete). */ +const LIVE_OR_DONE = "((upper(state) = 'DONE' and error_result is null) or upper(state) in ('PENDING','RUNNING'))" +/** The statement that ends a run: dbt builds an incremental model's temporary relation, then merges or inserts from it. */ +/** BigQuery ML statements: on demand, model training bills at its own price per TiB, not the query rate, so it is not priced from bytes billed. */ +const BQ_ML_TYPES = ["CREATE_MODEL"] +const BQ_FINAL_TYPES = ["MERGE", "INSERT", "SCRIPT"] +const DBT_TMP_SUFFIX = "__dbt_tmp" +/** A temporary-relation CREATE TABLE AS SELECT joins the final build that starts within this long after it ends. */ +export const BQ_TMP_JOIN_MS = 10 * 60_000 + +/** A BigQuery project id as a backtick-quoted name, or undefined when it holds anything a name can't. */ +export function bqProject(project: unknown): string | undefined { + return typeof project === "string" && /^[A-Za-z0-9_.:-]+$/.test(project) ? project : undefined +} + +/** The project's jobs, or only the caller's own (for a role that may not list every user's). */ +export type JobsView = "JOBS" | "JOBS_BY_USER" + +function bqJobs(project: string, location: unknown, view: JobsView): string { + return `\`${project}\`.\`region-${sanitizeBqRegion(location)}\`.INFORMATION_SCHEMA.${view}` +} + +/** The history and capacity queries (and the boundary, from its cutoff) read the same instant, `asOfMs`, as a literal: a window that slid between queries would not describe one period. */ +export function bigqueryHistorySql(input: { project: string; location?: unknown; needle: string; view?: JobsView; asOfMs: number }): string { + return `select /* ${OWN_MARK} */ job_id, user_email, creation_time, end_time, state, statement_type, destination_table.table_id as destination_table_id, destination_table.dataset_id as destination_dataset_id, ${invocationColumn}, ${targetColumn}, total_bytes_billed, total_slot_ms, reservation_id, cache_hit +from ${bqJobs(input.project, input.location, input.view ?? "JOBS")} +where creation_time > timestamp_millis(${windowStartMs(input.asOfMs)}) and creation_time <= timestamp_millis(${input.asOfMs}) + and upper(job_type) = 'QUERY' and ${LIVE_OR_DONE} + and parent_job_id is null + and ${notOwn} + and ${notContinuous} + and strpos(query, ${sqlString(input.needle)}) > 0 +order by creation_time desc limit ${HISTORY_LIMIT}` +} + +/** The child jobs of matched scripts: a script's own row carries no reservation, its children do. */ +/** `sinceMs` is the earliest parent's creation: a child never starts before its parent, and a fixed bound cannot slide past a child while the parents are read. */ +export function bigqueryChildrenSql(input: { project: string; location?: unknown; parents: string[]; sinceMs: number; view?: JobsView }): string { + return `select job_id, parent_job_id, creation_time, statement_type, total_bytes_billed, total_slot_ms, reservation_id, cache_hit +from ${bqJobs(input.project, input.location, input.view ?? "JOBS")} +where creation_time >= timestamp_millis(${Math.floor(input.sinceMs)}) + and upper(job_type) = 'QUERY' and upper(state) = 'DONE' and error_result is null + and ${notContinuous} + and parent_job_id in (${input.parents.map(sqlString).join(",")}) +order by creation_time desc limit ${BQ_CHILD_LIMIT}` +} + +/** How many query jobs ran in the last week, and how many of them in a reservation. */ +export function bigqueryCapacitySql(input: { project: string; location?: unknown; view?: JobsView; asOfMs: number }): string { + return `select count(*) as jobs, countif(reservation_id is not null) as reserved +from ${bqJobs(input.project, input.location, input.view ?? "JOBS")} +where creation_time > timestamp_millis(${windowStartMs(input.asOfMs, 7)}) and creation_time <= timestamp_millis(${input.asOfMs}) + and upper(job_type) = 'QUERY' and upper(state) = 'DONE' + and ${notContinuous}` +} + +/** + * The boundary reads the matching statements that started before the period the history read covers (`cutoffMs`, or the + * start of the window when the read did not hit its limit) and could join a run the history saw only the end of. + * + * The longest a job can plausibly be in flight, from BigQuery's documented limits: a query that has not started times out + * in the queue after 6 hours (interactive) or 24 hours (batch) by default (query queues page), and the queue timeout is + * configurable up to 48 hours (default configuration page: default_interactive_query_queue_timeout_ms and + * default_batch_query_queue_timeout_ms); once running (quotas page), a query or script may run up to 6 hours per attempt + * with up to three attempts (18 hours), and a CREATE MODEL statement times out at 24 hours by default, but at 48 hours for + * time series, AutoML and hyperparameter tuning models. The longest is the largest queue timeout plus the 48-hour CREATE + * MODEL: 48 + 48 = 96 hours. A job in flight longer than that is not covered, and neither is a job still going that was + * created longer ago than that. + */ +const BQ_QUEUE_MAX_MS = 48 * 3_600_000 +const BQ_RUN_MAX_MS = 48 * 3_600_000 +export const MAX_JOB_SPAN_MS = BQ_QUEUE_MAX_MS + BQ_RUN_MAX_MS + +/** + * How far from the cutoff a statement can be and still belong to a run that begins after it: a job in flight for the + * longest it can be (MAX_JOB_SPAN_MS), plus the longest gap by which one job joins the next (a temporary CTAS to its final + * build, ten minutes; ordinary chaining is a minute). It bounds the time rules for jobs that carry no invocation label: a + * finished job created earlier than this cannot chain into a run at the cutoff, and an unlabelled run starting later than + * this after the cutoff cannot have an unread job in it. A labelled invocation has no such limit: its jobs are found by id. + */ +export const BOUNDARY_SPAN_MS = MAX_JOB_SPAN_MS + Math.max(BQ_TMP_JOIN_MS, BQ_CHAIN_MS) + +/** + * The instants a boundary query is written with, all derived from the cutoff itself. `startBeforeMs` is one + * millisecond past it, so a statement that starts exactly at the cutoff is read; the lookbacks are measured from the + * cutoff, not from that millisecond. + */ +export type BoundaryWindow = { + /** Statements must start before this (the cutoff plus one millisecond). */ + startBeforeMs: number + /** ... and after this (the boundary span), for a job that has finished. */ + startAfterMs: number + /** A job still going (not done, or with no end time yet) is no older than the longest job span either. */ + liveStartAfterMs: number + /** A finished job of an invocation read may have been created any time JOBS keeps: an invocation has no span limit. */ + invocationStartAfterMs: number + /** A job must have ended at or after this (the cutoff less the chain window) to be able to join a run. */ + joinEndAtLeastMs: number + /** A temporary-relation CTAS must end at or after this (the cutoff less the join window). */ + tmpEndAtLeastMs: number +} + +export function boundaryWindow(cutoffMs: number, retentionStart = cutoffMs - JOBS_RETENTION_DAYS * DAY_MS): BoundaryWindow { + const cutoff = Math.trunc(cutoffMs) + return { + startBeforeMs: cutoff + 1, + startAfterMs: cutoff - BOUNDARY_SPAN_MS, + liveStartAfterMs: cutoff - BOUNDARY_SPAN_MS, + invocationStartAfterMs: Math.trunc(retentionStart), + joinEndAtLeastMs: cutoff - BQ_CHAIN_MS, + tmpEndAtLeastMs: cutoff - BQ_TMP_JOIN_MS, + } +} + +export function bigqueryBoundarySql(input: { + project: string + location?: unknown + needle: string + view?: JobsView + window: BoundaryWindow +}): string { + const at = (ms: number) => `timestamp_millis(${ms})` + const w = input.window + // One read, so no job can change state between two: what can join a run that starts after the cutoff is a finished job + // that ended within a minute before it (or the CTAS into dbt's temporary relation that ended within ten minutes before + // its final build) and was created in the lookback, or a job still going (not done, or with no end time yet) created + // no further back than the longest job span. Jobs still going come first, so finished ones cannot crowd them out of the limit. + const going = `(upper(state) in ('PENDING','RUNNING') or end_time is null)` + return `select /* run boundary */ /* ${OWN_MARK} */ job_id, user_email, creation_time, end_time, state, statement_type, destination_table.table_id as destination_table_id, destination_table.dataset_id as destination_dataset_id, ${invocationColumn}, ${targetColumn} +from ${bqJobs(input.project, input.location, input.view ?? "JOBS")} +where creation_time < ${at(w.startBeforeMs)} + and upper(job_type) = 'QUERY' + and parent_job_id is null + and ( + (${going} and creation_time > ${at(w.liveStartAfterMs)}) + or (creation_time > ${at(w.startAfterMs)} and upper(state) = 'DONE' and error_result is null and ( + end_time >= ${at(w.joinEndAtLeastMs)} + or (upper(statement_type) = 'CREATE_TABLE_AS_SELECT' and ends_with(destination_table.table_id, '${DBT_TMP_SUFFIX}') + and end_time >= ${at(w.tmpEndAtLeastMs)}) + )) + ) + and ${notOwn} + and ${notContinuous} + and strpos(query, ${sqlString(input.needle)}) > 0 +order by ${going} desc, creation_time desc limit ${HISTORY_LIMIT}` +} + +/** + * The jobs of the invocations already read, from before the cutoff and as far back as JOBS keeps them, in a read of their + * own: an invocation has no span limit, so these are found by id, and a full unlabelled boundary read cannot crowd them out. + * When this read is full, the invocations are not known to be complete. + */ +export function bigqueryInvocationSql(input: { project: string; location?: unknown; needle: string; view?: JobsView; window: BoundaryWindow; invocations: string[] }): string { + const at = (ms: number) => `timestamp_millis(${ms})` + const w = input.window + const ids = [...new Set(input.invocations)] + return `select /* invocation jobs */ /* ${OWN_MARK} */ job_id, user_email, creation_time, end_time, state, statement_type, destination_table.table_id as destination_table_id, destination_table.dataset_id as destination_dataset_id, ${invocationColumn}, ${targetColumn} +from ${bqJobs(input.project, input.location, input.view ?? "JOBS")} +where creation_time < ${at(w.startBeforeMs)} and creation_time > ${at(w.invocationStartAfterMs)} + and upper(job_type) = 'QUERY' and ${LIVE_OR_DONE} + and parent_job_id is null + and ${notOwn} + and ${notContinuous} + and strpos(query, ${sqlString(input.needle)}) > 0 + and (select value from unnest(labels) where key = '${INVOCATION_LABEL}') in (${ids.map(sqlString).join(",")}) +order by creation_time desc limit ${HISTORY_LIMIT}` +} + +// ---- Running a query through the dbt adapter ---- + +const jinjaString = (s: string) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'` + +/** + * Inline Jinja that runs `sql` through dbt's own connection (`run_query`) while dbt compiles it and renders every + * row as JSON text (dates and numbers as strings, nulls as null), since dbt's `tojson` drops what it can't encode. + * At dbt's parse pass, where `execute` is false, it runs nothing. + */ +export function rowsJinja(sql: string): string { + const literal = jinjaString(sql.replace(/[\s;]+$/, "")) + return ( + `{%- if execute -%}{%- set altimate_rows = run_query(${literal}) -%}{%- set altimate_out = [] -%}` + + `{%- for r in altimate_rows.rows -%}{%- set altimate_row = [] -%}` + + `{%- for v in r.values() -%}{%- do altimate_row.append(none if v is none else v | string) -%}{%- endfor -%}` + + `{%- do altimate_out.append(altimate_row) -%}{%- endfor -%}` + + `{{ tojson({"columns": altimate_rows.column_names | list, "rows": altimate_out}) }}` + + `{%- else -%}{"columns": [], "rows": []}{%- endif -%}` + ) +} + +/** Jinja that renders the fields of the dbt target the BigQuery history is read from. */ +export const TARGET_JINJA = + '{{ tojson({"project": target.get("project"), "execution_project": target.get("execution_project"), "location": target.get("location"), "name": target.get("name")}) }}' + +export type Row = Record + +export function parseRows(rendered: unknown): Row[] { + const parsed = typeof rendered === "string" ? JSON.parse(rendered.trim()) : undefined + if (!parsed || !Array.isArray(parsed.columns) || !Array.isArray(parsed.rows)) throw new Error("the query returned no table") + const columns: string[] = parsed.columns.map((c: unknown) => String(c).toLowerCase()) + return parsed.rows.map((values: (string | null)[]) => Object.fromEntries(columns.map((c, i) => [c, values[i] ?? null]))) +} + +// ---- Runs and their statistics ---- + +/** Why a run could not be priced. */ +export type Cause = "noslot" | "bqml" | "nullbytes" | "nochildren" | "cutchildren" | "badtime" | "unknown" +export type Causes = Partial> + +const CAUSE_TEXT: Record = { + noslot: "BigQuery gave no slot time for a job that ran in a reservation", + bqml: "a BigQuery ML job (CREATE MODEL) ran on demand, and its price is not the query rate", + nullbytes: "BigQuery gave no bytes billed for a job (it hides them for tables under a row access policy)", + nochildren: "a script's child jobs were not found", + cutchildren: "a script's child jobs may be cut off at the children query's limit", + badtime: "a script's start time could not be read", + unknown: "their cost is not known", +} + +const causeList = (causes: Causes) => + Object.entries(CAUSE_TEXT) + .filter(([cause]) => cause in causes) + .map(([, text]) => text) + .join("; ") + +/** A timestamp as text, read as UTC when it names no zone. */ +export function parseTime(value: string | null | undefined): number { + if (!value) return Number.NaN + const iso = value.includes("T") ? value : value.replace(" ", "T") + return Date.parse(/(Z|[+-]\d\d(:?\d\d)?)$/.test(iso.slice(10)) ? iso : `${iso}Z`) +} + +/** + * What lies before the period a history read covers. `cutoff` is the oldest returned statement's start when the read + * hit its limit, else the start of the window. `stmts` are the matching statements that started before it and could + * join a run that began earlier; undefined when they could not be read. + */ +export type Boundary = { + cutoff: number + stmts?: { user: string | null; start: number; end: number; tmp?: boolean; dataset?: string | null; inv?: string; target?: string }[] + /** Jobs still going (queued, running, or with no end time) in the window, each lasting to the instant read. They leave out any run they could chain into. */ + live?: { user: string | null; start: number; inv?: string; target?: string }[] + /** The read of the invocations' own jobs was full: no labelled run is known to be complete. */ + invocationsFull?: boolean + /** The boundary read was full: it cannot say what it left out, so runs near the cutoff are not trusted besides. */ + full?: boolean + /** The boundary read was full: every run by these users, who have a job still going, is left out. */ + liveFullUsers?: string[] +} + +/** When the boundary read is full or its statements are unknown, runs starting this close to the cutoff are not trusted. */ +export const BOUNDARY_FALLBACK_MS = BOUNDARY_SPAN_MS + +export function median(values: number[]): number { + const s = [...values].sort((a, b) => a - b) + const mid = s.length >> 1 + return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2 +} + +export function summarize(runs: { start: number; cost: number; native: number }[]) { + const latest = runs.reduce((a, b) => (b.start > a.start ? b : a)) + return { + lastRun: latest.cost, + typical: median(runs.map((r) => r.cost)), + highest: Math.max(...runs.map((r) => r.cost)), + runs: runs.length, + windowDays: HISTORY_DAYS as 30, + native: { + lastRun: latest.native, + typical: median(runs.map((r) => r.native)), + highest: Math.max(...runs.map((r) => r.native)), + }, + } +} + +const num = (v: string | null | undefined) => (v === null || v === undefined || v === "" ? undefined : Number.isFinite(Number(v)) ? Number(v) : undefined) + +// ---- Pricing per warehouse ---- + +export type History = { + cost: CostInfo + /** BigQuery: whether the project is on capacity pricing; undefined when that could not be told. */ + capacity?: boolean + /** The model's materialization, when the manifest names it. */ + materialized?: string +} + +const none = (reason: string, notes: string[] = [], rate: CostRate | null = null): CostInfo => ({ + basis: "none", + currency: "USD", + rate, + notes, + unknownReason: reason, +}) + +/** Where the history was read from: the target's location, or the `us` region a target with none falls back to. */ +export function locationNote(location: unknown): string { + const set = typeof location === "string" && location.trim() !== "" + const region = `region-${sanitizeBqRegion(location)}` + return set + ? `Location read: ${region} (the target's location).` + : `The target sets no location, so ${region} was read; if the datasets live in another location, set location in the dbt profile.` +} + +const PYTHON_NOTE = + "A Python model runs on Dataproc, not as a BigQuery query job, so it never appears in INFORMATION_SCHEMA.JOBS and its cost cannot be read from it." +const EPHEMERAL_NOTE = "An ephemeral model never runs on its own: its SQL is inlined into the models that ref it, so look at the runs of those models." + +function emptyMessage(uniqueId: string, table: string, opts: { materialized?: string; location?: string }): string { + const parts = [ + `No runs of ${uniqueId} in the last ${HISTORY_DAYS} days were found in ${table} (a project that overrides dbt's query-comment, a role without access, or a different location finds none).`, + opts.materialized === "ephemeral" ? EPHEMERAL_NOTE : undefined, + opts.location, + ] + return parts.filter(Boolean).join(" ") +} + +const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}` + +/** One BigQuery job, or the children of a script, priced as what they are: bytes billed on demand, slot time in a reservation. */ +type BqUnit = { + cause?: Cause + user: string + start: number + end: number + /** The dbt invocation id the job is labelled with, or "" when it has none. */ + inv: string + /** The dbt target the job's query comment names, or "" when it names none. */ + target: string + /** The destination dataset, when the job names one. */ + dataset: string + /** A CREATE TABLE AS SELECT into dbt's temporary relation. */ + tmp: boolean + /** A job that can end a run: MERGE, INSERT or a script. */ + final: boolean + /** The start and destination dataset of each final job a run holds. */ + finals?: { start: number; dataset: string }[] + /** The latest end of a temporary CTAS in the run that no final build has taken: its MERGE may still come for ten minutes. */ + unpairedTmpEnd?: number + /** Set on a temporary CTAS no final build took. */ + unpaired?: boolean + /** A statement that builds the model's relation (see BQ_BUILD_TYPES). */ + build: boolean + /** The job is still queued or running. */ + pending: boolean + cost: number + known: boolean + bytes: number + slotHours: number + reserved: boolean + demand: boolean +} + +function bqJob(r: Row, cfg: CostConfig, asOfMs?: number): BqUnit { + const slot = rateOf(cfg.bigquerySlotHourUsd, DEFAULT_RATES.bigquerySlotHourUsd, "USD/slot-hour", "bigquerySlotHourUsd").rate.value + const demand = rateOf(cfg.bigqueryUsdPerTib, DEFAULT_RATES.bigqueryUsdPerTib, "USD/TiB", "bigqueryUsdPerTib").rate.value + const reserved = r.reservation_id !== null && r.reservation_id !== undefined && r.reservation_id !== "" + const slotHours = (num(r.total_slot_ms) ?? 0) / 3_600_000 + const billed = num(r.total_bytes_billed) + // A cached result bills nothing; a missing figure (BigQuery hides it for tables under a row access policy) is not a zero. + const cached = String(r.cache_hit).toLowerCase() === "true" + // A job in a reservation is priced by its slot time, which must be reported too: a missing one is not a zero. + const ml = BQ_ML_TYPES.includes(stmtType(r)) + const known = reserved ? num(r.total_slot_ms) !== undefined : !ml && (billed !== undefined || cached) + const pending = isPending(r) + return { + cause: known ? undefined : reserved ? ("noslot" as Cause) : ml ? ("bqml" as Cause) : ("nullbytes" as Cause), + user: r.user_email ?? "", + // A job still running has no end yet: it lasts to the instant read, or beyond it. + end: pending ? (asOfMs ?? Number.POSITIVE_INFINITY) : parseTime(r.end_time), + // A BigQuery ML statement counts as a build, so a run of one exists and is left out with its BigQuery ML cause. + build: BQ_BUILD_TYPES.includes(stmtType(r)) || ml, + pending, + inv: r.dbt_invocation_id ?? "", + target: r.target_name ?? "", + dataset: r.destination_dataset_id ?? "", + tmp: stmtType(r) === "CREATE_TABLE_AS_SELECT" && (r.destination_table_id ?? "").endsWith(DBT_TMP_SUFFIX), + final: BQ_FINAL_TYPES.includes(stmtType(r)), + start: parseTime(r.creation_time), + cost: reserved ? slotHours * slot : ((billed ?? 0) / TIB) * demand, + known, + bytes: reserved ? 0 : (billed ?? 0), + slotHours: reserved ? slotHours : 0, + reserved, + demand: !reserved, + } +} + +/** A statement type as the warehouse reports it, in upper case. */ +const stmtType = (r: Row) => (r.statement_type ?? "").toUpperCase() + +/** A row that names a state other than DONE, or a null end time, is a job still queued or running; one that names neither is done. */ +const isPending = (r: Row) => (!!r.state && r.state.toUpperCase() !== "DONE") || r.end_time === null + +const sumUnits = (start: number, units: BqUnit[], over: { user: string; final: boolean; dataset: string; inv?: string; target?: string }): BqUnit => ({ + cause: units.find((u) => !u.known)?.cause, + user: over.user, + end: Math.max(...units.map((u) => u.end)), + inv: over.inv ?? "", + target: over.target ?? "", + dataset: over.dataset, + tmp: false, + final: over.final, + build: units.some((u) => u.build), + pending: units.some((u) => u.pending), + start, + cost: units.reduce((t, u) => t + u.cost, 0), + known: units.every((u) => u.known), + bytes: units.reduce((t, u) => t + u.bytes, 0), + slotHours: units.reduce((t, u) => t + u.slotHours, 0), + reserved: units.some((u) => u.reserved), + demand: units.some((u) => u.demand), +}) + +/** Two jobs may share a run's destination when either names none (a script has no destination of its own) or both name the same dataset. */ +const sameDataset = (a: BqUnit, b: BqUnit) => !a.dataset || !b.dataset || a.dataset === b.dataset + +/** + * BigQuery runs. dbt-bigquery labels every job with its invocation id, and jobs with the same id are one run, however far apart. + * Jobs without the label are grouped by user and time: the model's matched top-level jobs by one user form a run + * while each job starts within a minute after the previous job of the run ended (a pre- or post-hook, a delete or + * update, each batch of a microbatch model); a script counts as one job, priced from its children. dbt builds an + * incremental model's temporary relation with a CREATE TABLE AS SELECT into `__dbt_tmp` in the same dataset and + * then merges or inserts from it: such a CTAS pairs with the final build (MERGE, INSERT or script) of the same user + * that starts within ten minutes after it ends, one CTAS to one final build, and the pair is a single job of the run. + * Jobs that only read (a SELECT hook) or delete join a run but do not make one: a group needs a build job. A group with a + * job still queued or running, or whose last job ended within a minute before `asOfMs` (the next job may still start), + * is a run in progress and is left out. + */ +export function bigqueryRuns( + units: BqUnit[], + boundary?: Boundary, + asOfMs?: number, +): { runs: BqUnit[]; skipped: number; dropped: number; inProgress: number; causes: Causes } { + // Jobs labelled with a dbt invocation id are grouped by it: one invocation is one run, whatever the gaps between its jobs. + // Jobs without the label (an older adapter, a custom job) are grouped by user and time below. + const byInvocation = new Map() + for (const u of units.filter((x) => x.inv)) byInvocation.set(u.inv, [...(byInvocation.get(u.inv) ?? []), u]) + // dbt makes one temporary relation per final build, which follows it: each temporary CTAS of an invocation takes the first + // final build that starts after it ended and no other CTAS has taken. One with none is still waiting for its build, even + // when an earlier build of the invocation (a microbatch's first batch) exists. + for (const g of byInvocation.values()) { + const finals = g.filter((u) => u.final).sort((a, b) => a.start - b.start) + const taken = new Set() + for (const t of g.filter((u) => u.tmp).sort((a, b) => a.end - b.end)) { + const f = finals.find((x) => !taken.has(x) && x.start >= t.end) + if (f) taken.add(f) + else t.unpaired = true + } + } + units = units.filter((x) => !x.inv) + const heads = units.filter((u) => !u.tmp).sort((a, b) => a.start - b.start) + const atoms = new Map(heads.map((b) => [b, [b]])) + const loose: BqUnit[][] = [] + // dbt makes one temporary relation per final build: taken in the order they ended, each CTAS takes the first + // qualifying final build no other CTAS has claimed. + const claimed = new Set() + for (const t of units.filter((b) => b.tmp).sort((a, b) => a.end - b.end)) { + const head = heads.find( + (b) => b.final && !claimed.has(b) && b.user === t.user && sameDataset(b, t) && b.start >= t.end && b.start - t.end <= BQ_TMP_JOIN_MS, + ) + if (head) { + claimed.add(head) + atoms.get(head)!.push(t) + } else { + t.unpaired = true + loose.push([t]) + } + } + const byUser = new Map() + for (const atom of [...atoms.values(), ...loose]) byUser.set(atom[0].user, [...(byUser.get(atom[0].user) ?? []), atom]) + const startOf = (atom: BqUnit[]) => Math.min(...atom.map((u) => u.start)) + const endOf = (atom: BqUnit[]) => Math.max(...atom.map((u) => u.end)) + const grouped: BqUnit[][] = [...byInvocation.values()] + for (const list of byUser.values()) { + let current: BqUnit[] = [] + let currentEnd = Number.NaN + for (const atom of list.sort((a, b) => startOf(a) - startOf(b))) { + if (current.length && startOf(atom) - currentEnd <= BQ_CHAIN_MS) { + current.push(...atom) + currentEnd = Math.max(currentEnd, endOf(atom)) + } else { + if (current.length) grouped.push(current) + current = [...atom] + currentEnd = endOf(atom) + } + } + if (current.length) grouped.push(current) + } + const all = grouped.map((g) => { + const head = g.find((u) => !u.tmp) ?? g[0] + const finals = g.filter((u) => u.final) + const unit = sumUnits(Math.min(...g.map((u) => u.start)), g, { user: head.user, final: finals.length > 0, dataset: head.dataset, inv: head.inv, target: head.target }) + // An unpaired temporary CTAS can still be joined by its final build for ten minutes, whatever ran after it. + const unpairedTmpEnd = Math.max(Number.NEGATIVE_INFINITY, ...g.filter((u) => u.unpaired).map((u) => u.end)) + return { ...unit, finals: finals.map((u) => ({ start: u.start, dataset: u.dataset })), unpairedTmpEnd } + }) + // Only a group with a build job is a run; a group of reads (`dbt show`) is not priced. + const candidates = all.filter((r) => r.build) + // Whether an unread job could belong to a run: the same invocation id when both carry one, else the user-and-time rule. + const joins = (b: NonNullable[number], r: BqUnit) => + // A job belongs to a run of its own target only (jobs naming none, to runs naming none), and labelled and unlabelled + // jobs are never one run (the main grouping keeps them apart): only like meets like. + (b.target ?? "") !== r.target + ? false + : b.inv || r.inv + ? !!b.inv && b.inv === r.inv + : (b.user ?? "") === r.user && + (b.end >= r.start - BQ_CHAIN_MS || + (!!b.tmp && + (r.finals ?? []).some((f) => b.end <= f.start && b.end >= f.start - BQ_TMP_JOIN_MS && (!b.dataset || !f.dataset || b.dataset === f.dataset)))) + // A job before the cutoff that is still running and could join the run makes it a run in progress, not just an uncertain one. + const liveBefore = (r: BqUnit) => + !!boundary && + // A full read cannot say which jobs it left out, so every unlabelled run by a user seen live is left out; a labelled run is + // judged by its own invocation (the same id live below, else the invocation read) and is not overridden by the user. + ((!r.inv && !!boundary.liveFullUsers?.includes(r.user) && !!boundary.live?.some((b) => (b.user ?? "") === r.user && (b.target ?? "") === r.target)) || + !!boundary.live?.some( + (b) => + (b.target ?? "") === r.target && + (b.inv || r.inv ? !!b.inv && b.inv === r.inv : (b.user ?? "") === r.user && r.end >= b.start - BQ_CHAIN_MS), + )) + const live = candidates.filter((r) => !(r.pending || (asOfMs !== undefined && (r.end >= asOfMs - BQ_CHAIN_MS || (r.unpairedTmpEnd ?? Number.NEGATIVE_INFINITY) >= asOfMs - BQ_TMP_JOIN_MS)) || liveBefore(r))) + // Unread statements before the cutoff that would have joined a run, whatever the run now pairs with: a job by the + // run's user that ended at or after a minute before the run's start, or a temporary-relation CTAS by the same user, + // into the dataset of a final build (or any, when that build names none), that ended at or before the build's start + // and within ten minutes of it (an unread CTAS could have been the one that build took). Such a run is not trusted. + const unsure = (r: BqUnit) => + boundary + ? !!boundary.stmts?.some((b) => joins(b, r)) || + (boundary.invocationsFull === true && !!r.inv) || + // The time fallback is for unlabelled runs: a labelled run is complete when every job of its invocation was read. + ((!boundary.stmts || boundary.full === true) && !r.inv && r.start <= boundary.cutoff + BOUNDARY_FALLBACK_MS) + : false + const counted = live.filter((r) => !unsure(r)) + const runs = counted.filter((r) => r.known && Number.isFinite(r.start)) + const causes: Causes = {} + for (const r of counted) if (!r.known) causes[r.cause ?? "unknown"] = (causes[r.cause ?? "unknown"] ?? 0) + 1 + return { + runs, + skipped: counted.length - runs.length, + dropped: live.length - counted.length, + inProgress: candidates.length - live.length, + causes, + } +} + +/** The runs left out of the figures because of another target (or none named), by target, each with how it was priced. */ +function otherTargetsOf(runs: BqUnit[], demand: CostRate, slot: CostRate): NonNullable { + const by = new Map() + for (const r of runs) by.set(r.target || "unknown target", [...(by.get(r.target || "unknown target") ?? []), r]) + return [...by.entries()] + .map(([target, rs]) => { + const anyDemand = rs.some((r) => r.demand) + const anySlots = rs.some((r) => r.reserved) + const attribution = anyDemand && anySlots ? "mixed" : anySlots ? "slot_time" : "bytes_billed" + return { + target, + runs: rs.length, + typical: median(rs.map((r) => r.cost)), + attribution: attribution as "slot_time" | "bytes_billed" | "mixed", + rate: attribution === "slot_time" ? slot : demand, + ...(attribution === "mixed" && { slotRate: slot }), + } + }) + .sort((a, b) => b.runs - a.runs) +} + +const rateText = (r: CostRate) => `${r.value} ${r.unit}, ${r.source === "config" ? "your config" : "default"}` +const otherTargetsText = (others: NonNullable) => + others + .map((o) => { + const how = + o.attribution === "slot_time" + ? `attributed slot time at ${rateText(o.rate)}` + : o.attribution === "mixed" + ? `bytes billed at ${rateText(o.rate)} and attributed slot time at ${rateText(o.slotRate!)}` + : `bytes billed at ${rateText(o.rate)}` + return `${o.target}: ${plural(o.runs, "run")}, typical ${formatMoney(o.typical)} (${how})` + }) + .join("; ") + +export function priceBigquery( + rows: Row[], + children: Row[] | undefined, + uniqueId: string, + cfg: CostConfig, + boundary?: Boundary, + opts: { materialized?: string; location?: string; asOfMs?: number; target?: string } = {}, +): { cost: CostInfo; reserved: boolean } { + const table = "INFORMATION_SCHEMA.JOBS" + // Every message that says no run was found also says where it looked. + const withLocation = (text: string) => [text, opts.location].filter(Boolean).join(" ") + const demand = rateOf(cfg.bigqueryUsdPerTib, DEFAULT_RATES.bigqueryUsdPerTib, "USD/TiB", "bigqueryUsdPerTib") + const slot = rateOf(cfg.bigquerySlotHourUsd, DEFAULT_RATES.bigquerySlotHourUsd, "USD/slot-hour", "bigquerySlotHourUsd") + if (!rows.length) return { cost: none(emptyMessage(uniqueId, table, opts), [], demand.rate), reserved: false } + // Children come newest first, up to a limit: a script that started before the oldest child returned may have more. + const childrenCut = (children?.length ?? 0) >= BQ_CHILD_LIMIT + const childBoundary = Math.min(...(children ?? []).map((c) => parseTime(c.creation_time))) + const units = rows.map((r) => { + if (stmtType(r) !== "SCRIPT") return bqJob(r, cfg, opts.asOfMs) + const kids = (children ?? []).filter((c) => c.parent_job_id === r.job_id).map((c) => bqJob(c, cfg)) + // A script's own row is never counted beside its children; with none found, its cost is not known. + const start = parseTime(r.creation_time) + // The children carry no end time: the script ended when its own row says. + const pending = isPending(r) + const unit = { + ...sumUnits(start, kids, { user: r.user_email ?? "", final: true, dataset: r.destination_dataset_id ?? "", inv: r.dbt_invocation_id ?? "", target: r.target_name ?? "" }), + end: pending ? (opts.asOfMs ?? Number.POSITIVE_INFINITY) : parseTime(r.end_time), + build: true, + pending, + } + // At the limit, a script that began before the oldest child returned may have lost children, found or not. + // A start that does not parse cannot be compared with the children read's bounds. + if (!Number.isFinite(start)) return { ...unit, known: false, cause: "badtime" as Cause } + if (childrenCut && !(start > childBoundary)) return { ...unit, known: false, cause: "cutchildren" as Cause } + if (!kids.length) return { ...unit, known: false, cause: "nochildren" as Cause } + return unit + }) + const truncated = rows.length >= HISTORY_LIMIT + // The figures are of the current dbt target's runs: a dev run on sampled data is not what the model costs in prod. The jobs + // are split by target before they are grouped, so a run never mixes targets; jobs whose query comment names no target are + // an unknown one and are not in the figures either. Other targets' runs are formed the same way and only listed. + const mine = opts.target ? units.filter((u) => u.target === opts.target) : units + const { runs, skipped, dropped, inProgress, causes } = bigqueryRuns(mine, boundary, opts.asOfMs) + const elsewhere = opts.target + ? otherTargetsOf( + [...new Set(units.filter((u) => u.target !== opts.target).map((u) => u.target))].flatMap( + (t) => bigqueryRuns(units.filter((u) => u.target === t), boundary, opts.asOfMs).runs, + ), + demand.rate, + slot.rate, + ) + : [] + const anyReserved = units.some((u) => u.reserved) + const notes: string[] = truncated ? [LIMIT_NOTE] : [] + if (dropped) notes.push(boundaryNote(dropped)) + if (skipped) notes.push(`${plural(skipped, "run")} left out: ${causeList(causes)}.`) + if (boundary?.liveFullUsers?.length) notes.push("The read of jobs before the period was full, so every unlabelled run by a user with a job still running was left out.") + if (inProgress) notes.push(inProgress === 1 ? "A run still in progress was left out." : `${inProgress} runs still in progress were left out.`) + if (!runs.length && elsewhere.length) + return { + reserved: anyReserved, + cost: { + ...none( + withLocation(`No run of ${uniqueId} on the current target (${opts.target}) was found in the last ${HISTORY_DAYS} days; ${otherTargetsText(elsewhere)}.`), + notes, + demand.rate, + ), + target: opts.target, + otherTargets: elsewhere, + }, + } + if (!runs.length && !skipped && !dropped && inProgress) + return { + reserved: anyReserved, + cost: none(withLocation(`Every run of ${uniqueId} found is still in progress (or ended in the last minute), so none is priced.`), notes, demand.rate), + } + if (!runs.length && !skipped && !dropped) + return { + reserved: anyReserved, + cost: none( + [ + // Builds of another target that could not be priced are not "only reads": say what is true of the current target. + opts.target && units.some((u) => u.build) + ? `No priced run of ${uniqueId} on the current target (${opts.target}) was found: the builds found are of other targets and could not be priced.` + : `No run of ${uniqueId} found: the jobs that carry its comment only read data (for example dbt show), and none built it.`, + opts.location, + ] + .filter(Boolean) + .join(" "), + notes, + demand.rate, + ), + } + if (!runs.length && !skipped && dropped) + return { + reserved: anyReserved, + cost: none(withLocation(`Every run of ${uniqueId} found may have started before the period read, so none is priced.`), notes, demand.rate), + } + if (!runs.length) + return { + reserved: anyReserved, + cost: none(withLocation(`No run of ${uniqueId} found could be priced: ${causeList(causes)}.`), notes, demand.rate), + } + const anyDemand = runs.some((r) => r.demand) + const allReserved = !anyDemand + const mixed = runs.some((r) => r.reserved) && anyDemand + const newest = runs.reduce((a, b) => (b.start > a.start ? b : a)) + const rate = newest.reserved && !newest.demand ? slot.rate : demand.rate + if (mixed) { + notes.push("Some runs ran in a reservation (priced by slot time) and some on demand (priced by bytes billed).") + // Said only when whole runs differ: one run that mixes both (a script's children) says nothing about older ones. + const newestMode = newest.reserved !== newest.demand ? (newest.reserved ? "reserved" : "demand") : undefined + if (newestMode && runs.some((r) => r !== newest && r.reserved !== r.demand && r.reserved === (newestMode === "demand"))) + notes.push( + newestMode === "reserved" + ? "The newest run was in a reservation and older ones on demand: the project's pricing may have changed." + : "The newest run was on demand and older ones in a reservation: the project's pricing may have changed.", + ) + // The headline rate may be the slot rate; the on-demand runs in the figures are priced at this one. + notes.push(`On-demand runs are priced at ${demand.rate.value} USD/TiB (${demand.rate.source === "config" ? "from your config" : "default"}).`) + } + if (runs.some((r) => r.reserved)) + notes.push( + `Slot time is attributed at ${slot.rate.value} USD/slot-hour; it is an allocation, not the bill: autoscaled slots are billed in steps of 50, by default with a one-minute minimum (reservations with fluid scaling have none), and baseline slots are always charged.`, + ) + if (elsewhere.length) notes.push(`Runs of other targets are not in these figures: ${otherTargetsText(elsewhere)}.`) + if (anyDemand) notes.push("On-demand jobs are priced by the bytes BigQuery billed for each job.") + if (anyDemand && demand.note) notes.push(demand.note) + if (runs.some((r) => r.reserved) && slot.note) notes.push(slot.note) + const stats = summarize(runs.map((r) => ({ start: r.start, cost: r.cost, native: allReserved ? r.slotHours : r.bytes }))) + return { + reserved: anyReserved, + cost: { + basis: "history", + currency: "USD", + ...stats, + native: mixed ? undefined : { unit: allReserved ? "slot_hours" : "bytes_billed", ...stats.native }, + attribution: mixed ? "mixed" : allReserved ? "slot_time" : "bytes_billed", + ...(opts.target && { target: opts.target }), + ...(elsewhere.length && { otherTargets: elsewhere }), + rate, + notes, + }, + } +} + +// ---- BigQuery's pre-run price ---- + +/** BigQuery's per-query minimum for on-demand billing. */ +export const MIN_BILLED_BYTES = 10 * 1024 ** 2 + +/** The dry run's bytes at the on-demand rate: an estimate of the SELECT's bill, not a bound on it. */ +export function onDemandEstimate(bytes: number, usdPerTib: number): number { + return (bytes / TIB) * usdPerTib +} + +export function bigqueryOnDemandRate(cfg: CostConfig) { + return rateOf(cfg.bigqueryUsdPerTib, DEFAULT_RATES.bigqueryUsdPerTib, "USD/TiB", "bigqueryUsdPerTib") +} + +// ---- Reading the answer ---- + +export function accessProblem(message: string): string | undefined { + if (/access denied|permission|not authorized|forbidden/i.test(message)) + return "the role needs bigquery.jobs.create and bigquery.jobs.listAll on the project to read INFORMATION_SCHEMA.JOBS (or bigquery.jobs.create and bigquery.jobs.list for its own jobs, through JOBS_BY_USER)" + return undefined +} + +/** The first line of an error that says something: dbt wraps a warehouse error in a bare "Encountered an error:" line. */ +function errorDetail(message: string): string { + const lines = message + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !/^(\[?error\]?:?\s*)?encountered an error:?$/i.test(l)) + return (lines[0] ?? "").replace(/^\[?error\]?:\s*/i, "").slice(0, 300) +} + +export function unreadable(message: string, location?: string): CostInfo { + const why = accessProblem(message) + const detail = errorDetail(message) + return none(`Cost history could not be read${why ? `: ${why}` : ""}${detail ? ` (${detail})` : ""}.${why && location ? ` ${location}` : ""}`) +} + +/** A dollar amount as text, to enough digits that a small one is not shown as zero. */ +export function formatMoney(value: number): string { + const digits = value === 0 ? 2 : Math.min(8, Math.max(2, 1 - Math.floor(Math.log10(Math.abs(value))))) + return `$${value.toFixed(digits)}` +} + +const NATIVE_LABEL: Record = { bytes_billed: "bytes billed", slot_hours: "slot-hours" } + +function nativeText(n: NonNullable): string { + const f = (v: number | undefined) => (v === undefined ? "-" : n.unit === "bytes_billed" ? String(Math.round(v)) : String(Number(v.toPrecision(4)))) + return `${NATIVE_LABEL[n.unit]}: last ${f(n.lastRun)}, typical ${f(n.typical)}, highest ${f(n.highest)}` +} + +/** The SELECT's estimated on-demand price, with what can make the bill differ. `shown` is the dry run's size as text. */ +function selectText(c: CostInfo, shown: string): string { + return `Pre-run scan estimate (not the model's run history): BigQuery's dry run estimates the SELECT at ${shown}, about ${formatMoney(c.selectOnly!.estimate)} on-demand. BigQuery bills at least 10 MiB per query, which this estimate applies. The bill can differ: a cached or BI Engine result bills nothing, clustered tables often bill less after runtime pruning, and external sources and some queries are not fully counted.` +} + +/** The cost as plain sentences, the first being the answer (or why there is none). */ +export function costText(c: CostInfo, shown = "the bytes it reports"): string { + const lines: string[] = [] + // First, before any figure: whose jobs were read. + const slots = c.basis === "history" && (c.attribution === "slot_time" || c.attribution === "mixed") + const slotsNote = "reservation runs are attributed slot time, not the bill" + if (c.scope === "user") + lines.push(`Only your own jobs were read (no bigquery.jobs.listAll): service-account and other users' runs are missing${slots ? `; ${slotsNote}` : ""}.`) + if (c.basis === "history") { + lines.push( + `Cost from ${c.runs} run${c.runs === 1 ? "" : "s"} in the last ${c.windowDays} days${slots && c.scope !== "user" ? ` (${slotsNote})` : ""}${c.target ? ` on target ${c.target}` : ""}: last run ${formatMoney(c.lastRun!)}, typical ${formatMoney(c.typical!)} (median), highest ${formatMoney(c.highest!)}.`, + ) + if (c.native) lines.push(`In the warehouse's own unit, ${nativeText(c.native)}.`) + } else if (c.basis === "dry_run") { + lines.push(selectText(c, shown)) + } else { + lines.push(`Cost unknown: ${c.unknownReason}`) + } + // With history the SELECT's price is a second figure, and the notes below refer to it. + if (c.basis !== "dry_run" && c.selectOnly) lines.push(selectText(c, shown)) + if (c.rate) lines.push(`Rate: ${c.rate.value} ${c.rate.unit} (${c.rate.source === "config" ? "from your config" : "default"}).`) + for (const n of c.notes) lines.push(n) + return lines.join("\n") +} + +// ---- Reading the history ---- + +/** The boundary read failed: runs still in progress or cut by the period's start cannot be told apart from whole ones. */ +class BoundaryUnreadable extends Error {} + +/** Test seams. */ +export const costHistoryInternals = { + /** How long the history queries together wait for the warehouse; a slower one is no history, and the scan figure stands. */ + historyTimeoutMs: 60_000, + /** The instant a call reads the history as of: taken once, and written as a literal into the history and capacity queries and the boundary's cutoff. */ + now: () => Date.now(), + /** The `cost` block of the config. */ + readCostConfig: async (): Promise => { + try { + const { Config } = await import("@/config/config") + return (await Config.get())?.cost + } catch { + return undefined + } + }, +} + +type Compiler = { unsafeCompileQuery(sql: string, model?: string): Promise } + +const message = (e: unknown) => (e instanceof Error ? e.message : String(e)) + +/** + * What the model's earlier runs cost and whether the project is on capacity pricing. The queries run one after another + * (the Python bridge serialises adapter calls) inside one deadline, and after the scan figure is computed. Never + * rejects except for a cancelled call: a failure is an answer with no cost and the reason. + */ +export async function loadHistory(input: { + adapter: Compiler + model?: string + manifestPath?: string + signal: AbortSignal + cfg: CostConfig +}): Promise { + const { adapter, signal, cfg } = input + // One instant for the whole call: the main read, its boundary and the capacity check use it (the children start at their earliest parent). + const asOfMs = costHistoryInternals.now() + const windowStart = windowStartMs(asOfMs) + // A call cancelled while the scan ran stops here, whether or not any history query would have been sent. + signal.throwIfAborted() + const deadline = new AbortController() + const ms = costHistoryInternals.historyTimeoutMs + const timer = setTimeout(() => deadline.abort(new Error(`the cost history did not answer within ${ms / 1000} s`)), ms) + const both = AbortSignal.any([signal, deadline.signal]) + const run = (start: () => Promise): Promise => { + if (both.aborted) return Promise.reject(both.reason) + return new Promise((resolve, reject) => { + const stop = () => reject(both.reason) + both.addEventListener("abort", stop, { once: true }) + start().then(resolve, reject).finally(() => both.removeEventListener("abort", stop)) + }) + } + const rows = (sql: string) => run(async () => parseRows(await adapter.unsafeCompileQuery(rowsJinja(sql), undefined))) + let uniqueId: string | undefined + let materialized: string | undefined + let language: string | undefined + let unavailable: string | undefined + if (!input.model) { + unavailable = "A SQL input has no run history; pass a model to price its earlier runs." + } else if (!input.manifestPath) { + unavailable = "No dbt manifest was found, so the model's unique_id is unknown." + } + else { + const found = modelFromManifest(input.manifestPath, input.model) + if ("error" in found) { + unavailable = `Cost history needs the model's unique_id: ${found.error}.` + } + else ({ uniqueId, materialized, language } = found) + } + const base = { materialized } + /** + * The matching statements just before the period `read` covers: the history read's own cutoff when it hit its + * limit, else the start of the window. A boundary that can't be read (or hit its limit) is unknown. + */ + const boundaryFor = async ( + read: Row[], + sqlFor: (window: BoundaryWindow) => string, + invocationSqlFor?: (window: BoundaryWindow) => string, + ): Promise => { + if (!read.length) return undefined + const starts = read.map((r) => parseTime(r.creation_time)).filter(Number.isFinite) + const hit = read.length >= HISTORY_LIMIT && starts.length > 0 + // The cutoff is the oldest statement read when the limit was hit, else the window's own start: the same instant + // the main read used, never recomputed. + const cutoff = hit ? Math.min(...starts) : windowStart + try { + // The window reaches the cutoff's own instant (a statement that starts exactly at it is read: the main read takes + // only statements after the window's start, and the oldest statement it returned is at the cutoff itself) while + // every lookback is measured from the cutoff. The statements already read come back too and are filtered out below. + const window = boundaryWindow(cutoff, windowStartMs(asOfMs, JOBS_RETENTION_DAYS)) + const boundaryRows = await rows(sqlFor(window)) + // The invocations' own jobs, read apart; both reads' rows are evidence, a job in both counted once. + const ownRows = invocationSqlFor ? await rows(invocationSqlFor(window)) : [] + const invocationsFull = ownRows.length >= HISTORY_LIMIT + const seen = new Set(boundaryRows.map((r) => r.job_id)) + const found = [...boundaryRows, ...ownRows.filter((r) => !seen.has(r.job_id))] + const going = (r: Row) => isPending(r) + // The cutoff's millisecond also returns statements the history already read: only unread ones are evidence. + const readIds = new Set(read.map((r) => r.job_id)) + const unread = found.filter((r) => !readIds.has(r.job_id)) + const live = unread.filter(going).map((r) => ({ user: r.user_email ?? null, start: parseTime(r.creation_time), inv: r.dbt_invocation_id ?? "", target: r.target_name ?? "" })) + // Full: the read cannot say what it left out, so the fallback applies besides all the evidence it did return, and + // every run by a user with a job still going is left out. + const full = boundaryRows.length >= HISTORY_LIMIT + return { + cutoff, + live, + ...(invocationsFull && { invocationsFull }), + ...(full && { full, liveFullUsers: [...new Set(live.map((j) => j.user ?? ""))] }), + stmts: unread + .filter((r) => !going(r)) + .map((r) => ({ + user: r.user_email ?? null, + start: parseTime(r.creation_time), + end: parseTime(r.end_time), + tmp: stmtType(r) === "CREATE_TABLE_AS_SELECT" && (r.destination_table_id ?? "").endsWith(DBT_TMP_SUFFIX), + dataset: r.destination_dataset_id ?? null, + inv: r.dbt_invocation_id ?? "", + target: r.target_name ?? "", + })), + } + } catch (e) { + // Not knowing which runs are still going or were cut, no run can be vouched for: the history is unknown. + throw signal.aborted ? e : new BoundaryUnreadable(message(e)) + } + } + try { + return { ...(await bigqueryHistory()), ...base } + } catch (e) { + if (signal.aborted) throw e + return { cost: unreadable(message(e)), ...base } + } finally { + clearTimeout(timer) + } + + async function bigqueryHistory(): Promise> { + // A Python model runs on Dataproc, not as a BigQuery query job, so it is never in JOBS: no query can find a run. + if (language === "python") return { cost: none(PYTHON_NOTE) } + let target: Record + try { + target = JSON.parse(String(await run(() => adapter.unsafeCompileQuery(TARGET_JINJA, undefined))).trim()) + } catch (e) { + if (signal.aborted) throw e + return { cost: none(unavailable ?? `The dbt target could not be read (${message(e)}).`) } + } + const project = bqProject(target.execution_project || target.project) + if (!project) return { cost: none(unavailable ?? "The dbt target names no usable BigQuery project.") } + const location = target.location + const where = locationNote(location) + const targetName = typeof target.name === "string" && target.name ? target.name : undefined + // A role that may not list every user's jobs is retried on its own: the answer then covers only its own runs. + const read = async (sqlFor: (view: JobsView) => string): Promise<{ rows: Row[]; own: boolean; view: JobsView }> => { + try { + return { rows: await rows(sqlFor("JOBS")), own: false, view: "JOBS" } + } catch (e) { + if (signal.aborted || !accessProblem(message(e))) throw e + try { + return { rows: await rows(sqlFor("JOBS_BY_USER")), own: true, view: "JOBS_BY_USER" } + } catch { + throw e + } + } + } + let pricing: boolean | undefined + // Whose jobs the reads covered, once one succeeded: every later answer, a failure included, says so. + let scope: CostInfo["scope"] + const scoped = (cost: CostInfo): CostInfo => ({ ...cost, ...(scope && { scope }) }) + try { + const { rows: seen, own } = await read((view) => bigqueryCapacitySql({ project, location, view, asOfMs })) + scope = own ? "user" : "project" + const reserved = num(seen[0]?.reserved) ?? 0 + pricing = reserved > 0 ? true : (num(seen[0]?.jobs) ?? 0) > 0 ? false : undefined + } catch (e) { + if (signal.aborted) throw e + } + if (!uniqueId) return { cost: scoped(none(unavailable!)), capacity: pricing } + const id = uniqueId + let cost: CostInfo + let reserved = false + try { + const history = await read((view) => bigqueryHistorySql({ project, location, needle: needleFor(id), view, asOfMs })) + scope = history.own ? "user" : "project" + // A script whose start does not parse is left out of the children read (its run is unknown), so no NaN reaches the SQL. + const scripts = history.rows.filter((r) => stmtType(r) === "SCRIPT" && r.job_id && Number.isFinite(parseTime(r.creation_time))) + const parents = scripts.map((r) => r.job_id!) + const sinceMs = Math.min(...scripts.map((r) => parseTime(r.creation_time))) + const children = parents.length + ? (await read((view) => bigqueryChildrenSql({ project, location, parents, sinceMs, view }))).rows + : undefined + // The boundary is read from the view the history came from. + let boundary: Boundary | undefined + try { + const invocations = history.rows.map((r) => r.dbt_invocation_id ?? "").filter(Boolean) + boundary = await boundaryFor( + history.rows, + (window) => bigqueryBoundarySql({ project, location, needle: needleFor(id), view: history.view, window }), + invocations.length + ? (window) => bigqueryInvocationSql({ project, location, needle: needleFor(id), view: history.view, window, invocations }) + : undefined, + ) + } catch (e) { + if (!(e instanceof BoundaryUnreadable)) throw e + return { + cost: scoped(none(`could not check for runs still in progress: ${errorDetail(e.message)}.`)), + capacity: history.rows.some((r) => r.reservation_id) ? true : pricing, + } + } + ;({ cost, reserved } = priceBigquery(history.rows, children, uniqueId, cfg, boundary, { materialized, location: where, asOfMs, target: targetName })) + if (scope) cost.scope = scope + if (cost.basis === "history" && reserved && pricing === false) + cost.notes.push( + "This model's runs include reservation jobs, but the project's jobs of the last 7 days were all on demand: the pricing may have changed, so the dry run is not priced.", + ) + if (cost.basis === "history" && !reserved && pricing === true) + cost.notes.push( + "This model's runs were all on demand, but the project's jobs of the last 7 days include reservation jobs: the pricing may have changed, so the dry run is not priced.", + ) + } catch (e) { + if (signal.aborted) throw e + cost = scoped(unreadable(message(e), where)) + } + return { cost, capacity: reserved ? true : pricing } + } +} diff --git a/packages/opencode/test/altimate/dbt-cost-estimate.test.ts b/packages/opencode/test/altimate/dbt-cost-estimate.test.ts index 0a060a9a6b..6d031cf1c8 100644 --- a/packages/opencode/test/altimate/dbt-cost-estimate.test.ts +++ b/packages/opencode/test/altimate/dbt-cost-estimate.test.ts @@ -2,26 +2,15 @@ // the answer for a warehouse with no dry run, a read-only call, and a model compiled by name. The dbt adapter is // replaced through `dbtAdapterInternals`, so these tests need no Python, dbt or warehouse. import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test" -import { mkdtemp, rm, writeFile } from "node:fs/promises" -import os from "node:os" +import { mkdir, writeFile } from "node:fs/promises" import path from "node:path" import { Effect } from "effect" import type { Tool } from "@/tool/tool" import { SessionID, MessageID } from "@/session/schema" import { dbtAdapterInternals, resetDbtAdapter } from "@/altimate/native/connections/register" -import { - DbtCostEstimateTool, - dbtCostEstimateInternals, - explainJinja, - firstStatement, - mayBeScript, - parseBytesProcessed, - readsFiles, - scanSql, - parseDatabricksExplainCost, - parseSnowflakeExplain, - untilAbort, -} from "@/altimate/tools/dbt-cost-estimate" +import { DbtCostEstimateTool, parseBytesProcessed, untilAbort } from "@/altimate/tools/dbt-cost-estimate" +import { costHistoryInternals } from "@/altimate/tools/dbt-cost-history" +import { tmpdir } from "../fixture/fixture" import { initTool } from "./tool-fixture" const ctx: Tool.Context = { @@ -35,6 +24,18 @@ const ctx: Tool.Context = { } let project: string +let projectDir: Awaited> +/** The history queries (as Jinja) the tool sent through the adapter. */ +let historyLog: string[] = [] +/** How many times the dbt target was read: every history call starts there. */ +let targetReads = 0 +const defaultReadCostConfig = costHistoryInternals.readCostConfig +const defaultNow = costHistoryInternals.now + +/** What the history Jinja renders: the columns and rows of a table, every value text or null. */ +function table(columns: string[], rows: (string | null)[][]) { + return JSON.stringify({ columns, rows }) +} type Calls = { nodes: string[]; queries: [string, string | undefined][]; dryRuns: string[] } @@ -46,14 +47,23 @@ function fakeAdapter( compileFails?: boolean dryRunFails?: boolean compile?: () => Promise - /** What compiling the EXPLAIN Jinja renders (the plan's first column as JSON), or a failure to throw. */ - explain?: () => Promise + /** The table a history query renders (see `table`), or a failure to throw; the SQL it was asked is passed in. */ + history?: (jinja: string) => Promise + /** What the read of the invocations' own jobs renders; none by default. */ + invocations?: (jinja: string) => Promise + /** What the boundary query (the matching statements just before the period read) renders; none by default. */ + boundary?: (jinja: string) => Promise + /** What the dbt target renders. */ + target?: string + /** The manifest path the adapter reports (`getManifestPath`), as the project's own adapter does. */ + manifestPath?: string } = {}, ) { return { isInitialized: () => true, dispose: async () => {}, getAdapterType: () => opts.type ?? "bigquery", + ...(opts.manifestPath ? { getManifestPath: () => opts.manifestPath } : {}), unsafeCompileNode: async (model: string) => { calls.nodes.push(model) if (opts.compile) return opts.compile() @@ -61,8 +71,20 @@ function fakeAdapter( return `compiled(${model})` }, unsafeCompileQuery: async (query: string, name?: string) => { + if (query.startsWith("{%- if execute -%}{%- set altimate_rows")) { + historyLog.push(query) + if (query.includes("/* invocation jobs */")) + return opts.invocations ? opts.invocations(query) : table(["job_id", "user_email", "creation_time", "end_time", "state"], []) + if (query.includes("/* run boundary */")) + return opts.boundary ? opts.boundary(query) : table(["session_id", "creation_time", "start_time", "end_time"], []) + if (opts.history) return opts.history(query) + throw new Error("no history in this test") + } + if (query.startsWith('{{ tojson({"project"')) { + targetReads++ + return opts.target ?? '{"project": "p1", "execution_project": null, "location": "EU"}' + } calls.queries.push([query, name]) - if (opts.explain && query.startsWith("{%- if execute -%}{%- set altimate_plan")) return opts.explain() if (opts.compileFails) throw new Error("compilation failed") return `compiled(${query})` }, @@ -85,18 +107,57 @@ function useAdapter(calls: Calls, opts?: Parameters[1]) { } beforeAll(async () => { - project = await mkdtemp(path.join(os.tmpdir(), "dbt-cost-estimate-")) + projectDir = await tmpdir() + project = projectDir.path await writeFile(path.join(project, "dbt_project.yml"), "name: shop\n") + await mkdir(path.join(project, "target")) + const model = (pkg: string, name: string, materialized: string, deps: string[] = []) => [ + `model.${pkg}.${name}`, + { resource_type: "model", name, config: { materialized }, depends_on: { nodes: deps } }, + ] + await writeFile( + path.join(project, "target", "manifest.json"), + JSON.stringify({ + nodes: Object.fromEntries([ + model("shop", "orders", "incremental", ["model.shop.stg_orders", "source.shop.raw.items"]), + model("shop", "stg_orders", "table", ["source.shop.raw.orders"]), + model("shop", "dup", "table"), + model("other", "dup", "table"), + model("shop", "mart", "table", ["model.shop.stg_orders"]), + model("shop", "lonely", "table"), + model("shop", "inline", "ephemeral"), + ["model.shop.pymodel", { resource_type: "model", name: "pymodel", language: "python", config: { materialized: "table" }, depends_on: { nodes: [] } }], + ]), + sources: { "source.shop.raw.orders": {}, "source.shop.raw.items": {} }, + }), + ) }) afterAll(async () => { - await rm(project, { recursive: true, force: true }) + await projectDir[Symbol.asyncDispose]() }) +/** The history's reason for having no figure: the unknown reason, which leads the answer, and the notes. */ +const why = (cost: { unknownReason?: string; notes: string[] }) => [cost.unknownReason, ...cost.notes].join(" ") + +/** Runs `body` with the call's instant fixed, and hands it that instant. */ +async function withNowAt(body: (asOfMs: number) => Promise) { + const asOfMs = Date.UTC(2026, 5, 1, 20, 0, 0) + costHistoryInternals.now = () => asOfMs + try { + await body(asOfMs) + } finally { + costHistoryInternals.now = defaultNow + } +} +const iso = (ms: number) => new Date(ms).toISOString() + let calls: Calls beforeEach(() => { resetDbtAdapter() calls = { nodes: [], queries: [], dryRuns: [] } + historyLog = [] + targetReads = 0 }) afterEach(() => { resetDbtAdapter() @@ -190,7 +251,7 @@ describe("dbt_cost_estimate", () => { expect(result.output).toContain("2048 Bytes") }) - test("a zero from the dry run is a lower bound, not an upper bound", async () => { + test("a zero from the dry run is not priced", async () => { useAdapter(calls, { bytes: 0 }) const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select 1" }, ctx) expect(result.metadata).toEqual({ @@ -202,7 +263,7 @@ describe("dbt_cost_estimate", () => { display: "0 Bytes", truncated: false, }) - expect(result.output).toContain("lower bound") + expect(result.output).toContain("so it is not priced") expect(result.output).not.toContain("at most") }) @@ -212,7 +273,7 @@ describe("dbt_cost_estimate", () => { "execute immediate 'select * from big'", "select * from t where m = '--'; execute immediate 'select * from big'", "select * from t where m = '#sale'; select * from big", - ])("a script (%s) is a lower bound, not an upper bound", async (sql) => { + ])("a script (%s) is not priced", async (sql) => { useAdapter(calls, { bytes: "1.0 GiB" }) const result = await (await initTool(DbtCostEstimateTool)).execute({ sql }, ctx) expect(result.metadata).toMatchObject({ bytes: 1024 ** 3, lowerBound: true }) @@ -229,12 +290,12 @@ describe("dbt_cost_estimate", () => { } }) - test.each(["duckdb", "redshift", "postgres"])("answers supported:false on %s and compiles nothing", async (type) => { + test.each(["snowflake", "databricks", "duckdb", "redshift", "postgres"])("answers supported:false on %s, which is not BigQuery, and compiles nothing", async (type) => { useAdapter(calls, { type }) const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) expect(result.metadata).toMatchObject({ success: true, supported: false, adapter: type }) expect(result.metadata.bytes).toBeUndefined() - expect(result.output).toBe(`No cost estimate: scan estimates are only available on BigQuery, Snowflake and Databricks (this project uses ${type}).`) + expect(result.output).toBe(`No cost estimate: cost estimates are only available on BigQuery (this project uses ${type}).`) expect(calls).toEqual({ nodes: [], queries: [], dryRuns: [] }) }) @@ -362,899 +423,1114 @@ describe("dbt_cost_estimate", () => { }) }) -// Snowflake's EXPLAIN USING JSON answers one row, column `content`: the shape documented for the command, with a -// table scan per object read. Databricks' EXPLAIN COST answers one row, column `plan`: Spark's tree string, each node -// suffixed with `Statistics(sizeInBytes=…[, rowCount=…])` as Statistics.simpleString and Utils.bytesToString write it. -const SNOWFLAKE_PLAN = JSON.stringify({ - GlobalStats: { partitionsTotal: 1240, partitionsAssigned: 37, bytesAssigned: 2_147_483_648 }, - Operations: [ - [ - { id: 0, operation: "Result", expressions: ["ORDERS.O_ORDERKEY", "CUSTOMER.C_NAME"] }, - { id: 1, parentOperators: [0], operation: "InnerJoin", expressions: ["joinKey: (CUSTOMER.C_CUSTKEY = ORDERS.O_CUSTKEY)"] }, - { - id: 2, - parentOperators: [1], - operation: "TableScan", - objects: ["ANALYTICS.PUBLIC.ORDERS"], - expressions: ["O_ORDERKEY", "O_CUSTKEY", "O_ORDERDATE"], - partitionsAssigned: 30, - partitionsTotal: 1200, - bytesAssigned: 2_000_000_000, - }, - { id: 3, parentOperators: [1], operation: "JoinFilter", expressions: ["joinKey: (CUSTOMER.C_CUSTKEY = ORDERS.O_CUSTKEY)"] }, - { - id: 4, - parentOperators: [3], - operation: "TableScan", - objects: ["ANALYTICS.PUBLIC.CUSTOMER"], - expressions: ["C_CUSTKEY", "C_NAME"], - partitionsAssigned: 7, - partitionsTotal: 40, - bytesAssigned: 147_483_648, - }, - ], - ], -}) - -const DATABRICKS_PLAN = [ - "== Optimized Logical Plan ==", - "Aggregate [o_custkey#12L], [o_custkey#12L, sum(o_totalprice#15) AS revenue#40], Statistics(sizeInBytes=1.2 MiB, rowCount=5.00E+4)", - "+- Project [o_custkey#12L, o_totalprice#15], Statistics(sizeInBytes=1.6 GiB)", - " +- Join Inner, (o_custkey#12L = c_custkey#30L), Statistics(sizeInBytes=3.0 GiB)", - " :- Filter (isnotnull(o_orderdate#16) AND (o_orderdate#16 >= 2024-01-01)), Statistics(sizeInBytes=2.5 GiB)", - " : +- Relation main.sales.orders[o_orderkey#11L,o_custkey#12L,o_totalprice#15,o_orderdate#16] parquet, Statistics(sizeInBytes=2.5 GiB, rowCount=1.50E+7)", - " +- Relation main.sales.customer[c_custkey#30L,c_name#31] parquet, Statistics(sizeInBytes=512.0 MiB)", - "", - "== Physical Plan ==", - "AdaptiveSparkPlan isFinalPlan=false", - "+- HashAggregate(keys=[o_custkey#12L], functions=[sum(o_totalprice#15)])", - " +- FileScan parquet main.sales.orders[o_custkey#12L] Batched: true, Statistics(sizeInBytes=99.0 EiB)", -].join("\n") - -describe("parseSnowflakeExplain", () => { - test("reads GlobalStats: the bytes and partitions left after pruning", () => { - expect(parseSnowflakeExplain(SNOWFLAKE_PLAN)).toEqual({ bytes: 2_147_483_648, partitionsAssigned: 37, partitionsTotal: 1240 }) - }) +const JOB_COLUMNS = ["job_id", "user_email", "creation_time", "end_time", "statement_type", "destination_table_id", "destination_dataset_id", "total_bytes_billed", "total_slot_ms", "reservation_id", "cache_hit"] +const CHILD_COLUMNS = ["job_id", "parent_job_id", "creation_time", "statement_type", "total_bytes_billed", "total_slot_ms", "reservation_id", "cache_hit"] +const TIB = 1024 ** 4 +const DEMAND = { value: 6.25, unit: "USD/TiB", source: "default" } +const job = ( + id: string, + start: string, + end: string, + billed: number | null, + reservation: string | null = null, + slotMs = 0, + type = "MERGE", + user = "a@x.com", + destination: string | null = null, + dataset: string | null = null, +) => [ + id, + user, + start, + end, + type, + destination, + dataset, + billed === null ? null : String(billed), + String(slotMs), + reservation, + "False", +] + +/** + * A history answer: `jobs` for the history query, `children` for the script-children query, and the capacity check + * counts `reserved` of `total` query jobs. `denyJobs` refuses the project-wide view, as a role without listAll is. + */ +const bigqueryHistory = + (jobs: (string | null)[][], opts: { reserved?: string; total?: string; children?: (string | null)[][]; denyJobs?: boolean } = {}) => + async (jinja: string) => { + if (opts.denyJobs && /INFORMATION_SCHEMA\.JOBS\n|INFORMATION_SCHEMA\.JOBS\s/.test(jinja.replace(/\\n/g, "\n")) && !jinja.includes("JOBS_BY_USER")) + throw new Error("Access Denied: Table region-eu.INFORMATION_SCHEMA.JOBS: User does not have permission") + if (jinja.includes("countif(reservation_id")) return table(["jobs", "reserved"], [[opts.total ?? "10", opts.reserved ?? "0"]]) + if (jinja.includes("parent_job_id in (")) return table(CHILD_COLUMNS, opts.children ?? []) + return table(JOB_COLUMNS, jobs) + } - test("takes the content already parsed", () => { - expect(parseSnowflakeExplain(JSON.parse(SNOWFLAKE_PLAN))).toEqual({ bytes: 2_147_483_648, partitionsAssigned: 37, partitionsTotal: 1240 }) +describe("dbt_cost_estimate cost", () => { + afterEach(() => { + costHistoryInternals.historyTimeoutMs = 60_000 }) - test("a query that reads no table is zero bytes", () => { - expect(parseSnowflakeExplain('{"GlobalStats":{"partitionsTotal":0,"partitionsAssigned":0,"bytesAssigned":0},"Operations":[[{"id":0,"operation":"Result"}]]}')).toEqual({ - bytes: 0, - partitionsAssigned: 0, - partitionsTotal: 0, + test("BigQuery on demand: earlier runs are read from the jobs view, a delete joins the build that follows it, and the cost leads the answer", async () => { + useAdapter(calls, { + history: bigqueryHistory([ + // The newest run: a delete and the merge that follows it. The older run is a day before. + job("a2", "2026-05-02 10:00:30+00:00", "2026-05-02 10:01:30+00:00", 2 * TIB), + job("a1", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", 1 * TIB, null, 0, "DELETE"), + job("b1", "2026-05-01 10:00:00+00:00", "2026-05-01 10:01:00+00:00", 4 * TIB), + ]), }) - }) - - test("bytes without partition counts are still an estimate", () => { - expect(parseSnowflakeExplain({ GlobalStats: { bytesAssigned: 1024 } })).toEqual({ bytes: 1024 }) - }) - - test.each([ - ["not JSON", "GlobalStats: 1024"], - ["no GlobalStats", '{"Operations":[]}'], - ["no bytesAssigned", '{"GlobalStats":{"partitionsTotal":3}}'], - ["text bytes", '{"GlobalStats":{"bytesAssigned":"1024"}}'], - ["negative bytes", '{"GlobalStats":{"bytesAssigned":-1}}'], - ["the tabular format", "step\tid\tparent\toperation"], - ["null", null], - ["a number", 1024], - ])("does not read %s", (_, content) => { - expect(parseSnowflakeExplain(content)).toBeUndefined() - }) -}) - -describe("parseDatabricksExplainCost", () => { - test("sums the leaves of the optimized plan: the relations it scans, not the operators above them", () => { - expect(parseDatabricksExplainCost(DATABRICKS_PLAN)).toEqual({ bytes: Math.round(2.5 * 1024 ** 3 + 512 * 1024 ** 2) }) - }) - - test("a single relation and Spark's B unit", () => { - const plan = "== Optimized Logical Plan ==\nProject [id#0L], Statistics(sizeInBytes=12.0 B)\n+- Relation main.t[id#0L] parquet, Statistics(sizeInBytes=16.0 B, rowCount=2)\n\n== Physical Plan ==\n*(1) ColumnarToRow" - expect(parseDatabricksExplainCost(plan)).toEqual({ bytes: 16 }) - }) - - test("a scalar subquery's plan is printed inside the tree, and its relation counts too", () => { - const plan = [ - "== Optimized Logical Plan ==", - "Project [id#1L, scalar-subquery#5 [] AS m#6L], Statistics(sizeInBytes=2.0 MiB)", - ": +- Aggregate [max(v#3L) AS max(v)#8L], Statistics(sizeInBytes=16.0 B, rowCount=1)", - ": +- Relation main.s.dim[v#3L] parquet, Statistics(sizeInBytes=3.0 MiB)", - "+- Relation main.s.fact[id#1L] parquet, Statistics(sizeInBytes=1.5 GiB)", - "", - "== Physical Plan ==", - ].join("\n") - expect(parseDatabricksExplainCost(plan)).toEqual({ bytes: Math.round(1.5 * 1024 ** 3 + 3 * 1024 ** 2) }) - }) - - test("reads Spark 2's KB/MB units and the scientific form past a long", () => { - expect(parseDatabricksExplainCost("== Optimized Logical Plan ==\nRelation[a#0] parquet, Statistics(sizeInBytes=2.0 MB, hints=none)")).toEqual({ - bytes: 2 * 1024 ** 2 , + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const cost = result.metadata.cost + expect(cost).toMatchObject({ + basis: "history", + currency: "USD", + runs: 2, + windowDays: 30, + lastRun: 3 * 6.25, + typical: (3 * 6.25 + 4 * 6.25) / 2, + highest: 4 * 6.25, + native: { unit: "bytes_billed", lastRun: 3 * TIB, highest: 4 * TIB }, + rate: { value: 6.25, unit: "USD/TiB", source: "default" }, }) - // A size past 2^62 is Spark's "no statistics" default or larger: not a size. - expect(parseDatabricksExplainCost("== Optimized Logical Plan ==\nRelation[a#0] parquet, Statistics(sizeInBytes=1.23E+21 B)")).toEqual({ noStats: true }) - }) - - test("a relation without statistics shows Spark's default size, Long.MaxValue: no estimate, not 8 EiB", () => { - const plan = "== Optimized Logical Plan ==\nJoin Inner, Statistics(sizeInBytes=8.0 EiB)\n:- Relation main.a[x#1] parquet, Statistics(sizeInBytes=1.0 GiB)\n+- Relation jdbc.b[x#2] JDBCRelation, Statistics(sizeInBytes=8.0 EiB)" - expect(parseDatabricksExplainCost(plan)).toEqual({ noStats: true, relation: "jdbc.b" }) - }) - - test("a leaf with no statistics at all is no estimate", () => { - expect(parseDatabricksExplainCost("== Optimized Logical Plan ==\nProject [a#0], Statistics(sizeInBytes=1.0 KiB)\n+- Relation main.t[a#0] parquet")).toEqual({ noStats: true, relation: "main.t", unread: true }) - }) - - test.each([ - ["no optimized plan section", "== Physical Plan ==\n*(1) Scan"], - ["an empty section", "== Optimized Logical Plan ==\n\n== Physical Plan ==\nScan"], - ["not text", { plan: "x" }], - ["null", null], - ])("does not read %s", (_, plan) => { - expect(parseDatabricksExplainCost(plan)).toBeUndefined() - }) - - test("reads Windows line endings", () => { - expect(parseDatabricksExplainCost("== Optimized Logical Plan ==\r\nRelation main.t[a#0] parquet, Statistics(sizeInBytes=4.0 KiB)\r\n")).toEqual({ bytes: 4096 }) - }) -}) - -describe("explainJinja", () => { - test("runs the EXPLAIN through dbt's run_query and renders its first column as JSON", () => { - expect(explainJinja("EXPLAIN COST", "select 1")).toBe( - "{%- if execute -%}{%- set altimate_plan = run_query('EXPLAIN COST\nselect 1') -%}{{ tojson(altimate_plan.columns[0].values() | list) }}{%- else -%}[]{%- endif -%}", - ) - }) - - test("at dbt's parse pass (execute false) it runs nothing and renders an empty list, not an error", () => { - // dbt compile --inline renders the query at parse first, where run_query returns None: reading its columns there failed. - const template = explainJinja("EXPLAIN USING JSON", "select 1") - const parsePass = /^\{%- if execute -%\}[\s\S]*\{%- else -%\}([\s\S]*)\{%- endif -%\}$/.exec(template) - expect(parsePass?.[1]).toBe("[]") - expect(template.indexOf("run_query")).toBeLessThan(template.indexOf("{%- else -%}")) + const bytes = Math.round(4.2 * TIB) + // The SELECT's price is an estimate: the dry run's parsed bytes at the on-demand rate, with no bound fields. + expect(cost.selectOnly).toEqual({ estimate: (bytes / TIB) * 6.25 }) + expect(result.output.startsWith("Cost from 2 runs in the last 30 days: last run $18.75")).toBe(true) + expect(result.output).toContain("would process 4.2 TiB") + expect(result.metadata).toMatchObject({ supported: true, bytes, display: "4.2 TiB", model: "orders" }) + }) + + test("the scan figure is computed first: no adapter call for the target or the history starts before the dry run has finished", async () => { + let dryRunDone = false + const started: boolean[] = [] + const base = fakeAdapter(calls, { history: bigqueryHistory([]) }) + useAdapter(calls) + dbtAdapterInternals.create = async () => ({ + ...base, + unsafeCompileQuery: async (q: string, name?: string) => { + if (q.startsWith('{{ tojson({"project"') || q.startsWith("{%- if execute -%}{%- set altimate_rows")) started.push(dryRunDone) + return base.unsafeCompileQuery(q, name) + }, + validateSQLDryRun: async (q: string) => { + const answer = await base.validateSQLDryRun(q) + // Hold the dry run: a lookup that started beside it would see dryRunDone still false. + await new Promise((r) => setTimeout(r, 25)) + dryRunDone = true + return answer + }, + }) + await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(started.length).toBeGreaterThan(1) + expect(started.every(Boolean)).toBe(true) }) - test("escapes quotes and backslashes for the Jinja string, and drops a trailing semicolon", () => { - expect(explainJinja("EXPLAIN USING JSON", "select * from t where s = 'a\\b';\n")).toContain("run_query('EXPLAIN USING JSON\nselect * from t where s = \\'a\\\\b\\'')") + test("a history that fails never changes the scan figure", async () => { + useAdapter(calls, {}) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata).toMatchObject({ success: true, bytes: Math.round(4.2 * TIB), display: "4.2 TiB" }) }) -}) -describe("dbt_cost_estimate on a warehouse with a planner", () => { - const rendered = (row: unknown) => async () => JSON.stringify([row]) - - test("Snowflake: compiles the model, then EXPLAINs it, and answers the bytes assigned as an upper bound", async () => { - useAdapter(calls, { type: "snowflake", explain: rendered(SNOWFLAKE_PLAN) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(calls.nodes).toEqual(["orders"]) - expect(calls.queries).toEqual([[explainJinja("EXPLAIN USING JSON", "compiled(orders)"), undefined]]) - expect(calls.dryRuns).toEqual([]) - expect(result.metadata).toEqual({ - success: true, - supported: true, - adapter: "snowflake", - source: "explain", - bound: "upper", - bytes: 2_147_483_648, - display: "2.0 GiB", - partitionsAssigned: 37, - partitionsTotal: 1240, - model: "orders", - truncated: false, + test("BigQuery asks the project and region of the dbt target, for exactly this model's unique_id", async () => { + useAdapter(calls, { + history: bigqueryHistory([]), + target: '{"project": "data", "execution_project": "billing-proj", "location": "EU"}', }) - expect(result.output).toContain("orders would scan about 2.0 GiB, by Snowflake's plan estimate (37 of 1240 partitions after pruning; an upper bound") + await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const sql = historyLog.find((q) => q.includes("total_bytes_billed") && q.includes("strpos"))! + expect(sql).toContain("`billing-proj`.`region-eu`.INFORMATION_SCHEMA.JOBS") + // Inside the Jinja string the SQL's own quotes are escaped once more. + expect(sql).toContain("strpos(query, \\'\"node_id\": \"model.shop.orders\"\\') > 0") + expect(sql).toContain("parent_job_id is null") }) - test("Databricks: estimates inline SQL from EXPLAIN COST, as an estimate, not a bound", async () => { - useAdapter(calls, { type: "databricks", explain: rendered(DATABRICKS_PLAN) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select * from {{ ref('orders') }}" }, ctx) - expect(calls.queries).toEqual([ - ["select * from {{ ref('orders') }}", undefined], - [explainJinja("EXPLAIN COST", "compiled(select * from {{ ref('orders') }})"), undefined], - ]) - expect(result.metadata).toEqual({ - success: true, - supported: true, - adapter: "databricks", - source: "explain", - bound: "estimate", - bytes: Math.round(2.5 * 1024 ** 3 + 512 * 1024 ** 2), - display: "3.0 GiB", - truncated: false, + test("BigQuery capacity jobs are priced by slot time, with the caveat", async () => { + useAdapter(calls, { + history: bigqueryHistory([job("c1", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", 5 * TIB, "res-1", 7_200_000)], { reserved: "3" }), }) - expect(result.output).toContain("not a bound either way") - }) - - test("Databricks without table statistics: no estimate, and says why", async () => { - useAdapter(calls, { type: "databricks", explain: rendered("== Optimized Logical Plan ==\nRelation x.y[a#1] parquet, Statistics(sizeInBytes=8.0 EiB)") }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(result.metadata).toEqual({ success: false, adapter: "databricks", source: "explain", error: expect.stringContaining("no size for x.y"), truncated: false }) - expect(result.metadata.bytes).toBeUndefined() - expect(result.output).toContain("ANALYZE TABLE x.y COMPUTE STATISTICS NOSCAN") - expect(result.output).toContain("no size for x.y") - }) - - test("an EXPLAIN the warehouse refuses is no estimate, with the warehouse's error", async () => { - useAdapter(calls, { type: "snowflake", explain: async () => Promise.reject(new Error("SQL compilation error: Object 'ORDERS' does not exist")) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(result.title).toBe("dbt_cost_estimate: explain failed") - expect(result.metadata).toMatchObject({ success: false, adapter: "snowflake", source: "explain" }) - expect(result.output).toContain("does not exist") + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const cost = result.metadata.cost + expect(cost).toMatchObject({ + basis: "history", + lastRun: 2 * 0.06, + native: { unit: "slot_hours", lastRun: 2 }, + rate: { value: 0.06, unit: "USD/slot-hour", source: "default" }, + }) + expect(cost.notes.join(" ")).toContain("an allocation, not the bill") }) - test.each([ - ["a plan it can't read", JSON.stringify(['{"Operations":[]}'])], - ["no rows", "[]"], - ["text that is not JSON", "EXPLAIN output"], - ])("%s is no estimate, never a count", async (_, out) => { - useAdapter(calls, { type: "snowflake", explain: async () => out }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(result.metadata.success).toBe(false) - expect(result.metadata.bytes).toBeUndefined() + test("BigQuery: a temporary CTAS into one dataset and a MERGE into another five minutes later are two runs through the tool", async () => { + const tmpJob = (dataset: string) => job("t", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB, null, 0, "CREATE_TABLE_AS_SELECT", "a@x.com", "orders__dbt_tmp", dataset) + const merge = (dataset: string) => job("m", "2026-05-02 10:06:00+00:00", "2026-05-02 10:07:00+00:00", TIB, null, 0, "MERGE", "a@x.com", null, dataset) + useAdapter(calls, { history: bigqueryHistory([merge("dev"), tmpJob("prod")]) }) + expect((await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx)).metadata.cost.runs).toBe(2) + resetDbtAdapter() + useAdapter(calls, { history: bigqueryHistory([merge("prod"), tmpJob("prod")]) }) + expect((await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx)).metadata.cost.runs).toBe(1) }) - test("a model that doesn't compile is not EXPLAINed", async () => { - useAdapter(calls, { type: "snowflake", compileFails: true, explain: rendered(SNOWFLAKE_PLAN) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "nope" }, ctx) - expect(result.title).toBe("dbt_cost_estimate: compile failed") - expect(calls.queries).toEqual([]) + test("BigQuery: the CTAS into dbt's temporary relation and the MERGE after it are one run through the tool", async () => { + useAdapter(calls, { + history: bigqueryHistory([ + job("m", "2026-05-02 10:03:00+00:00", "2026-05-02 10:04:00+00:00", 2 * TIB), + job("t", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB, null, 0, "CREATE_TABLE_AS_SELECT", "a@x.com", "orders__dbt_tmp"), + ]), + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata.cost).toMatchObject({ basis: "history", runs: 1 }) + expect(result.metadata.cost.lastRun).toBeCloseTo(18.75, 10) }) - test("a cancelled call stops waiting for the EXPLAIN", async () => { - const abort = new AbortController() - let started!: () => void - const explaining = new Promise((resolve) => (started = resolve)) + test("script children are read from the earliest parent's creation, so a child cannot slide out of a moving window", async () => { + const parent = Date.parse("2026-05-02T10:00:01Z") + const kids = [ + ["k1", "p1", "2026-05-02 10:00:03+00:00", "CREATE_TABLE_AS_SELECT", String(TIB), "0", null, "False"], + ["k2", "p1", "2026-05-02 10:00:11+00:00", "MERGE", String(TIB), "0", null, "False"], + ] useAdapter(calls, { - type: "databricks", - explain: () => { - started() - return new Promise(() => {}) + history: async (jinja) => { + if (!jinja.includes("parent_job_id in (")) return bigqueryHistory([job("p1", "2026-05-02 10:00:01+00:00", "2026-05-02 10:00:20+00:00", 9 * TIB, null, 0, "SCRIPT")])(jinja) + // An adapter consistent with the SQL: a lower bound at the parent's creation keeps both children; a sliding + // window (current_timestamp minus 30 days) has already moved 5 s past the parent's start and loses the first. + const fixed = /creation_time >= timestamp_millis\((\d+)\)/.exec(jinja) + const lower = fixed ? Number(fixed[1]) : parent + 5_000 + return table(CHILD_COLUMNS, kids.filter((k) => Date.parse(String(k[2]).replace(" ", "T")) >= lower)) }, }) - const run = (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, { ...ctx, abort: abort.signal }) - // Cancelled once the EXPLAIN is under way, not before it starts. - await explaining - abort.abort(new Error("cancelled")) - await expect(run).rejects.toThrow("cancelled") - }) -}) - -describe("follow-ups to the planner estimate", () => { - const rendered = (row: unknown) => async () => JSON.stringify([row]) - const originalTimeout = dbtCostEstimateInternals.explainTimeoutMs - afterEach(() => { - dbtCostEstimateInternals.explainTimeoutMs = originalTimeout - }) - - test("an EXPLAIN that outlasts its deadline is no estimate, and the call stops waiting", async () => { - dbtCostEstimateInternals.explainTimeoutMs = 50 - useAdapter(calls, { type: "databricks", explain: () => new Promise(() => {}) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(result.title).toBe("dbt_cost_estimate: explain failed") - expect(result.output).toContain("did not answer within 0.05 s") - expect(result.metadata.bytes).toBeUndefined() - }) - - test("an EXPLAIN that answers within its deadline is read as before", async () => { - dbtCostEstimateInternals.explainTimeoutMs = 5_000 - useAdapter(calls, { type: "snowflake", explain: rendered(SNOWFLAKE_PLAN) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(result.metadata.bytes).toBe(2_147_483_648) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata.cost).toMatchObject({ runs: 1 }) + expect(result.metadata.cost.lastRun).toBeCloseTo(12.5, 10) }) - test.each([ - ["a multi-line block comment", "select 1; /* a\nb */", "select 1"], - ["a second semicolon and a comment", "select 1;; -- c", "select 1"], - ["a comment on the next line", "select 1;\n-- done\n", "select 1"], - ])("Snowflake sends %s after the final semicolon to nobody", async (_, compiled, sent) => { - expect(mayBeScript(compiled, "snowflake")).toBe(false) - useAdapter(calls, { type: "snowflake", compile: async () => compiled, explain: rendered(SNOWFLAKE_PLAN) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(calls.queries).toEqual([[explainJinja("EXPLAIN USING JSON", sent), undefined]]) - expect(result.metadata.success).toBe(true) + test("the tool description calls the cost reported usage at a stated rate, not what the warehouse billed", async () => { + const tool = await initTool(DbtCostEstimateTool) + expect(tool.description).not.toContain("what the warehouse billed") + expect(tool.description).toContain("stated rate") + expect(tool.description).toContain("not an invoice amount") + }) + + test("the SELECT's price is in the output beside the history it is a note about", async () => { + useAdapter(calls, { history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "mart", history: true }, ctx) + expect(result.output).toContain("Cost from 1 run") + expect(result.output).toContain("BigQuery's dry run estimates the SELECT at") + expect(result.output).toContain("The price covers the SELECT only") + }) + + test("the manifest the adapter reports is the one the model is looked up in", async () => { + await using tmp = await tmpdir() + const file = path.join(tmp.path, "manifest.json") + await writeFile(file, JSON.stringify({ nodes: { "model.other.custom": { resource_type: "model", name: "custom", config: {}, depends_on: { nodes: [] } } }, sources: {} })) + useAdapter(calls, { manifestPath: file, history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "custom", history: true }, ctx) + expect(result.metadata.cost).toMatchObject({ basis: "history", runs: 1 }) + expect(historyLog.some((q) => q.includes("model.other.custom"))).toBe(true) + }) + + test("a manifest that cannot be read leaves the scan figure and names the problem", async () => { + await using tmp = await tmpdir() + const file = path.join(tmp.path, "manifest.json") + await writeFile(file, "{ broken") + useAdapter(calls, { manifestPath: file, history: bigqueryHistory([]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata).toMatchObject({ success: true, bytes: Math.round(4.2 * TIB) }) + expect(why(result.metadata.cost)).toContain("could not be read") + // The headline says the history is unknown; a dry-run price, if any, is its own line. + expect(result.metadata.cost.basis).toBe("none") + expect(result.output.split("\n")[0]).toContain("Cost unknown:") + }) + + test("a script is priced from its child jobs, which carry the reservation the script row lacks", async () => { + useAdapter(calls, { + history: bigqueryHistory([job("p1", "2026-05-02 10:00:00+00:00", "2026-05-02 10:05:00+00:00", 9 * TIB, null, 0, "SCRIPT")], { + reserved: "2", + children: [ + ["k1", "p1", "2026-05-02 10:00:10+00:00", "CREATE_TABLE_AS_SELECT", "0", "3600000", "res", "False"], + ["k2", "p1", "2026-05-02 10:01:00+00:00", "MERGE", "0", "3600000", "res", "False"], + ], + }), + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const cost = result.metadata.cost + expect(cost).toMatchObject({ runs: 1, native: { unit: "slot_hours", lastRun: 2 } }) + expect(cost.lastRun).toBeCloseTo(0.12, 10) + expect(historyLog.some((q) => q.includes("parent_job_id in (\\'p1\\')"))).toBe(true) + }) + + test("a project on capacity pricing does not get the dry run priced", async () => { + useAdapter(calls, { history: bigqueryHistory([], { reserved: "5" }) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const cost = result.metadata.cost + expect(cost.selectOnly).toBeUndefined() + expect(cost.basis).toBe("none") + expect(cost.notes.join(" ")).toContain("capacity pricing") + expect(result.output).toContain("would process 4.2 TiB") + expect(cost.rate).toBeNull() + expect(result.output).not.toContain("Rate:") + }) + + test("an on-demand dry run is priced as an estimate from the parsed bytes, not the rounded display, and says it covers the SELECT only", async () => { + useAdapter(calls, { bytes: "1.0 KiB", history: bigqueryHistory([]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "stg_orders", history: true }, ctx) + const cost = result.metadata.cost + // The history found no run: that is the headline, and the dry-run price is a separate, labelled line. + expect(cost.basis).toBe("none") + expect(result.output.split("\n")[0]).toContain("Cost unknown: No runs of model.shop.stg_orders") + expect(result.output).toContain("\nPre-run scan estimate (not the model's run history): BigQuery's dry run estimates") + // 1 KiB is below BigQuery's 10 MiB per-query minimum, which the estimate applies. + expect(cost.selectOnly).toEqual({ estimate: (10 * 1024 ** 2 / TIB) * 6.25 }) + expect(cost.notes.join(" ")).toContain("The price covers the SELECT only.") + expect(why(cost)).toContain("No runs of model.shop.stg_orders in the last 30 days") + expect(result.output).toContain("BigQuery's dry run estimates the SELECT at 1.0 KiB, about $0.000060 on-demand. BigQuery bills at least 10 MiB per query, which this estimate applies. The bill can differ: a cached or BI Engine result bills nothing, clustered tables often bill less after runtime pruning, and external sources and some queries are not fully counted.") + for (const claim of ["at most", "at least $", "ceiling", "floor", "perTable"]) expect(result.output).not.toContain(claim) }) test.each([ - ["select 'a;b' from t; -- c", "snowflake", "select 'a;b' from t"], - ["select \"a;b\" /* ; */ from t", "snowflake", 'select "a;b" /* ; */ from t'], - ["select `a;b` from t; /* x */", "databricks", "select `a;b` from t"], - ["select 1 -- not; a split", "snowflake", "select 1 -- not; a split"], - ["select 1", "snowflake", "select 1"], - ])("firstStatement(%p, %s) keeps what the driver sends as the statement", (sql, type, expected) => { - expect(firstStatement(sql, type)).toBe(expected) - }) - - test("a section heading inside a multi-line literal does not end the plan", () => { - const plan = [ - "== Optimized Logical Plan ==", - "Project [concat(w#1, ", - "== Physical Plan ==", - ") AS z#2], Statistics(sizeInBytes=1.0 KiB)", - "+- Relation spark_catalog.default.b[w#1] parquet, Statistics(sizeInBytes=2.0 GiB)", - "", - "== Physical Plan ==", - "*(1) Project", - ].join("\n") - expect(parseDatabricksExplainCost(plan)).toEqual({ bytes: 2 * 1024 ** 3 }) - }) - - test("a section heading after a finished node still ends the plan", () => { - const plan = "== Optimized Logical Plan ==\nRelation main.t[a#0] parquet, Statistics(sizeInBytes=4.0 KiB)\n\n== Physical Plan ==\nRelation main.u[a#0] parquet, Statistics(sizeInBytes=9.0 GiB)" - expect(parseDatabricksExplainCost(plan)).toEqual({ bytes: 4096 }) - }) - - test("brackets inside a printed name do not stretch a node over the plan's real end", () => { - const plan = "== Optimized Logical Plan ==\nRelation main.t[a(b#0] parquet, Statistics(sizeInBytes=2.0 GiB)\n\n== Physical Plan ==\nFileScan parquet main.t[a(b#0]" - expect(parseDatabricksExplainCost(plan)).toEqual({ bytes: 2 * 1024 ** 3 }) - }) - - test("Snowflake: a scan of an external table or stage, or a scan with no size, keeps the total from being a cap", () => { - const mixed = (extra: object) => - JSON.stringify({ - GlobalStats: { bytesAssigned: 1024 }, - Operations: [[{ id: 1, operation: "TableScan", objects: ["T"], bytesAssigned: 1024 }, { id: 2, ...extra }]], - }) - expect(parseSnowflakeExplain(mixed({ operation: "ExternalScan", bytesAssigned: 0 }))).toEqual({ bytes: 1024, unsized: true }) - expect(parseSnowflakeExplain(mixed({ operation: "StageScan" }))).toEqual({ bytes: 1024, unsized: true }) - expect(parseSnowflakeExplain(mixed({ operation: "TableScan", objects: ["U"], bytesAssigned: 0 }))).toEqual({ bytes: 1024, unsized: true }) - expect(parseSnowflakeExplain(mixed({ operation: "SecureView", objects: ["V"] }))).toEqual({ bytes: 1024, unsized: true }) - expect(parseSnowflakeExplain(mixed({ operation: "DynamicSecureView" }))).toEqual({ bytes: 1024, unsized: true }) - // A secure view hides what it scans, so a total of 0 beside one is not a cap either. - expect(parseSnowflakeExplain('{"GlobalStats":{"bytesAssigned":0},"Operations":[[{"id":1,"operation":"SecureView"}]]}')).toEqual({ bytes: 0, unsized: true }) - expect(parseSnowflakeExplain(mixed({ operation: "TableScan", objects: ["U"] }))).toEqual({ bytes: 1024, unsized: true }) - expect(parseSnowflakeExplain(mixed({ operation: "Filter" }))).toEqual({ bytes: 1024 }) - expect(parseSnowflakeExplain(SNOWFLAKE_PLAN)).toEqual({ bytes: 2_147_483_648, partitionsAssigned: 37, partitionsTotal: 1240 }) - }) - - test("Snowflake: a positive total beside an external scan is not called an upper bound", async () => { - const plan = JSON.stringify({ - GlobalStats: { partitionsTotal: 2, partitionsAssigned: 2, bytesAssigned: 1024 }, - Operations: [[{ id: 1, operation: "TableScan", objects: ["T"], bytesAssigned: 1024 }, { id: 2, operation: "ExternalScan", objects: ["E"] }]], + ["a script", "select 1; select * from big", "1.0 GiB", "A script's dry run can skip statements or omit work that happens at run time, so it is not priced."], + ["a zero estimate", "select 1", 0, "The dry run reported 0 bytes, which BigQuery also reports for row-level security, external (federated) tables and cached results"], + ])("%s: a dry run that is only a lower bound is not priced, with its own reason", async (_name, sql, bytes, reason) => { + useAdapter(calls, { bytes, history: bigqueryHistory([]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ sql, history: true }, ctx) + const cost = result.metadata.cost + expect(result.metadata).toMatchObject({ lowerBound: true }) + expect(cost.selectOnly).toBeUndefined() + expect(cost.basis).toBe("none") + expect(cost.notes.join(" ")).toContain(reason) + // The other reason does not apply. + const other = reason.startsWith("A script") ? "reported 0 bytes" : "can skip statements" + expect(cost.notes.join(" ")).not.toContain(other) + }) + + test("when neither the project's jobs nor the caller's own say the pricing mode, the dry run is not priced and the scan stays", async () => { + useAdapter(calls, { + history: async (jinja) => { + if (jinja.includes("countif(reservation_id")) throw new Error("boom") + return table(JOB_COLUMNS, []) + }, }) - useAdapter(calls, { type: "snowflake", explain: rendered(plan) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select * from t join e" }, ctx) - expect(result.metadata).toMatchObject({ success: true, bound: "unknown", bytes: 1024 }) - expect(result.output).not.toContain("an upper bound") - }) - - test("a leaf that holds an inner plan keeps its own size", () => { - const plan = [ - "== Optimized Logical Plan ==", - "Relation main.s.t[a#0] parquet, Statistics(sizeInBytes=2.0 GiB)", - ": +- Relation main.s.u[a#1] parquet, Statistics(sizeInBytes=3.0 GiB)", - ].join("\n") - expect(parseDatabricksExplainCost(plan)).toEqual({ bytes: 5 * 1024 ** 3 }) - }) - - test("a leaf with an inner plan but no size of its own is no estimate, not the inner plan's size", () => { - const plan = [ - "== Optimized Logical Plan ==", - "Relation main.s.t[a#0] parquet", - ": +- Relation main.s.u[a#1] parquet, Statistics(sizeInBytes=3.0 GiB)", - ].join("\n") - expect(parseDatabricksExplainCost(plan)).toEqual({ noStats: true, relation: "main.s.t", unread: true }) - }) - - test("an EXPLAIN that rejects after its deadline changes nothing", async () => { - dbtCostEstimateInternals.explainTimeoutMs = 30 - let reject!: (e: Error) => void - useAdapter(calls, { type: "snowflake", explain: () => new Promise((_, r) => (reject = r)) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(result.title).toBe("dbt_cost_estimate: explain failed") - reject(new Error("late")) - await new Promise((resolve) => setTimeout(resolve, 20)) - expect(result.metadata.success).toBe(false) - expect(result.output).toContain("did not answer within 0.03 s") - expect(result.output).not.toContain("late") + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "stg_orders", history: true }, ctx) + const cost = result.metadata.cost + expect(cost.selectOnly).toBeUndefined() + expect(cost.basis).toBe("none") + expect(cost.unknownReason).toContain("BigQuery pricing mode could not be read (on-demand vs reservations)") + expect(result.metadata).toMatchObject({ success: true, bytes: Math.round(4.2 * TIB) }) }) - test("a node with a child and an inner plan is still not a leaf", () => { - const plan = [ - "== Optimized Logical Plan ==", - "Filter (a#0 IN (list#5 [])), Statistics(sizeInBytes=1.0 GiB)", - ": +- Relation main.s.u[a#1] parquet, Statistics(sizeInBytes=3.0 GiB)", - "+- Relation main.s.t[a#0] parquet, Statistics(sizeInBytes=2.0 GiB)", - ].join("\n") - expect(parseDatabricksExplainCost(plan)).toEqual({ bytes: 5 * 1024 ** 3 }) + test("no query job in the last week is no pricing mode either", async () => { + useAdapter(calls, { history: bigqueryHistory([], { total: "0" }) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "stg_orders", history: true }, ctx) + expect(result.metadata.cost.selectOnly).toBeUndefined() + expect(result.metadata.cost.unknownReason).toContain("pricing mode could not be read") }) - test("Snowflake's 0 bytes is not called an upper bound: it also reports 0 for a source it cannot size", async () => { - useAdapter(calls, { type: "snowflake", explain: rendered('{"GlobalStats":{"partitionsTotal":0,"partitionsAssigned":0,"bytesAssigned":0}}') }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select $1 from @stage" }, ctx) - expect(result.metadata).toMatchObject({ success: true, bound: "unknown", bytes: 0 }) - expect(result.output).toContain("not a cap") - expect(result.output).not.toContain("an upper bound") + test("a role without listAll falls back to its own jobs and says only its own runs were read", async () => { + useAdapter(calls, { + history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)], { denyJobs: true }), + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const cost = result.metadata.cost + expect(historyLog.some((q) => q.includes("JOBS_BY_USER") && q.includes("strpos"))).toBe(true) + expect(cost).toMatchObject({ basis: "history", lastRun: 6.25 }) + expect(cost.scope).toBe("user") + // The first line of the answer says whose jobs were read, ahead of any figure. + expect(result.output.split("\n")[0]).toBe("Only your own jobs were read (no bigquery.jobs.listAll): service-account and other users' runs are missing.") }) - test("a leaf with no readable size gets no ANALYZE advice: it is not known to lack statistics", async () => { - useAdapter(calls, { type: "databricks", explain: rendered("== Optimized Logical Plan ==\nRelation main.t[a#0] parquet") }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(result.metadata.success).toBe(false) - expect(result.output).toContain("printed no size this tool can read for main.t") - expect(result.output).not.toContain("ANALYZE") + test("a history the role cannot read at all leaves the scan figure and says what is missing", async () => { + useAdapter(calls, { + history: async () => { + throw new Error("Access Denied: Table region-eu.INFORMATION_SCHEMA.JOBS: User does not have permission") + }, + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata).toMatchObject({ success: true, supported: true, bytes: Math.round(4.2 * TIB), display: "4.2 TiB" }) + const cost = result.metadata.cost + expect(cost.unknownReason).toContain("bigquery.jobs.listAll") + expect(cost.runs).toBeUndefined() + expect(result.output).toContain("would process 4.2 TiB") + }) + + test("a history that never answers is bounded, and the scan figure still comes back", async () => { + costHistoryInternals.historyTimeoutMs = 30 + useAdapter(calls, { history: () => new Promise(() => {}) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata).toMatchObject({ success: true, bytes: Math.round(4.2 * TIB) }) + expect(result.metadata.cost.unknownReason).toContain("did not answer within 0.03 s") + }) + + test("SQL input has no history to read", async () => { + useAdapter(calls, { history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select 1", history: true }, ctx) + expect(historyLog.some((q) => q.includes("total_bytes_billed") && q.includes("strpos"))).toBe(false) + const cost = result.metadata.cost + expect(cost.basis).toBe("none") + expect(cost.runs).toBeUndefined() + expect(result.output.split("\n")[0]).toContain("Cost unknown: A SQL input has no run history") + expect(why(cost)).toContain("A SQL input has no run history") + // 4.2 TiB from the dry run's display, at the default $6.25 per TiB. + expect(cost.selectOnly).toEqual({ estimate: (Math.round(4.2 * TIB) / TIB) * 6.25 }) + }) + + test("a model name that matches two nodes is reported ambiguous and no history is read", async () => { + useAdapter(calls, { history: bigqueryHistory([]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "dup", history: true }, ctx) + expect(historyLog.some((q) => q.includes("total_bytes_billed") && q.includes("strpos"))).toBe(false) + const notes = why(result.metadata.cost) + expect(notes).toContain("model.other.dup") + expect(notes).toContain("model.shop.dup") + }) + + test("an incremental model's scan figure says it leaves out the MERGE; a table model's does not", async () => { + useAdapter(calls, { history: bigqueryHistory([]) }) + const tool = await initTool(DbtCostEstimateTool) + const incremental = (await tool.execute({ model: "orders", history: true }, ctx)).metadata + const table_ = (await tool.execute({ model: "stg_orders", history: true }, ctx)).metadata + expect(incremental.cost.notes.join(" ")).toContain("incremental") + expect(table_.cost.notes.join(" ")).not.toContain("incremental") }) -}) -describe("mayBeScript", () => { - test.each([ - ["snowflake", "select 1; delete from orders"], - ["snowflake", "select 1;\ndelete from orders;"], - ["snowflake", "select * from t where s = 'a'; drop table t"], - ["snowflake", "select $$a$$; delete from t"], - // Snowflake's own comment and dollar-quoted text are not set aside: a doubt counts as a script. - ["snowflake", "select 1 // note; delete from t"], - ["snowflake", "select $$a;b$$"], - ["snowflake", "execute immediate 'select 1'"], - ["snowflake", "select `a; b` from t"], - ["snowflake", "select 'unclosed; delete from t"], - ["databricks", "select 1; delete from orders"], - ["databricks", "select 1 # c; delete from t"], - // Found in review: text the scan does not model must not hide a separator the driver sees. - ["snowflake", "select $$--$$; delete from orders"], - ["snowflake", "select $$'$$; delete from orders -- '"], - ["snowflake", "select 1 // '\n; delete from orders -- '"], - ["snowflake", 'select "a\\" x" ; delete from orders; "'], - ["snowflake", "select 1 /* unclosed ; delete from orders"], - ["databricks", "select r'\\'; delete from orders -- '"], - ["databricks", "select 1 /* a /* b */ ; delete from orders */"], - ["snowflake", "select 1; -- one\ndelete from orders"], - ])("on %s, %p may be more than one statement", (type, sql) => { - expect(mayBeScript(sql, type)).toBe(true) + test("a rate from the config replaces the default and is named", async () => { + costHistoryInternals.readCostConfig = async () => ({ bigqueryUsdPerTib: 5 }) + try { + useAdapter(calls, { + history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)]), + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata.cost).toMatchObject({ lastRun: 5, rate: { value: 5, source: "config" } }) + } finally { + costHistoryInternals.readCostConfig = defaultReadCostConfig + } }) - test.each([ - ["snowflake", "select 1"], - ["snowflake", "select 1;\n "], - ["snowflake", "select 'a;b', \"x;y\" from t -- one; two\n/* three; */"], - ["snowflake", "select 'it''s; fine', 'a\\'; b' from t"], - ["databricks", "select `p;q`.c from t where s = 'a;b'"], - ["databricks", "with x as (select 1) select * from x;"], - ["snowflake", "select 1; -- done"], - ["snowflake", "select 'a\\'; b', \"c\\\"; d\" from t"], - ["databricks", "select array_join(arr, ';') from t -- x; y"], - ])("on %s, %p is one statement", (type, sql) => { - expect(mayBeScript(sql, type)).toBe(false) + test("one instant for the whole BigQuery call: capacity, history and boundary share it", async () => { + let asked = 0 + const asOf = Date.UTC(2026, 5, 1, 20, 0, 0) + costHistoryInternals.now = () => (asked++, asOf + asked * 5_000) + try { + useAdapter(calls, { + history: bigqueryHistory([job("p1", "2026-05-20 10:00:00+00:00", "2026-05-20 10:01:00+00:00", 9 * TIB, null, 0, "SCRIPT")], { + children: [["k1", "p1", "2026-05-20 10:00:05+00:00", "MERGE", String(TIB), "0", null, "False"]], + }), + }) + await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const start = asOf + 5_000 - 30 * 86_400_000 + expect(asked).toBe(1) + for (const q of historyLog) expect(q).not.toMatch(/current_(timestamp|date)/) + expect(historyLog.find((q) => q.includes("countif(reservation_id"))).toContain(`timestamp_millis(${asOf + 5_000 - 7 * 86_400_000})`) + expect(historyLog.find((q) => q.includes("strpos") && !q.includes("run boundary"))).toContain(`timestamp_millis(${start})`) + expect(historyLog.find((q) => q.includes("run boundary"))).toContain(`timestamp_millis(${start + 1})`) + } finally { + costHistoryInternals.now = defaultNow + } }) -}) -describe("dbt_cost_estimate refuses to EXPLAIN a script", () => { - for (const type of ["snowflake", "databricks"]) { - test(`on ${type}, a second statement is never sent: no estimate, and only the compile ran`, async () => { - useAdapter(calls, { type, explain: async () => JSON.stringify([SNOWFLAKE_PLAN]) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select 1; delete from orders" }, ctx) - expect(calls.queries).toEqual([["select 1; delete from orders", undefined]]) - expect(result.metadata).toMatchObject({ success: false, adapter: type, source: "explain" }) - expect(result.metadata.bytes).toBeUndefined() - expect(result.output).toContain("more than one statement") - }) - } -}) + describe("a statement that starts exactly at the window's start", () => { + // The main read takes statements after the window's start, so one exactly at it is only in the boundary read, which + // must reach it: an adapter consistent with the SQL returns a statement iff it starts before the literal it is given. + const asOf = Date.UTC(2026, 5, 1, 20, 0, 0) + const start = asOf - 30 * 86_400_000 + const iso = (ms: number) => new Date(ms).toISOString() + const before = (jinja: string, pattern: RegExp) => start < Number(pattern.exec(jinja)![1]) + const withNow = async (run: () => Promise) => { + costHistoryInternals.now = () => asOf + try { + await run() + } finally { + costHistoryInternals.now = defaultNow + } + } -describe("parseDatabricksExplainCost reads only the statistics Spark appends", () => { - test("a column named like statistics is not a size", () => { - expect(parseDatabricksExplainCost("== Optimized Logical Plan ==\nRelation main.t[Statistics(sizeInBytes=0.0 B)#0] parquet, Statistics(sizeInBytes=1.0 GiB)")).toEqual({ - bytes: 1024 ** 3 , + test("BigQuery", async () => { + await withNow(async () => { + useAdapter(calls, { + history: bigqueryHistory([job("m", iso(start + 30_000), iso(start + 90_000), TIB)]), + boundary: async (jinja) => + table(["job_id", "user_email", "creation_time", "end_time", "statement_type"], before(jinja, /creation_time < timestamp_millis\((\d+)\)/) ? [["edge", "a@x.com", iso(start), iso(start + 5_000), "DELETE"]] : []), + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + // The only run is left out, so the history is unknown. + expect(result.metadata.cost.runs).toBeUndefined() + expect(result.metadata.cost.basis).toBe("none") + expect(result.metadata.cost.notes.join(" ")).toContain("1 run that may have started before the period read was left out.") + }) }) }) - test("nor stands in for missing statistics, or for Spark's default size", () => { - expect(parseDatabricksExplainCost("== Optimized Logical Plan ==\nRelation main.t[Statistics(sizeInBytes=0.0 B)#0] parquet")).toEqual({ noStats: true, relation: "main.t", unread: true }) - expect(parseDatabricksExplainCost("== Optimized Logical Plan ==\nRelation [Statistics(sizeInBytes=0 B)#0] parquet, Statistics(sizeInBytes=8.0 EiB)")).toEqual({ noStats: true }) + describe("a boundary job that ended exactly a chain window before the cutoff", () => { + // 500 statements were returned, so the cutoff is the oldest one's start. An unread job that ended exactly the chain + // window before the oldest run still belongs to it (a gap of exactly the limit joins); one a millisecond earlier does + // not. An adapter consistent with the SQL returns a statement iff it is created before the start literal and ended at or + // after the chain literal. + // The oldest statement is five days before the as-of instant; the fillers follow it, 14.4 minutes apart, all after it. + const asOf = Date.UTC(2026, 4, 15) + const T0 = asOf - 5 * 86_400_000 + const step = 864_000 + const iso = (ms: number) => new Date(ms).toISOString() + const withNow = async (run: () => Promise) => { + costHistoryInternals.now = () => asOf + try { + await run() + } finally { + costHistoryInternals.now = defaultNow + } + } + const lit = (jinja: string, pattern: RegExp) => Number(pattern.exec(jinja)![1]) + + test.each([ + ["BigQuery chain window", 60_000, true], + ["BigQuery chain window, a millisecond earlier", 60_001, false], + ])("%s (a job that ended exactly that long before the cutoff)", async (_name, before, dropped) => { + await withNow(async () => { + const rows = [ + job("old", iso(T0), iso(T0 + 60_000), TIB), + ...Array.from({ length: 499 }, (_, i) => job(`f${i}`, iso(T0 + (i + 1) * step), iso(T0 + (i + 1) * step + 60_000), TIB, null, 0, "MERGE", `u${i}@x.com`)), + ] + useAdapter(calls, { + history: bigqueryHistory(rows), + boundary: async (jinja) => { + const s = lit(jinja, /creation_time < timestamp_millis\((\d+)\)/) + const d = lit(jinja, /end_time >= timestamp_millis\((\d+)\)/) + const ended = T0 - before + const created = ended - 1_000 + return table(["job_id", "user_email", "creation_time", "end_time", "statement_type"], created < s && ended >= d ? [["edge", "a@x.com", iso(created), iso(ended), "DELETE"]] : []) + }, + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata.cost.runs).toBe(dropped ? 499 : 500) + }) + }) }) -}) -describe("review follow-ups", () => { - test("a lone carriage return, which Jinja turns into a line break, cannot end a comment the check reads as running on", async () => { - for (const type of ["snowflake", "databricks"]) { - expect(mayBeScript("select 1 -- c\n; delete from orders", type)).toBe(true) - const local: Calls = { nodes: [], queries: [], dryRuns: [] } - useAdapter(local, { type, compile: async () => "select 1 -- comment\r; delete from orders", explain: async () => JSON.stringify([SNOWFLAKE_PLAN]) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(local.queries).toEqual([]) - expect(result.metadata).toMatchObject({ success: false, source: "explain" }) - expect(result.output).toContain("more than one statement") + test("without history, no INFORMATION_SCHEMA query is sent and the answer is the scan figure with no cost", async () => { + let configReads = 0 + costHistoryInternals.readCostConfig = async () => (configReads++, undefined) + try { + useAdapter(calls, { history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)]) }) + const tool = await initTool(DbtCostEstimateTool) + for (const args of [{ model: "orders" }, { model: "orders", history: false }]) { + const result = await tool.execute(args, ctx) + expect(result.metadata).toMatchObject({ success: true, supported: true, bytes: Math.round(4.2 * TIB), display: "4.2 TiB", model: "orders" }) + expect(result.metadata.cost).toBeUndefined() + expect(result.output.startsWith("orders would process 4.2 TiB")).toBe(true) + } + expect(historyLog).toEqual([]) + expect(targetReads).toBe(0) + expect(configReads).toBe(0) + expect(calls.dryRuns).toHaveLength(2) + } finally { + costHistoryInternals.readCostConfig = defaultReadCostConfig } }) - test("the SQL sent is the one checked: line endings are already line breaks", async () => { - useAdapter(calls, { type: "snowflake", compile: async () => "select 1\r\nfrom t\rwhere x", explain: async () => JSON.stringify([SNOWFLAKE_PLAN]) }) - await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(calls.queries).toEqual([[explainJinja("EXPLAIN USING JSON", "select 1\nfrom t\nwhere x"), undefined]]) + test("the tool description says when to pass history and that it runs billed INFORMATION_SCHEMA queries", async () => { + const { description } = await initTool(DbtCostEstimateTool) + expect(description).toContain("Pass `history: true` when the user asks what a model costs") + expect(description).toContain("billed INFORMATION_SCHEMA.JOBS queries") + expect(description).toContain("never cached") + expect(description).not.toMatch(/price range|upper bound|price bound|bound on the (bill|price)/i) }) - test("only Spark's own section headers end the optimized plan", () => { - const plan = [ - "== Optimized Logical Plan ==", - "Union, Statistics(sizeInBytes=2.0 GiB)", - ":- Project [concat(a#1, ==, note ==) AS x#3], Statistics(sizeInBytes=1.0 GiB)", - "== note ==", - ": +- Relation main.s.a[a#1] parquet, Statistics(sizeInBytes=1.0 GiB)", - "+- Relation main.s.b[b#2] parquet, Statistics(sizeInBytes=1.0 GiB)", - "", - "== Physical Plan ==", - "Union", - ].join("\n") - // The stray line is the rest of the Project above it, not the end of the plan and not a node: the two relations, exactly. - expect(parseDatabricksExplainCost(plan)).toEqual({ bytes: 2 * 1024 ** 3 }) + test("a model's reservation runs against a 7-day check that sees only on-demand jobs name the disagreement", async () => { + useAdapter(calls, { + history: bigqueryHistory([job("c1", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", 5 * TIB, "res-1", 7_200_000)], { reserved: "0" }), + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const notes = result.metadata.cost.notes.join(" ") + expect(notes).toContain("runs include reservation jobs, but the project's jobs of the last 7 days were all on demand") + // The fail-safe stays: the dry run is not priced. + expect(result.metadata.cost.selectOnly).toBeUndefined() }) -}) -describe("review follow-ups, round four", () => { - test.each([ - ["snowflake", "select 1\n!foo"], - ["snowflake", "!set x=1\nselect 1"], - ["snowflake", "select 1 /* outer /* inner */ */"], - ["databricks", "select 1 /* outer /* inner */ */"], - ])("on %s, %p is not read: no estimate", (type, sql) => { - expect(mayBeScript(sql, type)).toBe(true) - }) - - for (const [type, compiled] of [ - ["snowflake", "select 1\n!foo"], - ["snowflake", "select 1\r!foo"], - ["snowflake", "select 1\r\n!foo"], - ["snowflake", "select 1 /* outer /* inner */ */"], - ] as const) { - test(`on ${type}, ${JSON.stringify(compiled)} never reaches the EXPLAIN`, async () => { - const local: Calls = { nodes: [], queries: [], dryRuns: [] } - useAdapter(local, { type, compile: async () => compiled, explain: async () => JSON.stringify([SNOWFLAKE_PLAN]) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(local.queries).toEqual([]) - expect(result.metadata).toMatchObject({ success: false, source: "explain" }) + test("on-demand runs of the model against a 7-day check that sees reservation jobs name the disagreement", async () => { + useAdapter(calls, { + history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)], { reserved: "4" }), }) - } - - test("a ! inside a line is an operator, not a command", () => { - expect(mayBeScript("select a from t where a != 1", "snowflake")).toBe(false) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata.cost.notes.join(" ")).toContain("runs were all on demand, but the project's jobs of the last 7 days include reservation jobs") + expect(result.metadata.cost.selectOnly).toBeUndefined() }) -}) -describe("review follow-ups, round five", () => { - test.each([ - ["snowflake", "select 1; 'second\nstatement'"], - ["snowflake", 'select 1; "x"'], - ["databricks", "select 1; `x`"], - ["snowflake", "select 1 /*/*/"], - ["databricks", "select 1 /*/*/ ' */ */ ; delete from t -- '"], - ["snowflake", "select 1 -- c\r; delete from orders"], - ])("on %s, %p is not read: no estimate", (type, sql) => { - expect(mayBeScript(sql, type)).toBe(true) + test("agreeing history and 7-day check add no disagreement note", async () => { + useAdapter(calls, { history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata.cost.notes.join(" ")).not.toContain("may have changed") }) test.each([ - ["snowflake", "select 1;;\n"], - ["snowflake", "select 1; /* done */ -- really"], - ])("on %s, %p is one statement", (type, sql) => { - expect(mayBeScript(sql, type)).toBe(false) + ['{"project": "p1", "execution_project": null, "location": null}', "The target sets no location, so region-us was read"], + ['{"project": "p1", "execution_project": null, "location": "EU"}', "Location read: region-eu (the target's location)."], + ])("a no-runs answer names the location it read: %s", async (target, expected) => { + useAdapter(calls, { target, history: bigqueryHistory([]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const notes = why(result.metadata.cost) + expect(notes).toContain("No runs of model.shop.orders") + expect(notes).toContain(expected) }) - test("quoted text after a semicolon never reaches the EXPLAIN", async () => { - useAdapter(calls, { type: "snowflake", compile: async () => "select 1; 'second\nstatement'", explain: async () => JSON.stringify([SNOWFLAKE_PLAN]) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(calls.queries).toEqual([]) - expect(result.metadata).toMatchObject({ success: false, source: "explain" }) + test("an access failure names the location it read", async () => { + useAdapter(calls, { + target: '{"project": "p1", "execution_project": null, "location": null}', + history: async () => { + throw new Error("Access Denied: Table region-us.INFORMATION_SCHEMA.JOBS: User does not have permission") + }, + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata.cost.unknownReason).toContain("bigquery.jobs.listAll") + expect(result.metadata.cost.unknownReason).toContain("region-us was read") + }) + + test("a Python model is told it runs on Dataproc and never appears in JOBS, and no history query is sent", async () => { + useAdapter(calls, { history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "pymodel", history: true }, ctx) + expect(historyLog).toEqual([]) + expect(result.metadata.cost.runs).toBeUndefined() + expect([result.metadata.cost.unknownReason, ...result.metadata.cost.notes].join(" ")).toContain("A Python model runs on Dataproc, not as a BigQuery query job") + }) + + test("the current target's runs are the figures, the rest are in cost.otherTargets, and the scope is the project's", async () => { + const columns = [...JOB_COLUMNS, "target_name"] + const withTarget = (j: (string | null)[], target: string) => [...j, target] + const rows = [ + withTarget(job("p", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", 2 * TIB), "prod"), + withTarget(job("d1", "2026-05-03 10:00:00+00:00", "2026-05-03 10:01:00+00:00", TIB / 100), "dev"), + withTarget(job("d2", "2026-05-04 10:00:00+00:00", "2026-05-04 10:01:00+00:00", TIB / 100), "dev"), + ] + useAdapter(calls, { + target: '{"project": "p1", "execution_project": null, "location": "EU", "name": "prod"}', + history: async (jinja) => (jinja.includes("countif(reservation_id") ? table(["jobs", "reserved"], [["10", "0"]]) : table(columns, rows)), + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const cost = result.metadata.cost + expect(cost).toMatchObject({ basis: "history", runs: 1, lastRun: 12.5, target: "prod", scope: "project" }) + expect(cost.otherTargets).toEqual([{ target: "dev", runs: 2, typical: 0.0625, attribution: "bytes_billed", rate: DEMAND }]) + expect(result.output).toContain("Runs of other targets are not in these figures: dev: 2 runs") + expect(historyLog.find((q) => q.includes("total_bytes_billed"))).toContain("target_name") }) - test.each([ - ["a comma", "Relation main.sales.orders,archive[id#0] parquet, Statistics(sizeInBytes=8.0 EiB)"], - ["a hyphen", "Relation main.sales.my-table[id#0] parquet, Statistics(sizeInBytes=8.0 EiB)"], - ["a space", "Relation main.sales.my table[id#0] parquet, Statistics(sizeInBytes=8.0 EiB)"], - ["a Hive relation", "HiveTableRelation [`spark_catalog`.`default`.`t`, org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe], Statistics(sizeInBytes=8.0 EiB)"], - ])("a relation whose printed name has %s is not named: Spark prints it unquoted, so it may not be the whole name", (_, leaf) => { - expect(parseDatabricksExplainCost(`== Optimized Logical Plan ==\n${leaf}`)).toEqual({ noStats: true }) - }) - - test("a plain relation name is named in the advice", () => { - expect(parseDatabricksExplainCost("== Optimized Logical Plan ==\nRelation main.sales.orders[id#0] parquet, Statistics(sizeInBytes=8.0 EiB)")).toEqual({ - noStats: true, - relation: "main.sales.orders", + test("when only other targets have runs the headline says so; the dry-run price is its own labelled line, never the headline", async () => { + const columns = [...JOB_COLUMNS, "target_name"] + const dev = [...job("d", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB), "dev"] + useAdapter(calls, { + target: '{"project": "p1", "execution_project": null, "location": "EU", "name": "prod"}', + history: async (jinja) => (jinja.includes("countif(reservation_id") ? table(["jobs", "reserved"], [["10", "0"]]) : table(columns, [dev])), + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "stg_orders", history: true }, ctx) + const cost = result.metadata.cost + expect(cost.basis).toBe("none") + expect(cost.unknownReason).toContain("No run of model.shop.stg_orders on the current target (prod)") + expect(cost.selectOnly).toEqual({ estimate: expect.any(Number) }) + const lines = result.output.split("\n") + expect(lines[0]).toContain("Cost unknown: No run of model.shop.stg_orders on the current target (prod)") + expect(lines[0]).not.toContain("dry run") + expect(lines.some((l) => l.startsWith("Pre-run scan estimate (not the model's run history):"))).toBe(true) + }) + + test("a labelled run just after the window's start is not dropped by a time rule: it is complete when every job of its invocation was read", async () => { + await withNowAt(async (asOfMs) => { + const edge = asOfMs - 30 * 86_400_000 + const columns = [...JOB_COLUMNS, "state", "dbt_invocation_id"] + const run = ["m", "a@x.com", iso(edge + 3_600_000), iso(edge + 3_660_000), "MERGE", null, null, String(TIB), "0", null, "False", "DONE", "i1"] + useAdapter(calls, { history: async (jinja) => (jinja.includes("countif(reservation_id") ? table(["jobs", "reserved"], [["10", "0"]]) : table(columns, [run])) }) + const cost = (await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx)).metadata.cost + expect(cost.runs).toBe(1) + // The query asks for the invocation's jobs back to the 180 days JOBS keeps. + expect(historyLog.find((q) => q.includes("invocation jobs"))).toContain(`creation_time > timestamp_millis(${asOfMs - 180 * 86_400_000})`) }) }) -}) -describe("review follow-ups, round six", () => { - test("a node continued on a line of its own is one node: its size is not added as a leaf", () => { - const plan = [ - "== Optimized Logical Plan ==", - "Project [concat(a#1, line one", - "line two) AS x#3], Statistics(sizeInBytes=5.0 GiB)", - "+- Relation main.s.a[a#1] parquet, Statistics(sizeInBytes=1.0 GiB)", - ].join("\n") - expect(parseDatabricksExplainCost(plan)).toEqual({ bytes: 1024 ** 3 }) + test("a job of another target in the boundary read never drops a current-target run", async () => { + await withNowAt(async (asOfMs) => { + const edge = asOfMs - 30 * 86_400_000 + const columns = [...JOB_COLUMNS, "state", "target_name"] + const run = ["m", "a@x.com", iso(edge + 80 * 3_600_000), iso(edge + 80 * 3_600_000 + 60_000), "MERGE", null, null, String(TIB), "0", null, "False", "DONE", "prod"] + const BC = ["job_id", "user_email", "creation_time", "end_time", "state", "statement_type", "destination_table_id", "destination_dataset_id", "dbt_invocation_id", "target_name"] + const ask1 = async (target: string) => { + resetDbtAdapter() + useAdapter(calls, { + target: '{"project": "p1", "execution_project": null, "location": "EU", "name": "prod"}', + history: async (jinja) => (jinja.includes("countif(reservation_id") ? table(["jobs", "reserved"], [["10", "0"]]) : table(columns, [run])), + boundary: async () => table(BC, [["x", "a@x.com", iso(edge - 30_000), null, "RUNNING", "MERGE", null, null, null, target]]), + }) + return (await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx)).metadata.cost + } + expect((await ask1("dev")).runs).toBe(1) + expect((await ask1("prod")).notes).toContain("A run still in progress was left out.") + // A finished job just before the cutoff: an unlabelled prod run it could chain to is dropped only by a prod job. + const early = ["m", "a@x.com", iso(edge + 30_000), iso(edge + 90_000), "MERGE", null, null, String(TIB), "0", null, "False", "DONE", "prod"] + const ask2 = async (target: string) => { + resetDbtAdapter() + useAdapter(calls, { + target: '{"project": "p1", "execution_project": null, "location": "EU", "name": "prod"}', + history: async (jinja) => (jinja.includes("countif(reservation_id") ? table(["jobs", "reserved"], [["10", "0"]]) : table(columns, [early])), + boundary: async () => table(BC, [["x", "a@x.com", iso(edge - 120_000), iso(edge - 30_000), "DONE", "MERGE", null, null, null, target]]), + }) + return (await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx)).metadata.cost + } + expect((await ask2("dev")).runs).toBe(1) + expect((await ask2("prod")).notes.join(" ")).toContain("may have started before the period read") + expect(historyLog.find((q) => q.includes("run boundary"))).toContain("as target_name") + }) }) - test.each([ - "select * from read_files('/Volumes/c/s/v/raw', format => 'json')", - "select * from READ_FILES ('/Volumes/c/s/v/raw')", - "select * from cloud_files('/mnt/raw', 'json')", - "select * from json.`/Volumes/c/s/v/raw`", - "select * from parquet . `s3://bucket/path`", - ])("on Databricks, %p reads files to plan: no EXPLAIN is sent", async (compiled) => { - const local: Calls = { nodes: [], queries: [], dryRuns: [] } - useAdapter(local, { type: "databricks", compile: async () => compiled, explain: async () => JSON.stringify([DATABRICKS_PLAN]) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(local.queries).toEqual([]) - expect(result.metadata).toMatchObject({ success: false, adapter: "databricks", source: "explain" }) - expect(result.output).toContain("reads files directly") + test("a SQL input read through the own-jobs fallback says only the caller's jobs were read", async () => { + useAdapter(calls, { history: bigqueryHistory([], { denyJobs: true }) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select 1", history: true }, ctx) + expect(result.metadata.cost.scope).toBe("user") + expect(result.output.split("\n")[0]).toContain("Only your own jobs were read") }) - test("a Delta path and a table are still estimated", async () => { - for (const compiled of ["select * from delta.`/Volumes/c/s/v/t`", "select * from main.sales.orders"]) { - const local: Calls = { nodes: [], queries: [], dryRuns: [] } - useAdapter(local, { type: "databricks", compile: async () => compiled, explain: async () => JSON.stringify([DATABRICKS_PLAN]) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(result.metadata).toMatchObject({ success: true, source: "explain" }) + test("a failure after the own-jobs fallback still says only the caller's jobs were read", async () => { + useAdapter(calls, { + history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)], { denyJobs: true }), + boundary: async () => { + throw new Error("backend error") + }, + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(result.metadata.cost.unknownReason).toContain("could not check for runs still in progress") + expect(result.metadata.cost.scope).toBe("user") + expect(result.output.split("\n")[0]).toContain("Only your own jobs were read") + }) + + test("a script row with an unreadable start sends no NaN to the children query and is left out with its cause", async () => { + const script = job("s", "not a time", "2026-05-02 10:01:00+00:00", null, null, 0, "SCRIPT") + useAdapter(calls, { history: bigqueryHistory([script, job("m", "2026-05-03 10:00:00+00:00", "2026-05-03 10:01:00+00:00", TIB)]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + expect(historyLog.some((q) => q.includes("NaN"))).toBe(false) + expect(historyLog.some((q) => q.includes("parent_job_id in ("))).toBe(false) + expect(result.metadata.cost.notes.join(" ")).toContain("a script's start time could not be read") + }) + + test("an ephemeral model with no runs is told it never runs on its own", async () => { + useAdapter(calls, { history: bigqueryHistory([]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "inline", history: true }, ctx) + expect(why(result.metadata.cost)).toContain("An ephemeral model never runs on its own") + const table_ = await (await initTool(DbtCostEstimateTool)).execute({ model: "stg_orders", history: true }, ctx) + expect(why(table_.metadata.cost)).not.toContain("ephemeral") + }) + + test("a rate saved as null is ignored and named, and the default stands", async () => { + costHistoryInternals.readCostConfig = async () => ({ bigqueryUsdPerTib: null, bigquerySlotHourUsd: null }) + try { + useAdapter(calls, { history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const notes = result.metadata.cost.notes.join(" ") + expect(notes).toContain("cost.bigqueryUsdPerTib is ignored") + expect(notes).toContain("cost.bigquerySlotHourUsd is ignored") + expect(result.metadata.cost.rate).toMatchObject({ value: 6.25, source: "default" }) + } finally { + costHistoryInternals.readCostConfig = defaultReadCostConfig } }) -}) -describe("review follow-ups, round seven", () => { - test.each([ - "select * from read_files/**/('/Volumes/c/s/v/raw', format => 'json')", - "select * from `read_files`('/x')", - "select * from read_files -- why\n ('/x')", - "select * from `json`.`/Volumes/c/s/v/raw`", - "select * from json/**/.`/x`", - "select '--', * from read_files('/x')", - "select * from system.builtin.read_files('/x')", - ])("%p reads files", (sql) => { - expect(readsFiles(sql)).toBe(true) + test("a configured rate the tool ignores is named, and the default is not passed off as the configured one", async () => { + costHistoryInternals.readCostConfig = async () => ({ bigqueryUsdPerTib: -1, bigquerySlotHourUsd: 1_000_001 }) + try { + useAdapter(calls, { history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)]) }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const notes = result.metadata.cost.notes.join(" ") + expect(notes).toContain("cost.bigqueryUsdPerTib is ignored") + expect(notes).toContain("cost.bigquerySlotHourUsd is ignored") + expect(result.metadata.cost.rate).toMatchObject({ value: 6.25, source: "default" }) + } finally { + costHistoryInternals.readCostConfig = defaultReadCostConfig + } }) test.each([ - "select * from main.sales.orders", - "select t.json.field, text.col from t", - "select * from delta.`/Volumes/c/s/v/t`", - "select 'read_files' as note from t", - ])("%p reads tables", (sql) => { - expect(readsFiles(sql)).toBe(false) - }) - - test("on Databricks, a comment-split or quoted file read never reaches the EXPLAIN", async () => { - for (const compiled of ["select * from read_files/**/('/x')", "select * from `json`.`/x`"]) { - const local: Calls = { nodes: [], queries: [], dryRuns: [] } - useAdapter(local, { type: "databricks", compile: async () => compiled, explain: async () => JSON.stringify([DATABRICKS_PLAN]) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(local.queries).toEqual([]) - expect(result.metadata).toMatchObject({ success: false, adapter: "databricks", source: "explain" }) + ["an error", async () => { throw new Error("Encountered an error:\nbackend error: quota exceeded") }], + ["a timeout", () => new Promise(() => {})], + ])("when the boundary read fails (%s), no run is priced and the scan figure stays", async (name, boundary) => { + if (name === "a timeout") costHistoryInternals.historyTimeoutMs = 200 + useAdapter(calls, { + history: bigqueryHistory([job("a", "2026-05-02 10:00:00+00:00", "2026-05-02 10:01:00+00:00", TIB)]), + boundary, + }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx) + const cost = result.metadata.cost + expect(result.metadata).toMatchObject({ success: true, bytes: Math.round(4.2 * TIB), display: "4.2 TiB" }) + expect(cost.runs).toBeUndefined() + expect(cost.lastRun).toBeUndefined() + // The reason is the unknown reason, which leads the answer. + expect([cost.unknownReason, ...cost.notes].join(" ")).toContain("could not check for runs still in progress: ") + expect(result.output).not.toContain("Cost from") + }) + + describe("unfinished runs and boundary identity through the tool", () => { + const asOf = Date.UTC(2026, 5, 1, 20, 0, 0) + const iso = (ms: number) => new Date(ms).toISOString() + const COLS = [...JOB_COLUMNS, "state"] + const row = (id: string, start: number, end: number, type: string, billed: number, state = "DONE", dataset: string | null = null, dest: string | null = null) => [ + id, "a@x.com", iso(start), iso(end), type, dest, dataset, String(billed), "0", null, "False", state, + ] + const withNow = async (run: () => Promise) => { + costHistoryInternals.now = () => asOf + try { + await run() + } finally { + costHistoryInternals.now = defaultNow + } } - }) -}) + const ask = async () => (await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", history: true }, ctx)).metadata.cost + const answer = (rows: (string | null)[][], boundary?: (string | null)[][]) => ({ + history: async (jinja: string) => { + if (jinja.includes("countif(reservation_id")) return table(["jobs", "reserved"], [["10", "0"]]) + return table(COLS, rows) + }, + boundary: async () => table(["job_id", "user_email", "creation_time", "end_time", "statement_type", "destination_table_id", "destination_dataset_id"], boundary ?? []), + }) + const day = 86_400_000 + + test("a run whose last job ended 30 s before the instant read is left out, the instant being the one the call read as of", async () => { + await withNow(async () => { + useAdapter(calls, answer([row("m", asOf - 100_000, asOf - 30_000, "MERGE", TIB), row("old", asOf - 2 * day, asOf - 2 * day + 60_000, "MERGE", TIB)])) + const cost = await ask() + expect(cost.runs).toBe(1) + expect(cost.notes).toContain("A run still in progress was left out.") + }) + }) -describe("review follow-ups, round eight", () => { - const escapedNewline = [ - "WITH unused AS (SELECT 'a\\\n-- x' AS s) SELECT * FROM read_files('/x')", - "SELECT length('a\\\n--') AS n, * FROM read_files('/x', format => 'json')", - ] + test("a job still running is read with its state, so a finished CTAS beside it is not priced as a whole run", async () => { + await withNow(async () => { + const start = asOf - 3 * day + useAdapter(calls, answer([ + row("t", start, start + 60_000, "CREATE_TABLE_AS_SELECT", TIB, "DONE", "d", "orders__dbt_tmp"), + row("m", start + 120_000, start + 120_000, "MERGE", 0, "RUNNING", "d"), + ])) + const cost = await ask() + expect(historyLog.find((q) => q.includes("strpos") && !q.includes("run boundary"))).toContain("PENDING") + expect(cost.runs).toBeUndefined() + expect(cost.notes.join(" ")).toContain("A run still in progress was left out.") + }) + }) - test.each(escapedNewline)("a backslash before a line break stays inside the text: %p reads files", (sql) => { - expect(mayBeScript(sql, "databricks")).toBe(false) - expect(readsFiles(sql)).toBe(true) - }) + // 500 statements are returned, so the cutoff is the oldest one's start, five days before the instant read; user a's + // later build starts 4.1 days after it, beyond the 96 hours 10 minutes the full boundary read falls back to. + const T0 = asOf - 5 * day + const step = 864_000 + const fullRows = () => [ + row("old", T0, T0 + 60_000, "MERGE", TIB), + ...Array.from({ length: 499 }, (_, i) => { + const at = T0 + (i + 1) * step + const r = row(`f${i}`, at, at + 60_000, "MERGE", i === 410 ? 100 * TIB : TIB) + r[1] = i === 410 ? "a@x.com" : `u${i}@x.com` + return r + }), + ] + const BOUNDARY_COLS = ["job_id", "user_email", "creation_time", "end_time", "state", "statement_type", "destination_table_id", "destination_dataset_id"] + /** A full boundary read (500 rows), the jobs still going first, as the query orders them. */ + const fullBoundaryWith = (going: (string | null)[][]) => async () => + table(BOUNDARY_COLS, [...going, ...Array.from({ length: 500 - going.length }, (_, i) => [`b${i}`, `x${i}@x.com`, iso(T0 - 60_000), iso(T0 - 30_000), "DONE", "MERGE", null, null])]) + const goingRow = (end: string | null, state: string, created = T0 - 60_000, user = "a@x.com") => ["q", user, iso(created), end, state, "MERGE", null, null] + const boundaryQueries = () => historyLog.filter((q) => q.includes("run boundary")) + + test("a pending job a minute before the cutoff leaves out user a's build 4.1 days later, though the boundary read was full", async () => { + await withNow(async () => { + useAdapter(calls, { ...answer(fullRows()), boundary: fullBoundaryWith([goingRow(null, "PENDING")]) }) + const cost = await ask() + expect(cost.notes).toContain("2 runs still in progress were left out.") + // The 100 TiB build is not priced. + expect(cost.highest).toBeLessThan(100 * 6.25) + // One boundary read, and no other query for jobs still going. + expect(boundaryQueries()).toHaveLength(1) + // Jobs still going are read from no further back than the longest job span before the cutoff. + expect(boundaryQueries()[0]).toContain(`creation_time > timestamp_millis(${T0 - 96 * HOUR - 10 * 60_000}))`) + expect(historyLog.some((q) => q.includes("end_time, state\n"))).toBe(false) + }) + }) - test("so it never reaches the EXPLAIN", async () => { - for (const compiled of escapedNewline) { - const local: Calls = { nodes: [], queries: [], dryRuns: [] } - useAdapter(local, { type: "databricks", compile: async () => compiled, explain: async () => JSON.stringify([DATABRICKS_PLAN]) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(local.queries).toEqual([]) - expect(result.metadata).toMatchObject({ success: false, adapter: "databricks", source: "explain" }) - } - }) + test("a DONE job with no end time before the cutoff is read as going and leaves out the same user's build 4.1 days later", async () => { + await withNow(async () => { + useAdapter(calls, { + ...answer(fullRows()), + boundary: async () => table(BOUNDARY_COLS, [goingRow(null, "DONE")]), + }) + const cost = await ask() + expect(cost.notes).toContain("2 runs still in progress were left out.") + expect(cost.highest).toBeLessThan(100 * 6.25) + }) + }) - test("both checks read the SQL the same way: one scan", () => { - expect(scanSql("select `json`.`x` from t -- c\n", "databricks")).toEqual({ script: false, code: "select `json`.`x` from t ", literals: [], calls: 0 }) - expect(scanSql("select 'a' from t", "databricks").code).toBe("select from t") - }) -}) + test("a full boundary read leaves out every run by a user with a job still going, even one that ended long before", async () => { + await withNow(async () => { + useAdapter(calls, { ...answer(fullRows()), boundary: fullBoundaryWith([goingRow(null, "RUNNING", asOf - 3_600_000)]) }) + const cost = await ask() + expect(cost.notes.join(" ")).toContain("The read of jobs before the period was full") + expect(cost.highest).toBeLessThan(100 * 6.25) + }) + }) -describe("review follow-ups, round nine", () => { - test("a Databricks line comment continued past a backslash is not read", () => { - const sql = "SELECT 1 -- \\\n'ignored\n, * FROM read_files('/Volumes/c/s/v/raw', format => 'json') -- '" - expect(mayBeScript(sql, "databricks")).toBe(true) - expect(readsFiles(sql)).toBe(true) - }) + // Rows where user a's 50 TiB merge starts `afterMs` after the cutoff; every other run is one TiB by its own user. + const rowsWithMerge = (afterMs: number) => { + const rows = fullRows() + rows[1] = row("am", T0 + afterMs, T0 + afterMs + 60_000, "MERGE", 50 * TIB, "DONE", "d") + for (let i = 2; i < rows.length; i++) { + rows[i][1] = `u${i}@x.com` + rows[i][7] = String(TIB) + } + rows[0][1] = "z@x.com" + return rows + } + const HOUR = 3_600_000 - test.each([ - "SELECT * FROM libsvm.`s3://bucket/train`", - "SELECT * FROM somefmt.`dbfs:/mnt/raw`", - "SELECT * FROM `binaryFile`.`/Volumes/c/s/v/raw`", - ])("%p reads files", (sql) => { - expect(readsFiles(sql)).toBe(true) - }) + test("a full boundary read leaves out a run starting 25 hours after the cutoff: a job can be in flight for 96 hours", async () => { + await withNow(async () => { + useAdapter(calls, { ...answer(rowsWithMerge(25 * HOUR)), boundary: fullBoundaryWith([]) }) + expect((await ask()).highest).toBeLessThanOrEqual(6.25 + 1e-9) + }) + }) - test.each([ - "SELECT * FROM delta.`/Volumes/c/s/v/t`", - "SELECT * FROM sales.`order items`", - "SELECT * FROM main.sales.`orders`", - ])("%p reads a table", (sql) => { - expect(readsFiles(sql)).toBe(false) - }) - - test("a continued comment or a LIBSVM path never reaches the EXPLAIN", async () => { - for (const compiled of ["SELECT 1 -- \\\n'ignored\n, * FROM read_files('/x') -- '", "SELECT * FROM libsvm.`s3://bucket/train`"]) { - const local: Calls = { nodes: [], queries: [], dryRuns: [] } - useAdapter(local, { type: "databricks", compile: async () => compiled, explain: async () => JSON.stringify([DATABRICKS_PLAN]) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(local.queries).toEqual([]) - expect(result.metadata).toMatchObject({ success: false, adapter: "databricks", source: "explain" }) - } - }) -}) + test("a full boundary read leaves out a run 96 hours 1 minute after the cutoff, within the longest job span plus the join gap", async () => { + await withNow(async () => { + useAdapter(calls, { ...answer(rowsWithMerge(96 * HOUR + 60_000)), boundary: fullBoundaryWith([]) }) + expect((await ask()).highest).toBeLessThanOrEqual(6.25 + 1e-9) + }) + }) -describe("review follow-ups, round ten", () => { - test.each([ - "SELECT * FROM `org.apache.spark.sql.json.DefaultSource`.`/Volumes/c/s/v/raw`", - "SELECT * FROM `org.apache.spark.sql.execution.datasources.json.JsonFileFormat`.`/Volumes/c/s/v/raw`", - "SELECT * FROM somefmt.`prefix``/raw`", - "SELECT * FROM delta.`a``/b`", - ])("%p reads files", (sql) => { - expect(readsFiles(sql)).toBe(true) - }) + test("a CTAS created 96 hours 5 minutes before the cutoff that finished 7 minutes before it joins a merge a minute after it: the run is left out", async () => { + await withNow(async () => { + const edge = asOf - 30 * day + const lit = (jinja: string, pattern: RegExp) => Number(pattern.exec(jinja)![1]) + const created = edge - 96 * HOUR - 5 * 60_000 + useAdapter(calls, { + ...answer([row("m", edge + 60_000, edge + 120_000, "MERGE", TIB, "DONE", "d")]), + // An adapter consistent with the SQL: the finished CTAS is returned iff it was created after the lookback's start. + boundary: async (jinja) => { + const after = lit(jinja, /creation_time > timestamp_millis\((\d+)\) and upper\(state\) = \\?'DONE/) + return table(BOUNDARY_COLS, created > after ? [["t", "a@x.com", iso(created), iso(edge - 7 * 60_000), "DONE", "CREATE_TABLE_AS_SELECT", "orders__dbt_tmp", "d"]] : []) + }, + }) + const cost = await ask() + expect(cost.runs).toBeUndefined() + expect(cost.notes.join(" ")).toContain("1 run that may have started before the period read was left out.") + }) + }) - test("Delta's own provider over a path is still a table", () => { - expect(readsFiles("SELECT * FROM `delta`.`/Volumes/c/s/v/t`")).toBe(false) - expect(readsFiles("SELECT * FROM delta . `s3://bucket/t`")).toBe(false) - }) + test("a CREATE MODEL hook that ran for 47 hours before the cutoff and a merge 10 seconds after it are one run that began unread", async () => { + await withNow(async () => { + const edge = asOf - 30 * day + const lit = (jinja: string, pattern: RegExp) => Number(pattern.exec(jinja)![1]) + const created = edge - 47 * HOUR + useAdapter(calls, { + ...answer([row("m", edge + 10_000, edge + 70_000, "MERGE", TIB, "DONE", "d")]), + boundary: async (jinja) => { + const after = lit(jinja, /creation_time > timestamp_millis\((\d+)\) and upper\(state\) = \\?'DONE/) + return table(BOUNDARY_COLS, created > after ? [["h", "a@x.com", iso(created), iso(edge - 30_000), "DONE", "CREATE_MODEL", null, null]] : []) + }, + }) + const cost = await ask() + expect(cost.runs).toBeUndefined() + expect(cost.notes.join(" ")).toContain("1 run that may have started before the period read was left out.") + }) + }) - test("a provider class name over a path never reaches the EXPLAIN", async () => { - const local: Calls = { nodes: [], queries: [], dryRuns: [] } - useAdapter(local, { type: "databricks", compile: async () => "SELECT * FROM `org.apache.spark.sql.json.DefaultSource`.`/Volumes/c/s/v/raw`", explain: async () => JSON.stringify([DATABRICKS_PLAN]) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(local.queries).toEqual([]) - expect(result.metadata).toMatchObject({ success: false, adapter: "databricks", source: "explain" }) - }) -}) + test("a CREATE MODEL hook created 80 hours before the cutoff, queued 36 hours and finished 30 s before it, joins a merge 10 s after it: the run is left out", async () => { + await withNow(async () => { + const edge = asOf - 30 * day + const lit = (jinja: string, pattern: RegExp) => Number(pattern.exec(jinja)![1]) + const created = edge - 80 * HOUR + useAdapter(calls, { + ...answer([row("m", edge + 10_000, edge + 70_000, "MERGE", TIB, "DONE", "d")]), + // An adapter consistent with the SQL: the finished hook is returned iff it was created after the lookback's start. + boundary: async (jinja) => { + const after = lit(jinja, /creation_time > timestamp_millis\((\d+)\) and upper\(state\) = \\?'DONE/) + return table(BOUNDARY_COLS, created > after ? [["h", "a@x.com", iso(created), iso(edge - 30_000), "DONE", "CREATE_MODEL", null, null]] : []) + }, + }) + const cost = await ask() + expect(cost.runs).toBeUndefined() + expect(cost.notes.join(" ")).toContain("1 run that may have started before the period read was left out.") + }) + }) -describe("bot review follow-ups", () => { - test.each([ - "select * from query_audit where sql_text like '%read_files(%'", - "SELECT * FROM main.json.`orders`", - "SELECT * FROM main.image.`thumbnails`", - ])("%p reads a table", (sql) => { - expect(readsFiles(sql)).toBe(false) - }) + test("a full boundary read keeps the finished jobs it returned: a CTAS that finished 96 hours 13 minutes after the cutoff chains into a merge past the boundary span", async () => { + await withNow(async () => { + const merge = 96 * HOUR + 20 * 60_000 + const ctas = ["t", "a@x.com", iso(T0 - 60_000), iso(T0 + 96 * HOUR + 13 * 60_000), "DONE", "CREATE_TABLE_AS_SELECT", "orders__dbt_tmp", "d"] + const boundary = async () => + table(BOUNDARY_COLS, [ctas, ...Array.from({ length: 499 }, (_, i) => [`b${i}`, `x${i}@x.com`, iso(T0 - 60_000), iso(T0 - 30_000), "DONE", "MERGE", null, null])]) + useAdapter(calls, { ...answer(rowsWithMerge(merge)), boundary }) + expect((await ask()).highest).toBeLessThanOrEqual(6.25 + 1e-9) + // Without that CTAS in the read, the merge is beyond the fallback and priced. + resetDbtAdapter() + useAdapter(calls, { ...answer(rowsWithMerge(merge)), boundary: fullBoundaryWith([]) }) + expect((await ask()).highest).toBeCloseTo(50 * 6.25, 8) + }) + }) - test.each([ - "SELECT * FROM json.`data.json`", - "SELECT * FROM t JOIN csv.`rel` ON true", - "SELECT * FROM a, parquet.`p`", - "SELECT * FROM system.builtin.read_files('/x')", - ])("%p reads files", (sql) => { - expect(readsFiles(sql)).toBe(true) - }) + test("jobs labelled with their dbt invocation id are grouped by it: two invocations within a minute are two runs", async () => { + // Inside the history window. + const at = (offsetMs: number) => new Date(Date.now() - 10 * day + offsetMs).toISOString() + const labelled = (id: string, invocation: string, start: string, end: string, tib: number) => [...job(id, start, end, tib * TIB), invocation] + const columns = [...JOB_COLUMNS, "dbt_invocation_id"] + const rows = [labelled("a", "i1", at(0), at(60_000), 1), labelled("b", "i2", at(30_000), at(90_000), 2)] + useAdapter(calls, { history: async (jinja) => (jinja.includes("countif(reservation_id") ? table(["jobs", "reserved"], [["10", "0"]]) : table(columns, rows)) }) + const cost = await ask() + expect(cost.runs).toBe(2) + expect(cost.highest).toBeCloseTo(12.5, 10) + expect(historyLog.find((q) => q.includes("total_bytes_billed"))).toContain("dbt_invocation_id") + }) - test("many backtick-quoted names are read in one pass", () => { - const sql = `select ${Array.from({ length: 5000 }, (_, i) => `\`c${i}\``).join(", ")} from delta.\`/Volumes/c/s/v/t\`` - const started = performance.now() - expect(readsFiles(sql)).toBe(false) - expect(performance.now() - started).toBeLessThan(500) - }) -}) + test("a read of 500 jobs: an earlier job of the run's invocation, created days before the cutoff, leaves the run out; another invocation's does not", async () => { + await withNow(async () => { + const T0 = asOf - 5 * day + const columns = [...JOB_COLUMNS, "state", "dbt_invocation_id"] + const ownRun = (id: string) => ["m", "a@x.com", iso(T0 + 80 * 3_600_000), iso(T0 + 80 * 3_600_000 + 60_000), "MERGE", null, null, String(TIB), "0", null, "False", "DONE", id] + const fillers = Array.from({ length: 499 }, (_, i) => { + const at = T0 + i * 864_000 + return [`f${i}`, `u${i}@x.com`, iso(at), iso(at + 30_000), "MERGE", null, null, String(TIB), "0", null, "False", "DONE", null] + }) + const oldest = ["old", "z@x.com", iso(T0), iso(T0 + 30_000), "MERGE", null, null, String(TIB), "0", null, "False", "DONE", null] + const lit = (jinja: string, pattern: RegExp) => Number(pattern.exec(jinja)![1]) + // Created 30 hours before the cutoff; the label branch reads as far back as JOBS keeps jobs (180 days), so it is found. + const earlierAt = T0 - 30 * 3_600_000 + const BC = [...BOUNDARY_COLS, "dbt_invocation_id"] + const ask1 = async (runId: string, earlierId: string) => { + resetDbtAdapter() + useAdapter(calls, { + history: async (jinja) => (jinja.includes("countif(reservation_id") ? table(["jobs", "reserved"], [["10", "0"]]) : table(columns, [oldest, ownRun(runId), ...fillers.slice(1, 499)])), + // The boundary read is full of unlabelled jobs, which must not crowd out the invocation's own jobs, read apart. + boundary: async () => + table(BC, Array.from({ length: 500 }, (_, i) => [`b${i}`, `x${i}@x.com`, iso(T0 - 60_000), iso(T0 - 30_000), "DONE", "MERGE", null, null, null])), + // An adapter consistent with the SQL: the earlier job is returned iff its id is asked for and it is after the read's start. + invocations: async (jinja) => { + const after = lit(jinja, /creation_time > timestamp_millis\((\d+)\)/) + // The read reaches back as far as JOBS keeps jobs, not from the cutoff. + expect(after).toBe(asOf - 180 * day) + const seen = jinja.includes(`\\'${earlierId}\\'`) && earlierAt > after + return table(BC, seen ? [["x", "a@x.com", iso(earlierAt), iso(earlierAt + 60_000), "DONE", "MERGE", null, null, earlierId]] : []) + }, + }) + return ask() + } + const same = await ask1("i1", "i1") + expect(same.notes.join(" ")).toContain("may have started before the period read") + // The same invocation's job is what leaves the run out: with another id the run is one more priced run. + const other = await ask1("i1", "i2") + expect(other.runs).toBe((same.runs ?? 0) + 1) + }) + }) -describe("review follow-ups, round twelve", () => { - test.each([ - "SELECT * FROM (json.`data.json`)", - "SELECT * FROM`json`.`data.json`", - "SELECT * FROM json . `data.json`", - // A column qualified by an alias named like a format cannot be told from a path query without parsing: refused. - "SELECT json.`order-id` FROM main.sales.orders AS json", - ])("%p reads files (or may)", (sql) => { - expect(readsFiles(sql)).toBe(true) - }) - - test("a parenthesised or unspaced file read never reaches the EXPLAIN", async () => { - for (const compiled of ["SELECT * FROM (json.`data.json`)", "SELECT * FROM`json`.`data.json`"]) { - const local: Calls = { nodes: [], queries: [], dryRuns: [] } - useAdapter(local, { type: "databricks", compile: async () => compiled, explain: async () => JSON.stringify([DATABRICKS_PLAN]) }) - const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(local.queries).toEqual([]) - expect(result.metadata).toMatchObject({ success: false, adapter: "databricks", source: "explain" }) - } - }) -}) + test("a full read of the invocations' own jobs leaves the labelled run out as possibly cut", async () => { + await withNow(async () => { + const T0 = asOf - 5 * day + const columns = [...JOB_COLUMNS, "state", "dbt_invocation_id"] + const run = ["m", "a@x.com", iso(T0 + 80 * 3_600_000), iso(T0 + 80 * 3_600_000 + 60_000), "MERGE", null, null, String(TIB), "0", null, "False", "DONE", "i1"] + const BC = [...BOUNDARY_COLS, "dbt_invocation_id"] + const ask1 = async (own: number) => { + resetDbtAdapter() + useAdapter(calls, { + history: async (jinja) => (jinja.includes("countif(reservation_id") ? table(["jobs", "reserved"], [["10", "0"]]) : table(columns, [run])), + invocations: async () => table(BC, Array.from({ length: own }, (_, i) => [`o${i}`, "z@x.com", iso(T0 - 3_600_000 - i * 1000), iso(T0 - 3_000_000 - i * 1000), "DONE", "MERGE", null, null, "other"])), + }) + return ask() + } + expect((await ask1(499)).runs).toBe(1) + const full = await ask1(500) + expect(full.runs).toBeUndefined() + expect(full.notes.join(" ")).toContain("may have started before the period read") + }) + }) -describe("IDENTIFIER() on Databricks", () => { - test.each([ - "SELECT * FROM IDENTIFIER('read_files')('/Volumes/c/s/v/raw', format => 'json')", - "SELECT * FROM IDENTIFIER('system.builtin.read_files')('s3://b/x')", - "SELECT * FROM IDENTIFIER('json.`/Volumes/c/s/v/raw`')", - "select * from identifier ( 'READ_FILES' ) ('/x')", - "select * from IDENTIFIER(\"Cloud_Files\")('/x')", - "select * from IDENTIFIER('system . builtin . `read_files`')('/x')", - "select * from IDENTIFIER /* c */ ( /* d */ 'CSV.`/x`')", - "select * from IDENTIFIER('`parquet`.`s3://b/x`')", - "select * from IDENTIFIER('read' || '_files')('/x')", - "select * from IDENTIFIER('read_' '' 'files')('/x')", - "select * from IDENTIFIER(:tbl)", - "select * from IDENTIFIER(concat('json.`', :p, '`'))", - "select * from IDENTIFIER(tbl_var)", - "select * from IDENTIFIER('cat.sch.tbl') a join IDENTIFIER(:other) b on a.id = b.id", - "select * from IDENTIFIER('read\\_files')('/x')", - "SELECT * FROM IDENTIFIER(IDENTIFIER('lower')('READ_FILES'))('/Volumes/c/s/v/raw')", - "SELECT * FROM IDENTIFIER( IDENTIFIER('concat')('read_', 'files'))('/Volumes/c/s/v/raw')", - "SELECT * FROM IDENTIFIER('read_files /* c */')('/Volumes/c/s/v/raw')", - "SELECT * FROM IDENTIFIER('read_files/**/')('/Volumes/c/s/v/raw')", - "SELECT * FROM IDENTIFIER('json/**/.`/Volumes/c/s/v/raw`')", - "SELECT * FROM IDENTIFIER('read_files -- c\n')('/x')", - "SELECT * FROM system.builtin.IDENTIFIER('read_files')('/Volumes/c/s/v/raw')", - "SELECT * FROM json.IDENTIFIER('`/Volumes/c/s/v/raw`')", - "SELECT * FROM IDENTIFIER('json').`data.json`", - "SELECT * FROM IDENTIFIER('json') . `data`", - "SELECT * FROM IDENTIFIER('\"read_files\"')('/Volumes/c/s/v/raw', format => 'json')", - "SELECT * FROM IDENTIFIER(\"fn\")('/Volumes/c/s/v/raw')", - "SELECT * FROM \u0131DENTIFIER('read_files')('/Volumes/c/s/v/raw')", - "SELECT * FROM IDENTIFIER(\"IDENTIFIER('read_files')\")('/Volumes/c/s/v/raw')", - "SELECT * FROM IDENTIFIER('identifier(''x'')')('/x')", - "SELECT * FROM IDENTIFIER('read_' /*a*/ || 'files' /*b*/)('/Volumes/c/s/v/raw', format => 'json')", - "SELECT * FROM IDENTIFIER('`j\u017fon`.`data.json`')", - "SELECT * FROM IDENTIFIER('${hiveconf:source}')('/Volumes/c/s/v/raw')", - "SELECT * FROM IDENTIFIER('json.raw')", - "SELECT * FROM IDENTIFIER(' CSV . raw')", - "SELECT \u017fIDENTIFIER('safe') FROM IDENTIFIER(concat('read_', 'files'))('/x')", - "SELECT \u0131DENTIFIER('safe') FROM IDENTIFIER(concat('read_', 'files'))('/x')", - "SELECT * FROM IDENTIFIER('`org.apache.spark.sql.json.DefaultSource`.`data.json`')", - "SELECT * FROM IDENTIFIER('`org.apache.spark.sql.json.DefaultSource`.`data.json`')", - "SELECT * FROM IDENTIFIER('a.b.c.d')", - "SELECT * FROM IDENTIFIER('js' /*a*/ || 'on.`/Volumes/c/s/v/raw`' /*b*/)", - "SELECT 1 AS `\u00df\u00df\u00df`, XIDENTIFIER('safe') AS n FROM IDENTIFIER(concat('read_', 'files'))('/x')", - ])("%p may read files", (sql) => { - expect(readsFiles(sql)).toBe(true) - }) + test("a job still running that carries another invocation's id does not leave the run out", async () => { + await withNow(async () => { + const edge = asOf - 30 * day + // Well inside the window. + const run = ["m", "a@x.com", iso(edge + 80 * 3_600_000), iso(edge + 80 * 3_600_000 + 60_000), "MERGE", null, null, String(TIB), "0", null, "False", "DONE", "i1"] + const columns = [...JOB_COLUMNS, "state", "dbt_invocation_id"] + const live = (id: string) => ["q", "a@x.com", iso(edge - 200_000), null, "RUNNING", "MERGE", null, null, id] + const ask1 = async (id: string) => { + resetDbtAdapter() + useAdapter(calls, { + history: async (jinja) => (jinja.includes("countif(reservation_id") ? table(["jobs", "reserved"], [["10", "0"]]) : table(columns, [run])), + boundary: async () => table([...BOUNDARY_COLS, "dbt_invocation_id"], [live(id)]), + }) + return ask() + } + expect((await ask1("i2")).runs).toBe(1) + expect((await ask1("i1")).notes).toContain("A run still in progress was left out.") + }) + }) - test.each([ - "select * from IDENTIFIER('cat.sch.tbl')", - "select * from identifier ( 'cat.sch.tbl' ) t where t.x = 'read_files'", - "select IDENTIFIER('col') from main.sales.orders", - "select * from IDENTIFIER('main.json.t')", - "select * from `identifier`('x')", - "SELECT `note identifier(x)` FROM main.sales.orders", - `select * from IDENTIFIER${" ".repeat(120)}( 'cat.sch.tbl' )`, - "select * from IDENTIFIER('main.analytics.identifier_map')", - "SELECT 1 AS `\u00df\u00df`, XIDENTIFIER('safe') AS n FROM main.sales.orders", - ])("%p reads tables", (sql) => { - expect(readsFiles(sql)).toBe(false) - }) + test("without a job still going the same build is priced", async () => { + await withNow(async () => { + useAdapter(calls, { ...answer(fullRows()), boundary: fullBoundaryWith([]) }) + expect((await ask()).highest).toBeCloseTo(100 * 6.25, 8) + }) + }) - test.each([ - ["SELECT * FROM IDENTIFIER('system.builtin.read_files')('s3://b/x')", false], - ["SELECT * FROM IDENTIFIER(:tbl)", false], - ["SELECT * FROM IDENTIFIER('cat.sch.tbl')", true], - ])("%p: EXPLAIN sent is %p", async (compiled, explained) => { - useAdapter(calls, { type: "databricks", compile: async () => compiled, explain: async () => JSON.stringify([DATABRICKS_PLAN]) }) - await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) - expect(calls.queries.length > 0).toBe(explained) - }) + test("a CTAS created 25 hours before the cutoff that finished 30 s before it, and the MERGE 10 s after it, are one run that began unread", async () => { + await withNow(async () => { + const edge = asOf - 30 * day + const lit = (jinja: string, pattern: RegExp) => Number(pattern.exec(jinja)![1]) + const created = edge - 25 * 3_600_000 + useAdapter(calls, { + ...answer([row("m", edge + 10_000, edge + 70_000, "MERGE", TIB, "DONE", "d")]), + // An adapter consistent with the SQL: the finished CTAS is returned iff it was created after the lookback's start. + boundary: async (jinja) => { + const after = lit(jinja, /creation_time > timestamp_millis\((\d+)\) and upper\(state\) = \\?'DONE/) + return table(BOUNDARY_COLS, created > after ? [["t", "a@x.com", iso(created), iso(edge - 30_000), "DONE", "CREATE_TABLE_AS_SELECT", "orders__dbt_tmp", "d"]] : []) + }, + }) + const cost = await ask() + expect(cost.runs).toBeUndefined() + expect(cost.notes.join(" ")).toContain("1 run that may have started before the period read was left out.") + }) + }) - test("repeated comments before a concatenation scan in linear time", () => { - const sql = "SELECT * FROM IDENTIFIER('read_' " + "/**/".repeat(30) + " || 'files')('/Volumes/c/s/v/raw')" - const started = performance.now() - expect(readsFiles(sql)).toBe(true) - expect(performance.now() - started).toBeLessThan(200) + test("an unread temporary CTAS into another dataset does not drop a complete run, one into its dataset does", async () => { + await withNow(async () => { + // The window is not full, so the boundary starts at the window's edge; place the unread CTAS just before it. + const edge = asOf - 30 * day + const rowsAtEdge = [row("m", edge + 300_000, edge + 360_000, "MERGE", TIB, "DONE", "dev")] + const unread = (dataset: string) => [["u", "a@x.com", iso(edge - 300_000), iso(edge - 60_000), "CREATE_TABLE_AS_SELECT", "orders__dbt_tmp", dataset]] + useAdapter(calls, answer(rowsAtEdge, unread("prod"))) + expect((await ask()).runs).toBe(1) + resetDbtAdapter() + useAdapter(calls, answer(rowsAtEdge, unread("dev"))) + expect((await ask()).basis).toBe("none") + }) + }) }) - test("adjacent ordinary literals scan in linear time", () => { - const sql = "SELECT " + "'a' ".repeat(64000) + "FROM main.s.t" - const started = performance.now() - expect(readsFiles(sql)).toBe(false) - expect(performance.now() - started).toBeLessThan(1000) - }) - test("an unbalanced backtick over many slashes scans in linear time", () => { - const started = performance.now() - expect(readsFiles("SELECT * FROM IDENTIFIER('`" + "/".repeat(128000) + "')")).toBe(true) - expect(performance.now() - started).toBeLessThan(1000) - }) +}) - test("many ordinary literals scan in linear time", () => { - const sql = `select ${Array.from({ length: 20000 }, (_, n) => `'v${n}'`).join(", ")} from main.s.t` - const started = performance.now() - expect(readsFiles(sql)).toBe(false) - expect(performance.now() - started).toBeLessThan(1000) +describe("cost config", () => { + test("the cost block holds the BigQuery rates only, each a positive number", async () => { + const { ConfigV1 } = await import("@opencode-ai/core/v1/config/config") + const { Schema } = await import("effect") + const doc = Schema.toJsonSchemaDocument(ConfigV1.Info) + const text = JSON.stringify(doc) + expect(text).not.toContain("snowflakeUsdPerCredit") + expect(text).not.toContain("databricksUsdPerDbu") + for (const key of ["bigqueryUsdPerTib", "bigquerySlotHourUsd"]) { + const own = new RegExp(`"${key}":.*?"description":"([^"]*)"`).exec(text) + expect(own?.[1]).toContain("a positive number") + } }) - test("leaves Snowflake and BigQuery alone", async () => { - expect(scanSql("select * from IDENTIFIER('cat.sch.tbl')", "snowflake").literals).toEqual([]) - expect(scanSql("select * from IDENTIFIER('cat.sch.tbl')", "snowflake").calls).toBe(0) + test("loading the config tolerates a rate the tool will ignore: the schema has no refinement the PATCH route would skip", async () => { + const { ConfigV1 } = await import("@opencode-ai/core/v1/config/config") + const { Schema } = await import("effect") + const ok = (cost: unknown) => Schema.decodeUnknownExit(ConfigV1.Info)({ cost })._tag === "Success" + for (const key of ["bigqueryUsdPerTib", "bigquerySlotHourUsd"]) { + for (const value of [0, -1, 1e308, 1_000_001, 0.01, 6.25, 1e6]) expect(ok({ [key]: value })).toBe(true) + } + expect(ok({})).toBe(true) + // A rate saved as null loads (an infinity serializes to null), and so does one the PATCH route's Zod adapter validates. + const { zod } = await import("@/util/effect-zod") + for (const key of ["bigqueryUsdPerTib", "bigquerySlotHourUsd"]) { + expect(ok({ [key]: null })).toBe(true) + expect(zod(ConfigV1.Info).safeParse({ cost: { [key]: null } }).success).toBe(true) + expect(zod(ConfigV1.Info).safeParse({ cost: { [key]: 0 } }).success).toBe(true) + } + // The round trip of an unrelated save: 1e309 loads as Infinity, serializes as null, and the next load accepts it. + const loaded = Schema.decodeUnknownSync(ConfigV1.Info)(JSON.parse('{"cost":{"bigqueryUsdPerTib":1e309}}')) + const saved = JSON.stringify(loaded) + expect(saved).toContain('"bigqueryUsdPerTib":null') + expect(ok(JSON.parse(saved).cost)).toBe(true) + // The text tells the user what happens to such a value. + expect(JSON.stringify(Schema.toJsonSchemaDocument(ConfigV1.Info))).toContain("are ignored and named in the output") }) }) diff --git a/packages/opencode/test/altimate/dbt-cost-history.test.ts b/packages/opencode/test/altimate/dbt-cost-history.test.ts new file mode 100644 index 0000000000..8c3ed619ab --- /dev/null +++ b/packages/opencode/test/altimate/dbt-cost-history.test.ts @@ -0,0 +1,1402 @@ +// The cost of a model's earlier runs on BigQuery: the history SQL, the grouping of jobs into runs, and the pricing of +// what the jobs view reports. No adapter or warehouse is involved. +import { writeFile } from "node:fs/promises" +import path from "node:path" +import { describe, expect, test } from "bun:test" +import { tmpdir } from "../fixture/fixture" +import { + BQ_CHILD_LIMIT, + HISTORY_LIMIT, + bigqueryCapacitySql, + bigqueryHistorySql, + bqProject, + cleanRates, + costText, + median, + needleFor, + onDemandEstimate, + parseRows, + parseTime, + priceBigquery, + resolveModel, + rowsJinja, + unreadable, + windowStartMs, + bigqueryChildrenSql, + accessProblem, + TARGET_JINJA, + MIN_BILLED_BYTES, + ignoredRateNotes, + locationNote, + MAX_RATE, + formatMoney, + loadHistory, + manifestPathFor, + modelFromManifest, + BOUNDARY_SPAN_MS, + MAX_JOB_SPAN_MS, + bigqueryBoundarySql, + bigqueryInvocationSql, + boundaryWindow, + sqlString, + summarize, + type Row, +} from "@/altimate/tools/dbt-cost-history" + +const TIB = 1024 ** 4 +const DEMAND = { value: 6.25, unit: "USD/TiB", source: "default" as const } +const MIN = 60_000 +/** The instant the SQL under test is read as of. */ +const ASOF = Date.UTC(2026, 5, 1, 20, 0, 0) +const WINDOW = windowStartMs(ASOF) + +describe("needle and SQL escaping", () => { + test("the needle closes its quote, so one model id is not a prefix of another", () => { + expect(needleFor("model.a.b")).toBe('"node_id": "model.a.b"') + expect(needleFor("model.a.b")).not.toContain('"node_id": "model.a.bc') + }) + + test("a quote or a backslash in the needle cannot end the SQL literal", () => { + expect(sqlString("a'b\\c")).toBe("'a\\'b\\\\c'") + expect(sqlString("a'; drop table x; --")).toBe("'a\\'; drop table x; --'") + }) +}) + +describe("history SQL builders", () => { + const needle = needleFor("model.shop.orders") + + test("BigQuery: project, lowercased region, window, type filter, parent jobs and exact match", () => { + const sql = bigqueryHistorySql({ project: "my-proj", location: "EU", needle, asOfMs: ASOF }) + expect(sql).toContain("from `my-proj`.`region-eu`.INFORMATION_SCHEMA.JOBS") + expect(sql).toContain(`creation_time > timestamp_millis(${WINDOW}) and creation_time <= timestamp_millis(${ASOF})`) + expect(sql).toContain("parent_job_id is null") + expect(sql).toContain("error_result is null") + // No statement-type filter: a SELECT hook is billed and part of the invocation. The tool's own reads are excluded by their marker. + expect(sql).not.toContain("statement_type) in") + expect(sql).toContain("strpos(query, 'altimate_cost_read') = 0") + expect(sql).toContain("select /* altimate_cost_read */ job_id") + // The dbt invocation label of each job, which makes the jobs of one invocation one run. + expect(sql).toContain("(select value from unnest(labels) where key = 'dbt_invocation_id') as dbt_invocation_id") + // The state is read, so a job still queued or running is known as such. + expect(sql).toContain("end_time, state, statement_type") + // Finished jobs, and those still queued or running, whose run is not complete. + expect(sql).toContain("(upper(state) = 'DONE' and error_result is null) or upper(state) in ('PENDING','RUNNING')") + expect(sql).toContain(`strpos(query, '"node_id": "model.shop.orders"') > 0`) + expect(sql).not.toMatch(/\blike\b/i) + expect(sql).toContain("order by creation_time desc limit 500") + }) + + test("BigQuery: no location falls back to us, and a hostile one cannot leave the quoted name", () => { + expect(bigqueryHistorySql({ project: "p", needle, asOfMs: ASOF })).toContain("`region-us`") + expect(bigqueryHistorySql({ project: "p", location: "eu`; drop", needle, asOfMs: ASOF })).toContain("`region-eudrop`") + }) + + test("BigQuery: the capacity check counts a week of query jobs and those in a reservation", () => { + const sql = bigqueryCapacitySql({ project: "p", location: "us", asOfMs: ASOF }) + expect(sql).toContain(`creation_time > timestamp_millis(${windowStartMs(ASOF, 7)}) and creation_time <= timestamp_millis(${ASOF})`) + expect(sql).toContain("countif(reservation_id is not null) as reserved") + expect(sql).toContain("count(*) as jobs") + expect(sql).toContain("upper(job_type) = 'QUERY'") + }) + + test("BigQuery: a role that cannot list every user's jobs reads its own from JOBS_BY_USER", () => { + expect(bigqueryHistorySql({ project: "p", needle: "n", view: "JOBS_BY_USER", asOfMs: ASOF })).toContain("INFORMATION_SCHEMA.JOBS_BY_USER") + expect(bigqueryHistorySql({ project: "p", needle: "n", asOfMs: ASOF })).toContain("INFORMATION_SCHEMA.JOBS\n") + expect(bigqueryCapacitySql({ project: "p", view: "JOBS_BY_USER", asOfMs: ASOF })).toContain("JOBS_BY_USER") + }) + + test("BigQuery: the children of matched scripts are read by parent id, escaped, from the earliest parent's creation, in the same region", () => { + const sql = bigqueryChildrenSql({ project: "p", location: "EU", parents: ["job_1", "j'2"], sinceMs: 1_700_000_000_123 }) + expect(sql).toContain("parent_job_id in ('job_1','j\\'2')") + expect(sql).toContain("`region-eu`") + // The lower bound is the earliest parent's creation: a fixed instant, not a window that slides while the parents are read. + expect(sql).toContain("creation_time >= timestamp_millis(1700000000123)") + expect(sql).not.toContain("current_timestamp") + }) + + test("BigQuery project ids with anything beyond a name's characters are refused", () => { + expect(bqProject("my-proj")).toBe("my-proj") + expect(bqProject("example.com:proj")).toBe("example.com:proj") + expect(bqProject("p`; drop")).toBeUndefined() + expect(bqProject(undefined)).toBeUndefined() + }) + + test("every comparison with a warehouse enum or category column is case-insensitive", () => { + const needle = needleFor("model.shop.orders") + const w = boundaryWindow(1_780_000_000_000) + const sqls = [ + bigqueryHistorySql({ project: "p", needle, asOfMs: ASOF }), + bigqueryChildrenSql({ project: "p", parents: ["a"], sinceMs: 1 }), + bigqueryCapacitySql({ project: "p", asOfMs: ASOF }), + bigqueryBoundarySql({ project: "p", needle, window: w }), + ] + const columns = ["statement_type", "job_type", "state"] + const bare = new RegExp(`(? m[0])).toEqual([]) + // The check sees a bare comparison. + expect([..."and state = 'DONE'".matchAll(bare)]).toHaveLength(1) + }) + + test("a quote in the needle is escaped in the history SQL", () => { + const hostile = `"node_id": "model.a.b' or 1=1 --"` + expect(bigqueryHistorySql({ project: "p", needle: hostile, asOfMs: ASOF })).toContain("b\\' or 1=1") + }) +}) + +describe("resolveModel", () => { + const nodes = { + "model.shop.orders": { resource_type: "model", name: "orders", config: { materialized: "incremental" } }, + "model.shop.dup": { resource_type: "model", name: "dup" }, + "model.other.dup": { resource_type: "model", name: "dup" }, + "model.shop.items.v1": { resource_type: "model", name: "items", version: 1 }, + "model.shop.items.v2": { resource_type: "model", name: "items", version: 2 }, + "seed.shop.orders": { resource_type: "seed", name: "orders" }, + } + + test("a name, a unique_id and a package-qualified name each reach one node", () => { + expect(resolveModel(nodes, "orders")).toEqual({ uniqueId: "model.shop.orders", materialized: "incremental" }) + expect(resolveModel(nodes, "model.shop.orders")).toMatchObject({ uniqueId: "model.shop.orders" }) + expect(resolveModel(nodes, "shop.orders")).toMatchObject({ uniqueId: "model.shop.orders" }) + expect(resolveModel(nodes, "other.dup")).toMatchObject({ uniqueId: "model.other.dup" }) + }) + + test("a versioned name resolves to the version it names, and the bare name is ambiguous", () => { + expect(resolveModel(nodes, "items.v2")).toMatchObject({ uniqueId: "model.shop.items.v2" }) + expect(resolveModel(nodes, "items")).toEqual({ error: expect.stringContaining("model.shop.items.v1, model.shop.items.v2") }) + }) + + test("two packages with one name are ambiguous, and a missing name is an error", () => { + expect(resolveModel(nodes, "dup")).toEqual({ error: expect.stringContaining("ambiguous") }) + expect(resolveModel(nodes, "nope")).toEqual({ error: expect.stringContaining("no model named nope") }) + }) +}) + +describe("rows from the adapter", () => { + test("the Jinja runs the query through run_query, escaped, and does nothing at parse time", () => { + const jinja = rowsJinja("select 'a\\b';") + expect(jinja).toContain("run_query('select \\'a\\\\b\\'')") + expect(jinja).toContain("{%- else -%}") + expect(jinja).toContain("v | string") + }) + + test("a table is read into rows keyed by lower-cased column", () => { + expect(parseRows('{"columns":["Job_ID","X"],"rows":[["a",null],["b","2"]]}')).toEqual([ + { job_id: "a", x: null }, + { job_id: "b", x: "2" }, + ]) + }) + + test("anything else is refused, not read as no rows", () => { + expect(() => parseRows("compiled(select 1)")).toThrow() + expect(() => parseRows('{"columns":[]}')).toThrow("no table") + }) + + test("times read as UTC when they name no zone, and keep the zone when they do", () => { + expect(parseTime("2026-05-02 10:00:00")).toBe(Date.UTC(2026, 4, 2, 10)) + expect(parseTime("2026-05-02 10:00:00+00:00")).toBe(Date.UTC(2026, 4, 2, 10)) + expect(parseTime("2026-05-02 10:00:00.123000-07:00")).toBe(Date.UTC(2026, 4, 2, 17, 0, 0, 123)) + expect(parseTime(null)).toBeNaN() + }) +}) + +describe("run statistics", () => { + test("median is the middle run, or the mean of the middle two", () => { + expect(median([9, 1, 5])).toBe(5) + expect(median([1, 2, 3, 10])).toBe(2.5) + }) + + test("last run is the newest one, typical the median, highest the largest", () => { + const s = summarize([ + { start: 3, cost: 3, native: 30 }, + { start: 9, cost: 1, native: 10 }, + { start: 1, cost: 8, native: 80 }, + ]) + expect(s).toMatchObject({ lastRun: 1, typical: 3, highest: 8, runs: 3, windowDays: 30 }) + expect(s.native).toEqual({ lastRun: 10, typical: 30, highest: 80 }) + }) +}) + +const bq = ( + id: string, + startMin: number, + billed: number | null, + reservation: string | null = null, + slotMs = 0, + type = "MERGE", + extra: Row = {}, +): Row => ({ + job_id: id, + creation_time: new Date(startMin * MIN).toISOString(), + end_time: new Date((startMin + 1) * MIN).toISOString(), + statement_type: type, + total_bytes_billed: billed === null ? null : String(billed), + total_slot_ms: String(slotMs), + reservation_id: reservation, + cache_hit: "False", + user_email: "a@x.com", + destination_table_id: null, + ...extra, +}) + +describe("BigQuery pricing", () => { + test("on demand: bytes billed over a TiB at the rate", () => { + const { cost, reserved } = priceBigquery([bq("a", 0, 2 * TIB)], undefined, "model.s.m", {}) + expect(reserved).toBe(false) + expect(cost).toMatchObject({ basis: "history", lastRun: 12.5, native: { unit: "bytes_billed", lastRun: 2 * TIB }, rate: { value: 6.25, source: "default" } }) + }) + + test("the configured rate wins and is named config", () => { + const { cost } = priceBigquery([bq("a", 0, TIB)], undefined, "model.s.m", { bigqueryUsdPerTib: 5 }) + expect(cost).toMatchObject({ lastRun: 5, rate: { value: 5, source: "config" } }) + expect(cost.notes.join(" ")).not.toContain("default rate") + }) + + test("a default rate says which key sets it", () => { + const { cost } = priceBigquery([bq("a", 0, TIB)], undefined, "model.s.m", {}) + expect(cost.notes.join(" ")).toContain("cost.bigqueryUsdPerTib") + }) + + test("a reservation job is priced by slot time, not bytes", () => { + const { cost, reserved } = priceBigquery([bq("a", 0, 100 * TIB, "res", 3_600_000 * 2)], undefined, "model.s.m", {}) + expect(reserved).toBe(true) + expect(cost).toMatchObject({ lastRun: 0.12, native: { unit: "slot_hours", lastRun: 2 }, rate: { value: 0.06, unit: "USD/slot-hour" } }) + expect(cost.notes.join(" ")).toContain("an allocation, not the bill") + }) + + test("a configured slot-hour rate is used", () => { + const { cost } = priceBigquery([bq("a", 0, 0, "res", 3_600_000)], undefined, "model.s.m", { bigquerySlotHourUsd: 0.04 }) + expect(cost).toMatchObject({ lastRun: 0.04, rate: { value: 0.04, source: "config" } }) + }) + + test("mixed pricing sums both, keeps no single native unit, and says so", () => { + const { cost } = priceBigquery([bq("a", 0, TIB), bq("b", 100, 0, "res", 3_600_000)], undefined, "model.s.m", {}) + expect(cost.native).toBeUndefined() + expect(cost.highest).toBeCloseTo(6.25) + expect(cost.notes.join(" ")).toContain("some on demand") + // The newest run is the reservation's, so the headline rate is the slot rate; the on-demand rate is named too. + expect(cost.rate?.unit).toBe("USD/slot-hour") + expect(cost.notes.join(" ")).toContain("On-demand runs are priced at 6.25 USD/TiB (default).") + const configured = priceBigquery([bq("a", 0, TIB), bq("b", 100, 0, "res", 3_600_000)], undefined, "model.s.m", { bigqueryUsdPerTib: 5 }).cost + expect(configured.notes.join(" ")).toContain("On-demand runs are priced at 5 USD/TiB (from your config).") + }) + + test("all-reservation history names no on-demand rate", () => { + expect(priceBigquery([bq("b", 100, 0, "res", 3_600_000)], undefined, "model.s.m", {}).cost.notes.join(" ")).not.toContain("On-demand runs") + }) + + test("no job is no cost, and the message names the table and the unique_id", () => { + const { cost } = priceBigquery([], undefined, "model.s.m", {}) + expect(cost.basis).toBe("none") + expect(cost.unknownReason).toContain("No runs of model.s.m in the last 30 days were found in INFORMATION_SCHEMA.JOBS") + }) + + test("a script is priced from its children, each by its own reservation, and the parent is not added", () => { + const parent = bq("p", 0, 50 * TIB, null, 0, "SCRIPT") + const children: Row[] = [ + { job_id: "c1", parent_job_id: "p", statement_type: "CREATE_TABLE_AS_SELECT", total_bytes_billed: String(TIB), total_slot_ms: "0", reservation_id: null, cache_hit: "False" }, + { job_id: "c2", parent_job_id: "p", statement_type: "MERGE", total_bytes_billed: "0", total_slot_ms: String(3_600_000), reservation_id: "res", cache_hit: "False" }, + { job_id: "x", parent_job_id: "other", statement_type: "MERGE", total_bytes_billed: String(9 * TIB), total_slot_ms: "0", reservation_id: null, cache_hit: "False" }, + ] + const { cost, reserved } = priceBigquery([parent], children, "model.s.m", {}) + expect(reserved).toBe(true) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(6.25 + 0.06, 10) + }) + + test("a script whose children were not found is left out, not priced from its own row", () => { + const { cost } = priceBigquery([bq("p", 0, 50 * TIB, null, 0, "SCRIPT")], [], "model.s.m", {}) + expect(cost.basis).toBe("none") + expect(cost.notes.join(" ")).toContain("1 run left out") + }) + + test("an on-demand job with no bytes billed is unknown and its run is left out, never a zero", () => { + const { cost } = priceBigquery([bq("a", 0, TIB), bq("b", 100, null)], undefined, "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBe(6.25) + expect(cost.notes.join(" ")).toContain("1 run left out") + }) + + test("a cached job with zero bytes billed is a real zero", () => { + const { cost } = priceBigquery([bq("a", 0, 0, null, 0, "MERGE", { cache_hit: "True" })], undefined, "model.s.m", {}) + expect(cost).toMatchObject({ basis: "history", runs: 1, lastRun: 0 }) + // A $0 run gets no note claiming a minimum charge. + expect(cost.notes.some((n: string) => /at least|minimum|rounds up/i.test(n))).toBe(false) + expect(cost.notes).toContain("On-demand jobs are priced by the bytes BigQuery billed for each job.") + }) + + test("jobs by one user, each starting within a minute after the previous one ended, are one run; a longer gap is a new run", () => { + // Each bq() job lasts a minute: starts at 0, 1 and 2 minutes chain, a job at 5 starts 2 minutes after the last ended. + const chained = priceBigquery([bq("a", 0, TIB), bq("b", 1, TIB), bq("c", 2, TIB)], undefined, "model.s.m", {}) + expect(chained.cost.runs).toBe(1) + expect(chained.cost.lastRun).toBe(3 * 6.25) + expect(priceBigquery([bq("a", 0, TIB), bq("b", 5, TIB), bq("c", 10, TIB)], undefined, "model.s.m", {}).cost.runs).toBe(3) + // Exactly a minute after the previous job ended chains; a millisecond more does not. + const gap = (ms: number) => priceBigquery([bq("a", 0, TIB), { ...bq("b", 0, TIB), creation_time: new Date(MIN + ms + MIN).toISOString(), end_time: new Date(3 * MIN + ms).toISOString() }], undefined, "model.s.m", {}).cost.runs + expect(gap(0)).toBe(1) + expect(gap(1)).toBe(2) + }) + + test("a delete joins the build that starts within a minute after it ends, else is not part of its run", () => { + // The delete runs minutes 0 to 1; the build starts 30 s after it ends, so they are one run. + const build = (gapMs: number) => ({ ...bq("m", 0, TIB), creation_time: new Date(MIN + gapMs).toISOString(), end_time: new Date(2 * MIN + gapMs).toISOString() }) + const attached = priceBigquery([bq("d", 0, TIB, null, 0, "DELETE"), build(30_000)], undefined, "model.s.m", {}) + expect(attached.cost.runs).toBe(1) + expect(attached.cost.lastRun).toBe(12.5) + // More than a minute after it ends: two groups, and a delete alone is not a run, so only the build is priced. + const apart = priceBigquery([bq("d", 0, TIB, null, 0, "UPDATE"), build(60_001)], undefined, "model.s.m", {}) + expect(apart.cost.runs).toBe(1) + expect(apart.cost.lastRun).toBe(6.25) + // Exactly a minute after it ends still joins. + expect(priceBigquery([bq("d", 0, TIB, null, 0, "DELETE"), build(60_000)], undefined, "model.s.m", {}).cost.lastRun).toBe(12.5) + }) + + test("a CTAS and an INSERT post-hook 5 s later are one run, not a $6.25 run and a near-zero one", () => { + const rows = [ + bq("c", 0, TIB, null, 0, "CREATE_TABLE_AS_SELECT", { destination_table_id: "orders" }), + { ...bq("h", 0, 10 * 1024 ** 2, null, 0, "INSERT", { destination_table_id: "audit" }), creation_time: new Date(MIN + 5_000).toISOString(), end_time: new Date(MIN + 6_000).toISOString() }, + ] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(6.25 + (10 * 1024 ** 2 / TIB) * 6.25, 10) + expect(cost.highest).toBeCloseTo(cost.lastRun!, 10) + }) + + test("the batches of a microbatch model are one run", () => { + const batch = (id: string, startMin: number) => bq(id, startMin, TIB, null, 0, "MERGE", { destination_table_id: "orders" }) + const { cost } = priceBigquery([batch("b1", 0), batch("b2", 1), batch("b3", 2)], undefined, "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBe(3 * 6.25) + }) + + test("two scheduled invocations five minutes apart are two runs", () => { + const { cost } = priceBigquery([bq("a", 0, TIB), bq("b", 5, TIB)], undefined, "model.s.m", {}) + expect(cost.runs).toBe(2) + expect(cost.highest).toBe(6.25) + }) + + test("jobs of different users are different runs even when they chain in time", () => { + const rows = [bq("a", 0, TIB), bq("b", 1, TIB, null, 0, "MERGE", { user_email: "b@x.com" })] + expect(priceBigquery(rows, undefined, "model.s.m", {}).cost.runs).toBe(2) + }) +}) + +describe("BigQuery pre-run price", () => { + test("the estimate is the dry run's bytes at the on-demand rate, with no bound fields", () => { + expect(onDemandEstimate(2 * TIB, 6.25)).toBeCloseTo(12.5, 12) + expect(onDemandEstimate(0, 6.25)).toBe(0) + expect(onDemandEstimate(TIB / 2, 5)).toBeCloseTo(2.5, 12) + }) +}) + +describe("rates config and the text", () => { + test("only positive numbers are rates", () => { + expect(cleanRates({ bigqueryUsdPerTib: 5, bigquerySlotHourUsd: -1, snowflakeUsdPerCredit: 3, databricksUsdPerDbu: 2 })).toEqual({ bigqueryUsdPerTib: 5 }) + expect(cleanRates(undefined)).toEqual({}) + }) + + test("the text leads with the cost, or with why there is none", () => { + const known = costText({ basis: "history", currency: "USD", lastRun: 1.5, typical: 1, highest: 2, runs: 3, windowDays: 30, rate: { value: 6.25, unit: "USD/TiB", source: "config" }, notes: ["a note"] }) + expect(known.split("\n")[0]).toBe("Cost from 3 runs in the last 30 days: last run $1.50, typical $1.00 (median), highest $2.00.") + expect(known).toContain("Rate: 6.25 USD/TiB (from your config).") + expect(known).toContain("a note") + expect(costText({ basis: "none", currency: "USD", rate: null, notes: [], unknownReason: "no history" })).toBe("Cost unknown: no history") + }) + + test("a dry-run price is worded as an estimate that the bill can differ from", () => { + const text = costText({ basis: "dry_run", currency: "USD", rate: null, notes: [], selectOnly: { estimate: 2 } }, "1.0 TiB") + expect(text).toBe( + "Pre-run scan estimate (not the model's run history): BigQuery's dry run estimates the SELECT at 1.0 TiB, about $2.00 on-demand. BigQuery bills at least 10 MiB per query, which this estimate applies. The bill can differ: a cached or BI Engine result bills nothing, clustered tables often bill less after runtime pruning, and external sources and some queries are not fully counted.", + ) + for (const claim of ["at most", "at least $", "ceiling", "floor"]) expect(text).not.toContain(claim) + }) +}) + +describe("run boundary", () => { + const C = 1_000 * MIN + const at = (min: number) => new Date(C + min * MIN).toISOString() + const boundary = (...stmts: { user: string | null; start: number; end: number; tmp?: boolean }[]) => ({ cutoff: C, stmts }) + + test("a boundary that could not be read drops runs starting within the boundary span (96 h 10 min) of the cutoff and keeps later ones", () => { + const rows = [ + { ...bq("near", 0, TIB), creation_time: at(60), end_time: at(61) }, + { ...bq("far", 0, 2 * TIB), creation_time: at(5 * 24 * 60), end_time: at(5 * 24 * 60 + 1) }, + ] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}, { cutoff: C }) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(12.5, 10) + expect(cost.notes.join(" ")).toContain("1 run that may have started before the period read was left out.") + }) + + test("an unreadable boundary is measured from the cutoff itself: a run exactly the boundary span after it is dropped, one a millisecond later is kept", () => { + const at = (ms: number) => new Date(C + ms).toISOString() + const day = BOUNDARY_SPAN_MS + const run = (offset: number) => + priceBigquery([{ ...bq("a", 0, TIB), creation_time: at(offset), end_time: at(offset + 1000) }], undefined, "model.s.m", {}, { cutoff: C }).cost.basis + expect(run(day)).toBe("none") + expect(run(day + 1)).toBe("history") + }) + + test("without a boundary nothing is dropped, and a full result says only 500 statements were read", () => { + const rows = Array.from({ length: HISTORY_LIMIT }, (_, i) => bq(`q${i}`, i * 120, TIB)) + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}) + expect(cost.runs).toBe(HISTORY_LIMIT) + expect(cost.notes.join(" ")).toContain("Only the newest 500 statements were read") + }) + + test("BigQuery: an unread job by the same user that ended within a minute before a run began may belong to it; others do not", () => { + const rows = [ + { ...bq("near", 0, TIB), creation_time: at(0.5), end_time: at(1.5) }, + { ...bq("far", 0, TIB), creation_time: at(120), end_time: at(121) }, + ] + const price = (b: { user: string | null; start: number; end: number }) => priceBigquery(rows, undefined, "model.s.m", {}, boundary(b)).cost + const own = price({ user: "a@x.com", start: C - 3 * MIN, end: C - 0.2 * MIN }) + expect(own.runs).toBe(1) + expect(own.notes.join(" ")).toContain("1 run that may have started before the period read was left out.") + // Another user's job, or one that ended more than a minute before the run began, cannot have chained to it. + expect(price({ user: "someone@else.com", start: C - 3 * MIN, end: C - 0.2 * MIN }).runs).toBe(2) + expect(price({ user: "a@x.com", start: C - 6 * MIN, end: C - 5 * MIN }).runs).toBe(2) + }) + + test("BigQuery: a delete pre-hook and the insert_overwrite script 20 s later by the same user are one run, priced from the script's children", () => { + const rows = [ + bq("d", 0, TIB, null, 0, "DELETE"), + { ...bq("s", 0, 9 * TIB, null, 0, "SCRIPT"), creation_time: new Date(20_000).toISOString() }, + ] + const children: Row[] = [ + { job_id: "k", parent_job_id: "s", creation_time: new Date(21_000).toISOString(), statement_type: "INSERT", total_bytes_billed: String(2 * TIB), total_slot_ms: "0", reservation_id: null, cache_hit: "False" }, + ] + const { cost } = priceBigquery(rows, children, "model.s.m", {}) + // The script row has the user; its children have none. Without it the delete would be a run of its own. + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(18.75, 10) + }) + + const tmpCtas = (id: string, startMin: number, billed: number, user = "a@x.com", dest = "orders__dbt_tmp"): Row => + bq(id, startMin, billed, null, 0, "CREATE_TABLE_AS_SELECT", { user_email: user, destination_table_id: dest }) + + test("BigQuery: the CTAS into the temporary relation and the MERGE that follows it are one run", () => { + // The CTAS runs a minute (minute 0 to 1); the MERGE starts at minute 3, within ten minutes of its end. + const rows = [tmpCtas("t", 0, TIB), bq("m", 3, 2 * TIB)] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(18.75, 10) + }) + + test("BigQuery: a temporary-relation CTAS joins only a final build by the same user within ten minutes after it ends", () => { + expect(priceBigquery([tmpCtas("t", 0, TIB), bq("m", 3, TIB, null, 0, "MERGE", { user_email: "b@x.com" })], undefined, "model.s.m", {}).cost.runs).toBe(2) + expect(priceBigquery([tmpCtas("t", 0, TIB), bq("m", 12, TIB)], undefined, "model.s.m", {}).cost.runs).toBe(2) + // A CTAS into an ordinary table is a build of its own, not a temporary relation. + expect(priceBigquery([tmpCtas("t", 0, TIB, "a@x.com", "orders"), bq("m", 3, TIB)], undefined, "model.s.m", {}).cost.runs).toBe(2) + }) + + test("BigQuery: delete, temporary CTAS and merge are one run, even when the merge starts over a minute after the delete", () => { + const rows = [bq("d", 0, TIB, null, 0, "DELETE"), { ...tmpCtas("t", 0, TIB), creation_time: new Date(30_000).toISOString(), end_time: new Date(5 * MIN).toISOString() }, bq("m", 6, TIB)] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(18.75, 10) + }) + + test("BigQuery: a merge whose temporary CTAS ended just before the cutoff may be the end of a run that began unread, so it is dropped", () => { + const rows = [{ ...bq("m", 0, TIB), creation_time: at(2) }] + const stmt = (end: number, user = "a@x.com") => ({ user, start: C - 5 * MIN, end: C + end * MIN, tmp: true }) + const cost = (b: ReturnType) => priceBigquery(rows, undefined, "model.s.m", {}, boundary(b)).cost + expect(cost(stmt(0)).notes.join(" ")).toContain("1 run that may have started before the period read was left out.") + // Another user's CTAS, or one that ended over ten minutes before the merge, cannot have fed it. + expect(cost(stmt(0, "b@x.com")).runs).toBe(1) + expect(priceBigquery(rows, undefined, "model.s.m", {}, boundary({ user: "a@x.com", start: C - 30 * MIN, end: C - 20 * MIN, tmp: true })).cost.runs).toBe(1) + }) + + test("BigQuery: an unread CTAS that could have been a merge's temporary relation drops it even when the merge already pairs with a CTAS read", () => { + // The merge has its own CTAS in the result, but an unread one ended just before it too and could have been the one it took. + const rows = [{ ...tmpCtas("t", 0, TIB), creation_time: at(0), end_time: at(1) }, { ...bq("m", 0, TIB), creation_time: at(2) }] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}, boundary({ user: "a@x.com", start: C - 5 * MIN, end: C + 0, tmp: true })) + expect(cost.basis).toBe("none") + expect(cost.notes.join(" ")).toContain("1 run that may have started before the period read was left out.") + }) + + test("BigQuery: the temporary-relation rule is measured from the final build's start, not an attached delete's", () => { + // delete at +1 min chains to the CTAS at +1.2, which pairs with the merge at +3: the run starts at +1, its final build at +3. + const rows = [ + { ...bq("d", 0, TIB, null, 0, "DELETE"), creation_time: at(1), end_time: at(2) }, + { ...tmpCtas("t", 0, TIB), creation_time: at(1.2), end_time: at(2.2) }, + { ...bq("m", 0, TIB), creation_time: at(3), end_time: at(4) }, + ] + const price = (end: number) => priceBigquery(rows, undefined, "model.s.m", {}, boundary({ user: "a@x.com", start: C - 30 * MIN, end: C + end * MIN, tmp: true })).cost + // Ending at -8 minutes is eleven minutes before the merge's start (+3), outside its ten minutes of it: the run is whole. + expect(price(-8).runs).toBe(1) + // Ending 6 minutes before the cutoff is inside them. + expect(price(-6).basis).toBe("none") + }) + + test("BigQuery: an unread job is measured from the run's start, the earliest of its jobs", () => { + // A delete read at +0.1 min chains to the merge at +0.5 (it ends at +1.1): the run starts at +0.1. + const rows = [{ ...bq("d", 0, TIB, null, 0, "DELETE"), creation_time: at(0.1), end_time: at(0.3) }, { ...bq("m", 0, TIB), creation_time: at(0.5), end_time: at(1.5) }] + const run = (end: number) => priceBigquery(rows, undefined, "model.s.m", {}, boundary({ user: "a@x.com", start: C - 5 * MIN, end: C + end * MIN })).cost + // Ended 70 s before the run's start: too early to chain to it. + expect(run(-1.2).runs).toBe(1) + // Ended 50 s before it. + expect(run(-0.7).basis).toBe("none") + }) + + test("BigQuery: statement types are read in any case, so a lower-case merge still ends the run of its temporary CTAS", () => { + const rows = [tmpCtas("t", 0, TIB), bq("m", 3, 2 * TIB, null, 0, "merge")] + rows[0].statement_type = "create_table_as_select" + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(18.75, 10) + }) + + test("BigQuery: a delete joins only a build by the same user", () => { + const rows = [ + bq("d", 0, TIB, null, 0, "DELETE", { user_email: "a@x.com" }), + { ...bq("m", 0, TIB, null, 0, "MERGE", { user_email: "b@x.com" }), creation_time: new Date(20_000).toISOString() }, + ] + // The delete is another user's: it does not join the merge's run, and it makes none. + const other = priceBigquery(rows, undefined, "model.s.m", {}).cost + expect(other.runs).toBe(1) + expect(other.lastRun).toBe(6.25) + const same = [{ ...rows[0], user_email: "b@x.com" }, rows[1]] + expect(priceBigquery(same, undefined, "model.s.m", {}).cost.lastRun).toBe(12.5) + }) + + test("BigQuery: when the boundary alone leaves no run, the message says so rather than blaming bytes billed", () => { + const rows = [{ ...bq("near", 0, TIB), creation_time: at(0.5), end_time: at(1.5) }] + const cost = priceBigquery(rows, undefined, "model.s.m", {}, boundary({ user: "a@x.com", start: C - 3 * MIN, end: C - 0.2 * MIN })).cost + expect(cost.basis).toBe("none") + expect(cost.unknownReason).toContain("may have started before the period read") + expect(cost.unknownReason).not.toContain("no bytes billed") + }) +}) + +describe("boundary SQL", () => { + const needle = needleFor("model.shop.orders") + + // A cutoff far enough from zero that every derived instant is distinct and positive. + const CUT = 1_780_000_000_000 + const w = boundaryWindow(CUT) + + test("the window is derived from the cutoff itself: the start bound reaches it, every lookback is measured from it", () => { + expect(w).toEqual({ + startBeforeMs: CUT + 1, + startAfterMs: CUT - BOUNDARY_SPAN_MS, + liveStartAfterMs: CUT - BOUNDARY_SPAN_MS, + invocationStartAfterMs: CUT - 180 * 86_400_000, + joinEndAtLeastMs: CUT - 60_000, + tmpEndAtLeastMs: CUT - 600_000, + }) + }) + + test("BigQuery: top-level jobs of the same view, each lookback measured from the cutoff", () => { + const sql = bigqueryBoundarySql({ project: "p", location: "EU", needle, view: "JOBS_BY_USER", window: w }) + expect(sql).toContain("`p`.`region-eu`.INFORMATION_SCHEMA.JOBS_BY_USER") + expect(sql).toContain(`creation_time < timestamp_millis(${CUT + 1})`) + // Any matched job (a read too) that ended within a minute before the cutoff can chain to a later run, by end time. + expect(sql).toContain(`end_time >= timestamp_millis(${CUT - 60_000})`) + expect(sql).not.toContain("statement_type) in") + expect(sql).toContain("strpos(query, 'altimate_cost_read') = 0") + // The identity the main grouping pairs on: the destination table and dataset. + expect(sql).toContain("destination_table.table_id as destination_table_id, destination_table.dataset_id as destination_dataset_id") + expect(sql).toContain("user_email") + // And the CTAS into dbt's temporary relation that ended within ten minutes before it. + expect(sql).toContain("upper(statement_type) = 'CREATE_TABLE_AS_SELECT' and ends_with(destination_table.table_id, '__dbt_tmp')") + expect(sql).toContain(`end_time >= timestamp_millis(${CUT - 600_000})`) + expect(sql).not.toContain(`${CUT + 1 - 60_000}`) + expect(sql).not.toContain(`${CUT + 1 - 600_000}`) + expect(sql).toContain("parent_job_id is null") + expect(sql).toContain(`strpos(query, '"node_id": "model.shop.orders"') > 0`) + }) + + test("one boundary read: finished jobs from the 96-hour-10-minute lookback, or jobs still going from no further back, going first", () => { + const sql = bigqueryBoundarySql({ project: "p", needle, window: boundaryWindow(CUT) }) + const going = "(upper(state) in ('PENDING','RUNNING') or end_time is null)" + // A job still going cannot be older than the longest job span either, so it is not read from the window's start. + expect(sql).toContain(`(${going} and creation_time > timestamp_millis(${CUT - BOUNDARY_SPAN_MS}))`) + expect(sql).toContain(`creation_time > timestamp_millis(${CUT - BOUNDARY_SPAN_MS}) and upper(state) = 'DONE' and error_result is null`) + expect(sql).toContain(`order by ${going} desc, creation_time desc limit 500`) + expect(sql).toContain("end_time, state, statement_type") + expect(sql).not.toContain("liveStart") + // The largest configurable queue timeout (48 hours) plus the 48-hour CREATE MODEL timeout. + expect(MAX_JOB_SPAN_MS).toBe(96 * 3_600_000) + // The longest a job can be in flight plus the longest join gap (a temporary CTAS to its final build, ten minutes). + expect(BOUNDARY_SPAN_MS).toBe(96 * 3_600_000 + 10 * 60_000) + }) + + test("the boundary query reads the invocation label; the invocations' own jobs are a read of their own, back to the 180 days JOBS keeps", () => { + const plain = bigqueryBoundarySql({ project: "p", needle: "n", window: w }) + expect(plain).toContain("as dbt_invocation_id") + expect(plain).not.toContain("unnest(labels) where key = 'dbt_invocation_id') in") + const sql = bigqueryInvocationSql({ project: "p", location: "EU", needle: "n", view: "JOBS_BY_USER", window: boundaryWindow(CUT), invocations: ["i-1", "i'2", "i-1"] }) + expect(sql).toContain("select /* invocation jobs */ /* altimate_cost_read */ job_id") + expect(sql).toContain("`p`.`region-eu`.INFORMATION_SCHEMA.JOBS_BY_USER") + // An invocation has no span limit: its jobs are read as far back as JOBS keeps them, not the 96-hour lookback. + expect(sql).toContain(`creation_time < timestamp_millis(${CUT + 1}) and creation_time > timestamp_millis(${CUT - 180 * 86_400_000})`) + expect(sql).toContain("(upper(state) = 'DONE' and error_result is null) or upper(state) in ('PENDING','RUNNING')") + expect(sql).toContain("(select value from unnest(labels) where key = 'dbt_invocation_id') in ('i-1','i\\'2')") + expect(sql).toContain("strpos(query, 'altimate_cost_read') = 0") + expect(sql).toContain("parent_job_id is null") + expect(sql).toContain("order by creation_time desc limit 500") + }) + + test("the boundary query returns the id of each statement, so the ones already read can be excluded", () => { + expect(bigqueryBoundarySql({ project: "p", needle: "n", window: boundaryWindow(1) })).toContain("select /* run boundary */ /* altimate_cost_read */ job_id") + }) + + test("the BigQuery history reads the job's user, which a delete must share with the build it joins", () => { + expect(bigqueryHistorySql({ project: "p", needle: "n", asOfMs: ASOF })).toContain("job_id, user_email,") + expect(bigqueryHistorySql({ project: "p", needle: "n", asOfMs: ASOF })).toContain("destination_table.table_id as destination_table_id") + }) + +}) + +describe("script children at their limit", () => { + test("a script that began before the oldest child returned is unknown, a later one is priced", () => { + const old = bq("old", 700, null, null, 0, "SCRIPT") + const recent = bq("recent", 1000, null, null, 0, "SCRIPT") + const kid = (id: string, parent: string, startMin: number): Row => ({ + job_id: id, + parent_job_id: parent, + creation_time: new Date(startMin * MIN).toISOString(), + statement_type: "MERGE", + total_bytes_billed: String(TIB), + total_slot_ms: "0", + reservation_id: null, + cache_hit: "False", + }) + // Every child belongs to a matched script and starts during it. The oldest child returned is the old script's, a + // moment after it began: the cut happened there, so the old script may have had more children before it, while the + // recent one (minute 1000) began after the cut and is whole. + const children = [kid("oc", "old", 700.1), ...Array.from({ length: BQ_CHILD_LIMIT - 1 }, (_, i) => kid(`x${i}`, "recent", 1000 + i * 1e-5))] + const { cost } = priceBigquery([old, recent, bq("filler", 5000, TIB)], children, "model.s.m", {}) + expect(cost.runs).toBe(2) + expect(cost.notes.join(" ")).toContain("1 run left out") + }) +}) + +describe("review follow-ups: BigQuery temporary relation pairing", () => { + const C2 = 5_000 * MIN + const tmp = (id: string, startMin: number, billed: number, user = "a@x.com"): Row => + bq(id, startMin, billed, null, 0, "CREATE_TABLE_AS_SELECT", { user_email: user, destination_table_id: "orders__dbt_tmp" }) + + const ds = (row: Row, dataset: string): Row => ({ ...row, destination_dataset_id: dataset }) + + test("two overlapping invocations by one user pair one CTAS with one MERGE each, and their cost is whole", () => { + // tmpA 0-1 min (1 TiB), tmpB 0.5-1.5 (2 TiB), mergeA at 2 (3 TiB), mergeB at 4 (4 TiB): they overlap, so one run. + const rows = [tmp("tA", 0, TIB), tmp("tB", 0.5, 2 * TIB), bq("mA", 2, 3 * TIB), bq("mB", 4, 4 * TIB)] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(10 * 6.25, 10) + }) + + test("a temporary CTAS pairs only with a final build into the same dataset, so a MERGE into another dataset five minutes later is a second run", () => { + // The CTAS (prod dataset) ends at minute 1; a MERGE into dev starts at minute 6: a gap of five minutes, so not chained either. + const rows = [ds(tmp("t", 0, TIB), "prod"), ds(bq("m", 6, TIB), "dev")] + expect(priceBigquery(rows, undefined, "model.s.m", {}).cost.runs).toBe(2) + // The same dataset pairs them: one run. + expect(priceBigquery([ds(tmp("t", 0, TIB), "prod"), ds(bq("m", 6, TIB), "prod")], undefined, "model.s.m", {}).cost.runs).toBe(1) + }) + + test("a prod CTAS that ended first does not take the dev MERGE: the dev pair stays six minutes from it, a run of its own", () => { + // The prod CTAS (100 TiB) ends at minute 1 and the dev CTAS (1 TiB) at minute 8; the dev MERGE starts at minute 8, + // seven minutes after the prod CTAS ended, so by time alone the prod CTAS could take it. With the dataset it cannot: + // the dev pair is minutes 7-9 and the prod CTAS, with no prod MERGE, is a separate run. + const rows = [ds(tmp("tp", 0, 100 * TIB), "prod"), ds(tmp("td", 7, TIB), "dev"), ds(bq("md", 8, TIB), "dev")] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}) + expect(cost.runs).toBe(2) + expect(cost.highest).toBeCloseTo(100 * 6.25, 10) + expect(cost.lastRun).toBeCloseTo(2 * 6.25, 10) + }) + + test("interleaved prod and dev invocations by one user with no invocation label overlap in time, so they are reported as one run of both costs", () => { + // Without the label, grouping is by user and time, not by dataset. + const rows = [ds(tmp("tp", 0, 100 * TIB), "prod"), ds(tmp("td", 1, TIB), "dev"), ds(bq("md", 3, TIB), "dev"), ds(bq("mp", 6, 100 * TIB), "prod")] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(202 * 6.25, 10) + }) + + test("the same interleaved jobs labelled with their own invocation ids are two runs, each with its own cost", () => { + const inv = (row: Row, id: string): Row => ({ ...row, dbt_invocation_id: id }) + const rows = [ + inv(ds(tmp("tp", 0, 100 * TIB), "prod"), "prod-1"), + inv(ds(tmp("td", 1, TIB), "dev"), "dev-1"), + inv(ds(bq("md", 3, TIB), "dev"), "dev-1"), + inv(ds(bq("mp", 6, 100 * TIB), "prod"), "prod-1"), + ] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}) + expect(cost.runs).toBe(2) + expect(cost.highest).toBeCloseTo(200 * 6.25, 10) + expect(cost.typical).toBeCloseTo(((200 + 2) / 2) * 6.25, 10) + }) + + test("each temporary CTAS takes its own final build, so two invocations whose merges are minutes apart stay one run", () => { + // Both CTASs end by minute 1.2; the merges start at 2 and 9. If both CTASs paired with the first merge, the second + // merge would be six minutes from anything else and become a run of its own. + const rows = [tmp("tA", 0, TIB), tmp("tB", 0.2, TIB), bq("m1", 2, TIB), bq("m2", 9, TIB)] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(4 * 6.25, 10) + }) + + test("a second CTAS with no unclaimed final build is still part of the run and counted", () => { + const { cost } = priceBigquery([tmp("tA", 0, TIB), tmp("tB", 0.2, TIB), bq("m", 2, TIB)], undefined, "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(3 * 6.25, 10) + }) + + test("a run whose temporary CTAS is far from its merge keeps the pair as one job", () => { + // The CTAS ends at minute 1 and the merge starts at minute 9 (within ten): the pair spans the gap, so a delete at minute 5 is in the run. + const rows = [tmp("t", 0, TIB), bq("m", 9, TIB), bq("h", 5, TIB, null, 0, "DELETE")] + expect(priceBigquery(rows, undefined, "model.s.m", {}).cost.runs).toBe(1) + }) + + test("a job unread before the cutoff that overlapped a run's start may belong to it; one that ended long before cannot", () => { + const rows = [{ ...bq("m", 0, TIB), creation_time: new Date(C2 + 2 * MIN).toISOString(), end_time: new Date(C2 + 3 * MIN).toISOString() }] + const run = (end: number) => + priceBigquery(rows, undefined, "model.s.m", {}, { cutoff: C2, stmts: [{ user: "a@x.com", start: C2 - 5 * MIN, end: C2 + end * MIN, tmp: true }] }).cost + // Still running an hour after the run started: it overlaps it, so they chain and the run is dropped. + expect(run(60).notes.join(" ")).toContain("1 run that may have started before the period read was left out.") + // Ending a minute before it starts, it could be the merge's own temporary relation: the run is dropped. + expect(run(1).notes.join(" ")).toContain("1 run that may have started before the period read was left out.") + // Ended half an hour before: too early for either rule. + expect(run(-30).runs).toBe(1) + }) +}) + +describe("review follow-ups: rates, location, ephemeral and pricing mode", () => { + test("a rate that is zero, negative, not finite or above the maximum is ignored and named", () => { + const raw = { bigqueryUsdPerTib: 1e308, bigquerySlotHourUsd: -1 } + expect(cleanRates(raw)).toEqual({}) + // null (what a saved infinity reads back as) is ignored and named like any other unusable value. + expect(cleanRates({ bigqueryUsdPerTib: null })).toEqual({}) + expect(ignoredRateNotes({ bigqueryUsdPerTib: null, bigquerySlotHourUsd: 5 })).toEqual([expect.stringContaining("cost.bigqueryUsdPerTib is ignored")]) + expect(ignoredRateNotes(raw).map((n) => n.split(" ")[0])).toEqual(["cost.bigqueryUsdPerTib", "cost.bigquerySlotHourUsd"]) + expect(cleanRates({ bigqueryUsdPerTib: MAX_RATE + 1 })).toEqual({}) + expect(cleanRates({ bigqueryUsdPerTib: MAX_RATE, bigquerySlotHourUsd: 0.01 })).toEqual({ bigqueryUsdPerTib: MAX_RATE, bigquerySlotHourUsd: 0.01 }) + expect(ignoredRateNotes({ bigqueryUsdPerTib: 0 })).toHaveLength(1) + expect(ignoredRateNotes({ bigqueryUsdPerTib: 5 })).toEqual([]) + expect(ignoredRateNotes({})).toEqual([]) + expect(ignoredRateNotes(undefined)).toEqual([]) + }) + + test("two huge runs priced at a rate the config allows still have a finite median", () => { + const { cost } = priceBigquery([bq("a", 0, TIB), bq("b", 5, TIB)], undefined, "model.s.m", { bigqueryUsdPerTib: MAX_RATE }) + expect(Number.isFinite(cost.typical)).toBe(true) + }) + + test("the history reads the destination dataset, which a temporary CTAS must share with the build it pairs with", () => { + expect(bigqueryHistorySql({ project: "p", needle: "n", asOfMs: ASOF })).toContain("destination_table.dataset_id as destination_dataset_id") + }) + + test("the location read is named: the target's own, or the us region a target with none falls back to", () => { + expect(locationNote("EU")).toBe("Location read: region-eu (the target's location).") + for (const none of [undefined, null, "", " "]) expect(locationNote(none)).toContain("sets no location, so region-us was read") + expect(locationNote("us")).toBe("Location read: region-us (the target's location).") + const empty = (opts: { location?: string; materialized?: string }) => priceBigquery([], undefined, "model.s.m", {}, undefined, opts).cost.unknownReason! + expect(empty({ location: locationNote(undefined) })).toContain("region-us was read") + expect(empty({})).not.toContain("region-") + }) + + test("an ephemeral model's no-runs reason says it never runs on its own", () => { + const reason = (materialized: string) => priceBigquery([], undefined, "model.s.m", {}, undefined, { materialized }).cost.unknownReason! + expect(reason("ephemeral")).toContain("An ephemeral model never runs on its own: its SQL is inlined into the models that ref it") + expect(reason("table")).not.toContain("ephemeral") + }) + + test("a history whose newest run differs from older ones says the pricing may have changed", () => { + const old = bq("a", 0, TIB) + const newest = bq("b", 10, null, "res-1", 3_600_000) + expect(priceBigquery([old, newest], undefined, "model.s.m", {}).cost.notes.join(" ")).toContain("The newest run was in a reservation and older ones on demand") + const reverse = priceBigquery([bq("a", 0, null, "res-1", 3_600_000), bq("b", 10, TIB)], undefined, "model.s.m", {}) + expect(reverse.cost.notes.join(" ")).toContain("The newest run was on demand and older ones in a reservation") + expect(priceBigquery([bq("a", 0, TIB), bq("b", 10, TIB)], undefined, "model.s.m", {}).cost.notes.join(" ")).not.toContain("newest run") + }) +}) + +describe("review follow-ups: read-only hooks, boundary identity and unfinished runs", () => { + const C3 = 9_000 * MIN + const at = (min: number) => new Date(C3 + min * MIN).toISOString() + const job = (id: string, startMin: number, durMin: number, billed: number | null, type: string, extra: Row = {}): Row => ({ + ...bq(id, 0, billed, null, 0, type, extra), + creation_time: at(startMin), + end_time: at(startMin + durMin), + }) + const ds = (row: Row, dataset: string): Row => ({ ...row, destination_dataset_id: dataset }) + const tmp = (id: string, startMin: number, dataset: string) => + ds(job(id, startMin, 1, TIB, "CREATE_TABLE_AS_SELECT", { destination_table_id: "orders__dbt_tmp" }), dataset) + + test("a SELECT hook is billed and part of the invocation: a CTAS and a SELECT 5 s later are one run of both costs", () => { + const rows = [ + job("c", 0, 1, TIB, "CREATE_TABLE_AS_SELECT", { destination_table_id: "orders" }), + { ...job("s", 1, 0.1, TIB, "SELECT"), creation_time: new Date(C3 + MIN + 5_000).toISOString(), end_time: new Date(C3 + 2 * MIN).toISOString() }, + ] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(12.5, 10) + }) + + test("a group of reads only (dbt show) is not a run and is not priced", () => { + const { cost } = priceBigquery([job("s1", 0, 1, TIB, "SELECT"), job("s2", 1, 1, TIB, "SELECT")], undefined, "model.s.m", {}, undefined, { location: locationNote("EU") }) + expect(cost.basis).toBe("none") + expect(cost.unknownReason).toContain("only read data") + expect(cost.unknownReason).toContain("region-eu") + // Beside a build run, reads of another invocation are not counted as one. + const mixed = priceBigquery([job("m", 0, 1, TIB, "MERGE"), job("s", 30, 1, 5 * TIB, "SELECT")], undefined, "model.s.m", {}).cost + expect(mixed.runs).toBe(1) + expect(mixed.lastRun).toBe(6.25) + }) + + test("an unread job of any type, SELECT included, that ended within a minute before a run may belong to it", () => { + const rows = [job("m", 5, 1, TIB, "MERGE")] + const stmt = { user: "a@x.com", start: C3 - 3 * MIN, end: C3 + 4.5 * MIN } + expect(priceBigquery(rows, undefined, "model.s.m", {}, { cutoff: C3, stmts: [stmt] }).cost.basis).toBe("none") + }) + + test("a temporary CTAS in the boundary is evidence only for a final build into its own dataset", () => { + // The prod CTAS ended a minute before the cutoff; the dev MERGE starts five minutes after it. Same user. + const rows = [ds(job("m", 5, 1, TIB, "MERGE"), "dev")] + const run = (dataset: string) => + priceBigquery(rows, undefined, "model.s.m", {}, { cutoff: C3, stmts: [{ user: "a@x.com", start: C3 - 5 * MIN, end: C3 - MIN, tmp: true, dataset }] }).cost + // Another dataset: it could not have been this MERGE's relation, so the complete run stays. + expect(run("prod").runs).toBe(1) + expect(run("dev").basis).toBe("none") + // A MERGE that names no dataset (a script's) keeps the user-and-time rule. + const unnamed = [job("m", 5, 1, TIB, "MERGE")] + expect(priceBigquery(unnamed, undefined, "model.s.m", {}, { cutoff: C3, stmts: [{ user: "a@x.com", start: C3 - 5 * MIN, end: C3 - MIN, tmp: true, dataset: "prod" }] }).cost.basis).toBe("none") + }) + + test("a run with a job still running is left out, and the note says so", () => { + const asOf = C3 + 20 * MIN + const rows = [ + tmp("t", 0, "d"), + { ...ds(job("m", 3, 1, null, "MERGE"), "d"), state: "RUNNING", end_time: null }, + job("old", -600, 1, TIB, "MERGE"), + ] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}, undefined, { asOfMs: asOf }) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBe(6.25) + expect(cost.notes).toContain("A run still in progress was left out.") + // Without the finished CTAS being priced alone as a $6.25 run. + expect(cost.highest).toBe(6.25) + }) + + test("a pending job counts whatever its end time says, and an only-in-progress history is none", () => { + const pending = { ...job("m", 0, 1, TIB, "MERGE"), state: "PENDING" } + const { cost } = priceBigquery([pending], undefined, "model.s.m", {}, undefined, { asOfMs: C3 + 1000 * MIN }) + expect(cost.basis).toBe("none") + expect(cost.unknownReason).toContain("still in progress") + // No instant given (older callers): a pending job still never closes. + expect(priceBigquery([pending], undefined, "model.s.m", {}).cost.basis).toBe("none") + }) + + test("a run whose last job ended within a minute of the instant read may not be over: left out; a minute earlier it is whole", () => { + const run = (endAgoMs: number) => + priceBigquery([job("m", 0, 1, TIB, "MERGE")], undefined, "model.s.m", {}, undefined, { asOfMs: C3 + MIN + endAgoMs }).cost + expect(run(30_000).basis).toBe("none") + expect(run(30_000).notes).toContain("A run still in progress was left out.") + expect(run(60_000).basis).toBe("none") + expect(run(60_001).runs).toBe(1) + }) + + test("one run that mixes pricing modes (a script's children) does not claim older runs differ", () => { + const script = job("s", 0, 1, null, "SCRIPT") + const kid = (id: string, reservation: string | null, slotMs: string): Row => ({ job_id: id, parent_job_id: "s", creation_time: at(0.1), statement_type: "MERGE", total_bytes_billed: String(TIB), total_slot_ms: slotMs, reservation_id: reservation, cache_hit: "False" }) + const { cost } = priceBigquery([script], [kid("k1", null, "0"), kid("k2", "res", "3600000")], "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.notes.join(" ")).toContain("Some runs ran in a reservation") + expect(cost.notes.join(" ")).not.toContain("newest run") + }) + + test("a job still running that could chain into a run leaves it out as in progress, wherever the run is", () => { + const A = "a@x.com" + const price = (rows: Row[], boundary: Parameters[4]) => priceBigquery(rows, undefined, "model.s.m", {}, boundary).cost + const live = (user = A, startMin = -1) => ({ user, start: C3 + startMin * MIN }) + // The boundary read was full (no statements), so only the fallback applies besides the live evidence: a pending job a + // minute before the cutoff and A's build 100 hours after it. The build is past the fallback's 96 hours 10 minutes, yet still left out. + const late = [job("m", 100 * 60, 1, TIB, "MERGE")] + const full = price(late, { cutoff: C3, live: [live()] }) + expect(full.basis).toBe("none") + expect(full.notes).toContain("A run still in progress was left out.") + // The same build with no live job is kept (it is beyond the fallback's 96 hours 10 minutes). + expect(price(late, { cutoff: C3 }).runs).toBe(1) + // Another user's live job leaves it alone; a run that ended long before the live job began is not chained to it. + expect(price(late, { cutoff: C3, live: [live("b@x.com")] }).runs).toBe(1) + expect(price(late, { cutoff: C3, live: [live(A, 105 * 60)] }).runs).toBe(1) + // A run that ended within a minute before the live job began is chained to it. + expect(price(late, { cutoff: C3, live: [live(A, 100 * 60 + 1.5)] }).basis).toBe("none") + // A finished unread job only makes the run uncertain. + expect(price([job("m", 5, 1, TIB, "MERGE")], { cutoff: C3, stmts: [{ user: A, start: C3 - 30 * MIN, end: C3 + 4.5 * MIN }] }).notes.join(" ")).toContain("may have started before") + }) + + test("when the boundary read is full, every run by the users with a job still going is left out", () => { + const rows = [job("a1", 100 * 60, 1, TIB, "MERGE"), job("b1", 100 * 60, 1, TIB, "MERGE", { user_email: "b@x.com" })] + const cost = priceBigquery(rows, undefined, "model.s.m", {}, { cutoff: C3, live: [{ user: "a@x.com", start: C3 + 7000 * MIN }], liveFullUsers: ["a@x.com"] }).cost + // The live jobs began long after a1 ended, so only the full read's rule leaves it out; b's run stays. + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBe(6.25) + expect(cost.notes.join(" ")).toContain("The read of jobs before the period was full") + expect(cost.notes).toContain("A run still in progress was left out.") + }) + + test("a finished-looking job with no end time is still running", () => { + const cost = priceBigquery([{ ...job("m", 0, 1, TIB, "MERGE"), end_time: null }], undefined, "model.s.m", {}, undefined, { asOfMs: C3 + 1000 * MIN }).cost + expect(cost.basis).toBe("none") + expect(cost.notes).toContain("A run still in progress was left out.") + }) + + test("a run whose last job is a temporary CTAS can still be joined for ten minutes, so it is in progress until then", () => { + const ctas = tmp("t", 0, "d") // minutes 0 to 1 + const at = (minutes: number) => ({ asOfMs: C3 + minutes * MIN }) + const price = (rows: Row[], minutes: number) => priceBigquery(rows, undefined, "model.s.m", {}, undefined, at(minutes)).cost + // Ended at minute 1: two minutes later its MERGE may still come. + const early = price([ctas], 3) + expect(early.basis).toBe("none") + expect(early.notes).toContain("A run still in progress was left out.") + // Eleven minutes after it ended with no MERGE, it is a run of its own. + expect(price([ctas], 12).runs).toBe(1) + // The same wait is not asked of a job that is not a temporary CTAS: a MERGE ended two minutes ago is whole. + expect(price([job("m", 0, 1, TIB, "MERGE")], 3).runs).toBe(1) + }) + + test("a SELECT hook after an unpaired temporary CTAS does not close the CTAS's ten minutes", () => { + // The CTAS runs minutes 0 to 1 and a SELECT hook 1.1 to 1.5: the last job ended at 1.5, but the MERGE may still come. + const rows = [tmp("t", 0, "d"), job("s", 1.1, 0.4, TIB, "SELECT")] + const price = (minutes: number) => priceBigquery(rows, undefined, "model.s.m", {}, undefined, { asOfMs: C3 + minutes * MIN }).cost + expect(price(3).basis).toBe("none") + expect(price(3).notes).toContain("A run still in progress was left out.") + // More than ten minutes after the CTAS ended, with no MERGE, it is a run (the SELECT's cost is in it). + const done = price(12) + expect(done.runs).toBe(1) + expect(done.lastRun).toBeCloseTo(12.5, 10) + // A temporary CTAS a final build took does not hold the run open. + const paired = [tmp("t", 0, "d"), { ...job("m", 2, 1, TIB, "MERGE"), destination_dataset_id: "d" }] + expect(priceBigquery(paired, undefined, "model.s.m", {}, undefined, { asOfMs: C3 + 5 * MIN }).cost.runs).toBe(1) + }) + + describe("invocation labels", () => { + const inv = (row: Row, id: string): Row => ({ ...row, dbt_invocation_id: id }) + const price = (rows: Row[], boundary?: Parameters[4]) => priceBigquery(rows, undefined, "model.s.m", {}, boundary).cost + + test("one invocation whose jobs are minutes apart (a slow hook) is one run", () => { + const rows = [inv(job("m", 0, 1, TIB, "MERGE"), "i1"), inv(job("h", 6, 1, TIB, "INSERT"), "i1")] + const cost = price(rows) + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBe(12.5) + // The same jobs without the label are two runs, by the user-and-time rule. + expect(price(rows.map((r) => ({ ...r, dbt_invocation_id: null }))).runs).toBe(2) + }) + + test("two invocations by one user within a minute of each other are two runs, and a labelled job never joins an unlabelled one", () => { + const two = price([inv(job("a", 0, 1, TIB, "MERGE"), "i1"), inv(job("b", 1, 1, 2 * TIB, "MERGE"), "i2")]) + expect(two.runs).toBe(2) + expect(two.highest).toBe(12.5) + const mixed = price([inv(job("a", 0, 1, TIB, "MERGE"), "i1"), job("b", 1, 1, TIB, "MERGE")]) + expect(mixed.runs).toBe(2) + }) + + test("an unread job of the same invocation leaves the run out, however long before it ended; another invocation's does not", () => { + const rows = [inv(job("m", 5, 1, TIB, "MERGE"), "i1")] + const stmt = (id: string) => ({ user: "a@x.com", start: C3 - 600 * MIN, end: C3 - 500 * MIN, inv: id }) + const left = price(rows, { cutoff: C3, stmts: [stmt("i1")] }) + expect(left.basis).toBe("none") + expect(left.notes.join(" ")).toContain("may have started before") + expect(price(rows, { cutoff: C3, stmts: [stmt("i2")] }).runs).toBe(1) + // Even a job that ended seconds before the run began, by the same user, is not of the run when its id differs. + expect(price(rows, { cutoff: C3, stmts: [{ user: "a@x.com", start: C3 - 3 * MIN, end: C3 + 4.5 * MIN, inv: "i2" }] }).runs).toBe(1) + // Labelled and unlabelled jobs are never one run, as in the main grouping: an unlabelled unread job near a labelled run + // does not leave it out, and a labelled one does not leave out an unlabelled run. + const near = { user: "a@x.com", start: C3 - 3 * MIN, end: C3 + 4.5 * MIN } + expect(price(rows, { cutoff: C3, stmts: [near] }).runs).toBe(1) + expect(price([job("m", 5, 1, TIB, "MERGE")], { cutoff: C3, stmts: [{ ...near, inv: "i1" }] }).runs).toBe(1) + expect(price([job("m", 5, 1, TIB, "MERGE")], { cutoff: C3, stmts: [near] }).basis).toBe("none") + // The same holds for a job still going. + expect(price(rows, { cutoff: C3, stmts: [], live: [{ user: "a@x.com", start: C3 - 3 * MIN }] }).runs).toBe(1) + expect(price([job("m", 5, 1, TIB, "MERGE")], { cutoff: C3, stmts: [], live: [{ user: "a@x.com", start: C3 - 3 * MIN, inv: "i1" }] }).runs).toBe(1) + }) + + test("a job still running with the run's invocation id leaves it in progress; another id does not", () => { + const rows = [inv(job("m", 75 * 60, 1, TIB, "MERGE"), "i1")] + const running = (id: string, start: number) => ({ cutoff: C3, live: [{ user: "a@x.com", start: C3 + start * MIN, inv: id }] }) + // The same invocation began long before; no time rule is needed. + const same = price(rows, running("i1", -3000)) + expect(same.notes).toContain("A run still in progress was left out.") + // Another invocation's live job, which started before the run ended, is not part of it. + expect(price(rows, running("i2", 75 * 60 - 1)).runs).toBe(1) + }) + + test("a script is grouped by its own row's label, its children carrying none", () => { + const script = inv(job("s", 0, 1, null, "SCRIPT"), "i1") + const kid: Row = { job_id: "k", parent_job_id: "s", creation_time: at(0.2), statement_type: "MERGE", total_bytes_billed: String(2 * TIB), total_slot_ms: "0", reservation_id: null, cache_hit: "False" } + const hook = inv(job("h", 6, 1, TIB, "INSERT"), "i1") + const cost = priceBigquery([script, hook], [kid], "model.s.m", {}).cost + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBeCloseTo(18.75, 10) + }) + + test("an invocation with a temporary CTAS and no final build yet is still held open for ten minutes", () => { + const rows = [inv(tmp("t", 0, "d"), "i1"), inv(job("s", 1.1, 0.4, TIB, "SELECT"), "i1")] + const at = (minutes: number) => priceBigquery(rows, undefined, "model.s.m", {}, undefined, { asOfMs: C3 + minutes * MIN }).cost + expect(at(3).notes).toContain("A run still in progress was left out.") + expect(at(12).runs).toBe(1) + }) + }) + + test("two runs in progress are counted in one note", () => { + const asOf = C3 + 100 * MIN + const rows = [job("a", 98, 1, TIB, "MERGE"), { ...job("b", 0, 1, TIB, "MERGE", { user_email: "b@x.com" }), state: "RUNNING" }, job("c", -600, 1, TIB, "MERGE")] + const { cost } = priceBigquery(rows, undefined, "model.s.m", {}, undefined, { asOfMs: asOf }) + expect(cost.runs).toBe(1) + expect(cost.notes).toContain("2 runs still in progress were left out.") + }) +}) + +describe("review: targets, scope, attribution, Python, permissions", () => { + const tgt = (row: Row, target: string): Row => ({ ...row, target_name: target }) + const run = (id: string, startMin: number, billed: number, target: string): Row => tgt(bq(id, startMin * 10, billed), target) + const price = (rows: Row[], target?: string) => priceBigquery(rows, undefined, "model.s.m", {}, undefined, { target }).cost + + test("the figures are of the current target's runs; other targets are listed in the metadata and a note", () => { + const rows = [run("p1", 0, TIB, "prod"), run("p2", 1, 3 * TIB, "prod"), ...[2, 3, 4].map((i) => run(`d${i}`, i, TIB / 100, "dev")), run("u", 5, 7 * TIB, "")] + const cost = price(rows, "prod") + expect(cost.runs).toBe(2) + expect(cost.highest).toBeCloseTo(18.75, 10) + expect(cost.target).toBe("prod") + expect(cost.otherTargets).toEqual([ + { target: "dev", runs: 3, typical: expect.closeTo(0.0625, 10), attribution: "bytes_billed", rate: DEMAND }, + { target: "unknown target", runs: 1, typical: expect.closeTo(43.75, 10), attribution: "bytes_billed", rate: DEMAND }, + ]) + expect(cost.notes.join(" ")).toContain("Runs of other targets are not in these figures: dev: 3 runs") + expect(costText(cost).split("\n")[0]).toContain("on target prod") + // With no current target named (an older caller), every run counts. + expect(price(rows).runs).toBe(6) + expect(price(rows).otherTargets).toBeUndefined() + }) + + test("when the current target has no runs but others do, nothing is the headline cost", () => { + const cost = price([run("d1", 0, TIB, "dev"), run("d2", 1, TIB, "dev")], "prod") + expect(cost.basis).toBe("none") + expect(cost.lastRun).toBeUndefined() + expect(cost.unknownReason).toContain("No run of model.s.m on the current target (prod)") + expect(cost.unknownReason).toContain("dev: 2 runs, typical $6.25") + expect(cost.otherTargets).toEqual([{ target: "dev", runs: 2, typical: 6.25, attribution: "bytes_billed", rate: DEMAND }]) + // Runs that name no target are not the current target's either. + expect(price([run("u", 0, TIB, "")], "prod").otherTargets).toEqual([{ target: "unknown target", runs: 1, typical: 6.25, attribution: "bytes_billed", rate: DEMAND }]) + }) + + test("the history reads the target name from the query comment, and the target's own name is read", () => { + expect(bigqueryHistorySql({ project: "p", needle: "n", asOfMs: ASOF })).toContain(`regexp_extract(query, r'"target_name": "([^"]*)"') as target_name`) + expect(TARGET_JINJA).toContain('"name": target.get("name")') + }) + + test("a history from JOBS_BY_USER says first that only the caller's jobs were read", () => { + const text = costText({ basis: "history", currency: "USD", runs: 1, windowDays: 30, lastRun: 1, typical: 1, highest: 1, rate: null, notes: [], scope: "user" }) + expect(text.split("\n")[0]).toBe("Only your own jobs were read (no bigquery.jobs.listAll): service-account and other users' runs are missing.") + expect(costText({ basis: "history", currency: "USD", runs: 1, windowDays: 30, lastRun: 1, typical: 1, highest: 1, rate: null, notes: [], scope: "project" })).not.toContain("Only your own") + }) + + test("reservation runs are attributed slot time: named in the first line and in the metadata, with the Standard rate in the note", () => { + const slots = price([bq("a", 0, null, "res", 3_600_000)]) + expect(slots.attribution).toBe("slot_time") + expect(costText(slots).split("\n")[0]).toContain("reservation runs are attributed slot time, not the bill") + expect(slots.notes.join(" ")).toContain("billed in steps of 50, by default with a one-minute minimum (reservations with fluid scaling have none), and baseline slots are always charged") + expect(slots.notes.join(" ")).toContain("Standard is 0.04") + expect(price([bq("a", 0, TIB)]).attribution).toBe("bytes_billed") + expect(costText(price([bq("a", 0, TIB)])).split("\n")[0]).not.toContain("attributed") + const mixed = price([bq("a", 0, TIB), bq("b", 50, null, "res", 3_600_000)]) + expect(mixed.attribution).toBe("mixed") + expect(costText(mixed).split("\n")[0]).toContain("attributed slot time") + }) + + test("a run whose only job is a BigQuery ML statement exists and is unknown with its cause, not a run that was never found", () => { + const { cost } = priceBigquery([bq("h", 0, TIB, null, 0, "CREATE_MODEL", { dbt_invocation_id: "i1" })], undefined, "model.s.m", {}) + expect(cost.basis).toBe("none") + expect(cost.unknownReason).toContain("a BigQuery ML job (CREATE MODEL) ran on demand") + expect(cost.unknownReason).not.toContain("only read data") + // Without a label too. + expect(priceBigquery([bq("h", 0, TIB, null, 0, "CREATE_MODEL")], undefined, "model.s.m", {}).cost.unknownReason).toContain("BigQuery ML") + }) + + test("a script whose start does not parse is unknown with its own cause, and a manifest language is read", () => { + const script = { ...bq("s", 0, null, null, 0, "SCRIPT"), creation_time: "not a time" } + const { cost } = priceBigquery([script, bq("m", 500, TIB)], [{ job_id: "k", parent_job_id: "s", creation_time: "1970-01-01T00:00:10Z", statement_type: "MERGE", total_bytes_billed: "1", total_slot_ms: "0", reservation_id: null, cache_hit: "False" }], "model.s.m", {}) + expect(cost.runs).toBe(1) + expect(cost.notes.join(" ")).toContain("a script's start time could not be read") + expect(resolveModel({ "model.s.py": { resource_type: "model", name: "py", language: "python" } }, "py")).toEqual({ uniqueId: "model.s.py", materialized: undefined, language: "python" }) + }) + + test("the access hint names both permission pairs", () => { + const hint = accessProblem("Access Denied: permission")! + expect(hint).toContain("bigquery.jobs.create and bigquery.jobs.listAll") + expect(hint).toContain("bigquery.jobs.create and bigquery.jobs.list for its own jobs") + }) + + test("a dry run's minimum bill is 10 MiB", () => { + expect(MIN_BILLED_BYTES).toBe(10 * 1024 * 1024) + }) +}) + +describe("checklist review: BigQuery ML, window edge, labelled pairing, target split, scope", () => { + const C4 = 20_000 * MIN + const at = (min: number) => new Date(C4 + min * MIN).toISOString() + const j = (id: string, startMin: number, durMin: number, billed: number | null, type: string, extra: Row = {}): Row => ({ + ...bq(id, 0, billed, null, 0, type, extra), + creation_time: at(startMin), + end_time: at(startMin + durMin), + }) + const inv = (row: Row, id: string): Row => ({ ...row, dbt_invocation_id: id }) + + test("an on-demand BigQuery ML job is unknown (its price is not the query rate), so its run is left out; on a reservation slot time applies", () => { + const hook = inv(j("h", 1, 1, TIB, "CREATE_MODEL"), "i1") + const build = inv(j("m", 0, 1, TIB, "MERGE"), "i1") + const { cost } = priceBigquery([build, hook], undefined, "model.s.m", {}) + expect(cost.basis).toBe("none") + expect(cost.unknownReason).toContain("a BigQuery ML job (CREATE MODEL) ran on demand") + // A script whose child is a CREATE MODEL is unknown too. + const kid: Row = { job_id: "k", parent_job_id: "s", creation_time: at(0.1), statement_type: "CREATE_MODEL", total_bytes_billed: String(TIB), total_slot_ms: "0", reservation_id: null, cache_hit: "False" } + expect(priceBigquery([j("s", 0, 1, null, "SCRIPT")], [kid], "model.s.m", {}).cost.basis).toBe("none") + // Another run still prices; the ML run is counted as left out. + const both = priceBigquery([j("a", 0, 1, TIB, "MERGE"), inv(j("b", 100, 1, TIB, "CREATE_MODEL"), "i9"), inv(j("c", 101, 1, TIB, "MERGE"), "i9")], undefined, "model.s.m", {}).cost + expect(both.runs).toBe(1) + expect(both.notes.join(" ")).toContain("a BigQuery ML job") + // On a reservation, slot time is the price. + const reserved = priceBigquery([{ ...build, dbt_invocation_id: "i1" }, { ...hook, reservation_id: "res", total_slot_ms: "3600000" }], undefined, "model.s.m", {}).cost + expect(reserved.basis).toBe("history") + }) + + test("the time fallback of a full or unknown boundary read is for unlabelled runs: a labelled run is complete when every job of its invocation was read", () => { + const full = { cutoff: C4, stmts: [], full: true } + const price = (row: Row) => priceBigquery([row], undefined, "model.s.m", {}, full).cost + expect(price(j("m", 60, 1, TIB, "MERGE")).basis).toBe("none") + expect(price(inv(j("m", 60, 1, TIB, "MERGE"), "i1")).runs).toBe(1) + expect(priceBigquery([j("m", 60, 1, TIB, "MERGE")], undefined, "model.s.m", {}, { cutoff: C4 }).cost.basis).toBe("none") + expect(priceBigquery([inv(j("m", 60, 1, TIB, "MERGE"), "i1")], undefined, "model.s.m", {}, { cutoff: C4 }).cost.runs).toBe(1) + }) + + test("a boundary or live job of another target never drops or holds a current-target run; an unnamed target meets only unnamed runs", () => { + const tg = (row: Row, target: string): Row => ({ ...row, target_name: target }) + const run = [tg(j("m", 5, 1, TIB, "MERGE"), "prod")] + const price = (boundary: Parameters[4]) => priceBigquery(run, undefined, "model.s.m", {}, boundary, { target: "prod" }).cost + const stmt = (target?: string) => ({ user: "a@x.com", start: C4 - 3 * MIN, end: C4 + 4.5 * MIN, ...(target !== undefined && { target }) }) + expect(price({ cutoff: C4, stmts: [stmt("prod")] }).basis).toBe("none") + expect(price({ cutoff: C4, stmts: [stmt("dev")] }).runs).toBe(1) + expect(price({ cutoff: C4, stmts: [stmt()] }).runs).toBe(1) + expect(price({ cutoff: C4, stmts: [], live: [{ user: "a@x.com", start: C4 - 3 * MIN, target: "dev" }] }).runs).toBe(1) + expect(price({ cutoff: C4, stmts: [], live: [{ user: "a@x.com", start: C4 - 3 * MIN, target: "prod" }] }).notes).toContain("A run still in progress was left out.") + // The users seen live when the read was full leave out their runs of the same target only. + const full = (target: string) => price({ cutoff: C4, stmts: [], full: true, liveFullUsers: ["a@x.com"], live: [{ user: "a@x.com", start: C4 + 1000 * MIN, target }] }) + expect(full("dev").notes.join(" ")).not.toContain("in progress") + expect(full("prod").notes).toContain("A run still in progress was left out.") + // A build of another target that could not be priced is not called a read-only job. + const unpriced = priceBigquery([tg(j("d", 0, 1, null, "MERGE"), "dev")], undefined, "model.s.m", {}, undefined, { target: "prod" }).cost + expect(unpriced.unknownReason).toContain("the builds found are of other targets and could not be priced") + expect(unpriced.unknownReason).not.toContain("only read data") + }) + + test("a later temporary CTAS with no build after it is still waiting for it, though an earlier build of the invocation exists", () => { + // CTAS 0-1, MERGE 2-3, then a second CTAS 10-11 whose MERGE has not run. + const rows = [inv(j("t1", 0, 1, TIB, "CREATE_TABLE_AS_SELECT", { destination_table_id: "o__dbt_tmp" }), "i1"), inv(j("m1", 2, 1, TIB, "MERGE"), "i1"), inv(j("t2", 10, 1, TIB, "CREATE_TABLE_AS_SELECT", { destination_table_id: "o__dbt_tmp" }), "i1")] + const asOf = (min: number) => priceBigquery(rows, undefined, "model.s.m", {}, undefined, { asOfMs: C4 + min * MIN }).cost + expect(asOf(13).notes).toContain("A run still in progress was left out.") + expect(asOf(13).basis).toBe("none") + // Ten minutes after the second CTAS ended with no MERGE, the invocation is whole. + expect(asOf(22).runs).toBe(1) + expect(asOf(22).lastRun).toBeCloseTo(18.75, 10) + // A build before the CTAS does not pair with it (pairing goes forward in time): the build alone holds nothing open. + const early = [inv(j("m0", 0, 1, TIB, "MERGE"), "i2"), inv(j("t", 5, 1, TIB, "CREATE_TABLE_AS_SELECT", { destination_table_id: "o__dbt_tmp" }), "i2")] + expect(priceBigquery(early, undefined, "model.s.m", {}, undefined, { asOfMs: C4 + 8 * MIN }).cost.basis).toBe("none") + }) + + test("jobs are split by target before they are grouped: adjacent prod and dev jobs are two runs, in either order", () => { + const tgt = (row: Row, target: string): Row => ({ ...row, target_name: target }) + const prod = tgt(j("p", 0, 1, TIB, "MERGE"), "prod") + const dev = tgt(j("d", 1, 1, 10 * TIB, "MERGE"), "dev") + for (const rows of [[prod, dev], [dev, prod]]) { + const cost = priceBigquery(rows, undefined, "model.s.m", {}, undefined, { target: "prod" }).cost + expect(cost.runs).toBe(1) + expect(cost.lastRun).toBe(6.25) + expect(cost.otherTargets).toEqual([{ target: "dev", runs: 1, typical: 62.5, attribution: "bytes_billed", rate: DEMAND }]) + } + // A job naming no target is not absorbed by a named one. + const unnamed = priceBigquery([prod, j("u", 1, 1, 10 * TIB, "MERGE")], undefined, "model.s.m", {}, undefined, { target: "prod" }).cost + expect(unnamed.lastRun).toBe(6.25) + expect(unnamed.otherTargets).toEqual([{ target: "unknown target", runs: 1, typical: 62.5, attribution: "bytes_billed", rate: DEMAND }]) + }) + + test("each other target says how its figure was priced and at what rate, in the metadata and the note", () => { + const tg = (row: Row, target: string): Row => ({ ...row, target_name: target }) + const rows = [ + tg(j("p", 0, 1, TIB, "MERGE"), "prod"), + tg(j("d", 100, 1, null, "MERGE", {}), "dev"), + { ...tg(j("c", 200, 1, TIB, "MERGE"), "ci"), reservation_id: "res", total_slot_ms: "7200000" }, + tg(j("m1", 300, 1, TIB, "MERGE"), "mix"), + { ...tg(j("m2", 400, 1, null, "MERGE"), "mix"), reservation_id: "res", total_slot_ms: "3600000" }, + ] + rows[1] = { ...rows[1], total_bytes_billed: String(2 * TIB) } + const cost = priceBigquery(rows, undefined, "model.s.m", { bigqueryUsdPerTib: 5 }, undefined, { target: "prod" }).cost + const by = Object.fromEntries((cost.otherTargets ?? []).map((o) => [o.target, o])) + expect(by.dev).toMatchObject({ attribution: "bytes_billed", rate: { value: 5, unit: "USD/TiB", source: "config" } }) + expect(by.ci).toMatchObject({ attribution: "slot_time", typical: 0.12, rate: { value: 0.06, unit: "USD/slot-hour", source: "default" } }) + expect(by.mix).toMatchObject({ attribution: "mixed", rate: { unit: "USD/TiB" }, slotRate: { unit: "USD/slot-hour" } }) + const note = cost.notes.join(" ") + expect(note).toContain("dev: 1 run, typical $10.00 (bytes billed at 5 USD/TiB, your config)") + expect(note).toContain("ci: 1 run, typical $0.12 (attributed slot time at 0.06 USD/slot-hour, default)") + expect(note).toContain("mix: 2 runs") + expect(note).toContain("bytes billed at 5 USD/TiB, your config and attributed slot time at 0.06 USD/slot-hour, default") + }) + + test("on a full read, a user seen live leaves out only that user's unlabelled runs: a labelled run is judged by its own invocation", () => { + const A = "a@x.com" + const labelled = (id: string) => inv(j("m", 60, 1, TIB, "MERGE"), id) + // The full read saw A's job iX still running, started long after the runs below. + const price = (rows: Row[], liveInv?: string) => + priceBigquery(rows, undefined, "model.s.m", {}, { cutoff: C4, stmts: [], full: true, liveFullUsers: [A], live: [{ user: A, start: C4 + 2000 * MIN, ...(liveInv && { inv: liveInv }) }] }).cost + // Past the fallback's span, so only the live rules apply. + const at = (m: number) => ({ ...j("x", m, 1, TIB, "MERGE") }) + expect(price([{ ...at(110 * 60), dbt_invocation_id: "i1" }], "iX").runs).toBe(1) + expect(price([{ ...at(110 * 60), dbt_invocation_id: "i1" }], "i1").notes).toContain("A run still in progress was left out.") + // An unlabelled run by the same user is left out by the user rule. + expect(price([at(110 * 60)]).notes).toContain("A run still in progress was left out.") + // A job with no label (what the full read saw) does not leave out a labelled run either. + expect(price([labelled("i1")]).runs).toBe(1) + }) + + test("a continuous query is not a dbt run: all five reads leave it out", () => { + const needle = needleFor("model.shop.orders") + const w = boundaryWindow(C4) + for (const sql of [ + bigqueryHistorySql({ project: "p", needle, asOfMs: ASOF }), + bigqueryBoundarySql({ project: "p", needle, window: w }), + bigqueryInvocationSql({ project: "p", needle, window: w, invocations: ["i1"] }), + bigqueryCapacitySql({ project: "p", asOfMs: ASOF }), + bigqueryChildrenSql({ project: "p", parents: ["a"], sinceMs: 1 }), + ]) + expect(sql).toContain("and coalesce(continuous, false) = false") + }) + + test("a full read of the invocations' own jobs leaves out every labelled run, whatever the unlabelled boundary read found", () => { + const labelled = [inv(j("m", 60, 1, TIB, "MERGE"), "i1")] + const unlabelled = [j("u", 20 * 60, 1, TIB, "MERGE")] + const price = (rows: Row[], extra: object) => priceBigquery(rows, undefined, "model.s.m", {}, { cutoff: C4, stmts: [], ...extra }).cost + const full = price(labelled, { invocationsFull: true }) + expect(full.basis).toBe("none") + expect(full.notes.join(" ")).toContain("may have started before the period read") + expect(price(labelled, {}).runs).toBe(1) + // An unlabelled run is not part of that read. + expect(price(unlabelled, { invocationsFull: true }).runs).toBe(1) + }) + + test("only the caller's jobs and reservation attribution share the first line", () => { + const base = { basis: "history" as const, currency: "USD" as const, runs: 1, windowDays: 30 as const, lastRun: 1, typical: 1, highest: 1, rate: null, notes: [], scope: "user" as const } + const first = costText({ ...base, attribution: "slot_time" }).split("\n")[0] + expect(first).toBe("Only your own jobs were read (no bigquery.jobs.listAll): service-account and other users' runs are missing; reservation runs are attributed slot time, not the bill.") + expect(costText({ ...base, attribution: "slot_time" })).not.toContain("days (reservation runs") + }) + + test("every message that says no run was found names the location read", () => { + const where = locationNote(undefined) + const run = (rows: Row[], opts: Record = {}, boundary?: Parameters[4]) => + priceBigquery(rows, undefined, "model.s.m", {}, boundary, { location: where, ...opts }).cost.unknownReason! + const tg = (row: Row, target: string): Row => ({ ...row, target_name: target }) + expect(run([tg(j("d", 0, 1, TIB, "MERGE"), "dev")], { target: "prod" })).toContain("region-us was read") + expect(run([{ ...j("p", 0, 1, TIB, "MERGE"), state: "RUNNING" }])).toContain("region-us was read") + expect(run([j("m", 5, 1, TIB, "MERGE")], {}, { cutoff: C4 })).toContain("region-us was read") + expect(run([j("m", 5, 1, null, "MERGE")])).toContain("region-us was read") + }) +}) + +describe("review follow-ups: text and causes", () => { + test("an amount shows enough digits that a small one is not zero", () => { + expect(formatMoney(6.562559604645912)).toBe("$6.56") + expect(formatMoney(0.000059604644775)).toBe("$0.000060") + expect(formatMoney(0)).toBe("$0.00") + }) + + test("the SELECT's price is in the text beside the history, since a note refers to it", () => { + const text = costText({ + basis: "history", + currency: "USD", + lastRun: 1, + typical: 1, + highest: 1, + runs: 1, + windowDays: 30, + rate: null, + notes: [], + selectOnly: { estimate: 2 }, + }, "1.0 TiB") + expect(text.split("\n")[0]).toContain("Cost from 1 run") + expect(text).toContain("estimates the SELECT at 1.0 TiB, about $2.00 on-demand") + }) + + test("BigQuery: children cut off at their limit are named as the cause, not 'not found'", () => { + const script = bq("s", 0, null, null, 0, "SCRIPT") + const kid = (i: number): Row => ({ + job_id: `k${i}`, + // Every child belongs to the matched script and starts during it: a response the children query can return. + parent_job_id: "s", + creation_time: new Date(MIN / 2).toISOString(), + statement_type: "MERGE", + total_bytes_billed: "1", + total_slot_ms: "0", + reservation_id: null, + cache_hit: "False", + }) + const { cost } = priceBigquery([script], Array.from({ length: BQ_CHILD_LIMIT }, (_, i) => kid(i)), "model.s.m", {}) + expect(cost.unknownReason).toContain("cut off at the children query's limit") + expect(cost.unknownReason).not.toContain("were not found") + const none = priceBigquery([script], [], "model.s.m", {}).cost + expect(none.unknownReason).toContain("child jobs were not found") + }) + + test("BigQuery: a reservation job with no slot time is unknown, never zero slot-hours", () => { + const { cost } = priceBigquery([bq("a", 0, 0, "res", 0, "MERGE", { total_slot_ms: null })], undefined, "model.s.m", {}) + expect(cost.basis).toBe("none") + expect(cost.unknownReason).toContain("no slot time for a job that ran in a reservation") + // A reported zero is still a zero. + expect(priceBigquery([bq("b", 0, 0, "res", 0)], undefined, "model.s.m", {}).cost).toMatchObject({ basis: "history", lastRun: 0 }) + }) + + test("BigQuery: a job with no bytes billed is named as the cause", () => { + const { cost } = priceBigquery([bq("a", 0, null)], undefined, "model.s.m", {}) + expect(cost.unknownReason).toContain("hides them for tables under a row access policy") + }) +}) + +describe("review follow-ups: manifest and cancellation", () => { + test("the manifest path is the adapter's own, else its project's target, else the session's project's target", () => { + expect(manifestPathFor({ getManifestPath: () => "/x/m.json", getProjectRoot: () => "/p" }, "/q")).toBe("/x/m.json") + expect(manifestPathFor({ getProjectRoot: () => "/p" }, "/q")).toBe("/p/target/manifest.json") + expect(manifestPathFor({}, "/q")).toBe("/q/target/manifest.json") + expect(manifestPathFor({}, undefined)).toBeUndefined() + expect(manifestPathFor({ getManifestPath: () => "" }, "/q")).toBe("/q/target/manifest.json") + }) + + test("a manifest that cannot be read is an error that names the file", async () => { + await using tmp = await tmpdir() + const file = path.join(tmp.path, "manifest.json") + await writeFile(file, "{ not json") + expect(modelFromManifest(file, "orders")).toEqual({ error: expect.stringContaining(`the manifest at ${file}`) }) + expect(modelFromManifest(path.join(tmp.path, "missing.json"), "orders")).toEqual({ error: expect.stringContaining("no manifest at") }) + }) + + test("dbt's bare 'Encountered an error:' wrapper is not shown as the cause", () => { + const wrapped = unreadable("[ERROR]: Encountered an error:\nNOT_FOUND: Dataset p:d was not found in location EU") + expect(wrapped.unknownReason).toContain("(NOT_FOUND: Dataset p:d was not found") + expect(wrapped.unknownReason).not.toContain("Encountered an error") + // A message that is only the wrapper leaves no empty parentheses. + const bare = unreadable("[ERROR]: Encountered an error:") + expect(bare.unknownReason).not.toContain("()") + expect(bare.unknownReason).not.toContain("Encountered") + // An ordinary message is shown as it was. + expect(unreadable("boom\nsecond line").unknownReason).toContain("(boom)") + }) + + test("a call cancelled before the history starts stops, even when no query would be sent", async () => { + const controller = new AbortController() + controller.abort(new Error("cancelled")) + const adapter = { unsafeCompileQuery: async () => "{}" } + const input = { adapter, signal: controller.signal, cfg: {} } + // SQL input has no history to read, and an unresolved model none either: both would otherwise return normally. + expect(await loadHistory({ ...input, model: undefined }).then(() => "answered", (e: unknown) => e)).toMatchObject({ message: "cancelled" }) + expect(await loadHistory({ ...input, model: "orders", manifestPath: undefined }).then(() => "answered", (e: unknown) => e)).toMatchObject({ message: "cancelled" }) + }) +}) diff --git a/packages/opencode/test/skill/release-v0.12.12-adversarial.test.ts b/packages/opencode/test/skill/release-v0.12.12-adversarial.test.ts index 8374d6566d..00e34d36f2 100644 --- a/packages/opencode/test/skill/release-v0.12.12-adversarial.test.ts +++ b/packages/opencode/test/skill/release-v0.12.12-adversarial.test.ts @@ -6,8 +6,6 @@ * * This file adds the boundary classes those suites do not reach, and covers the release review fixes: * - * - `dbt_cost_estimate`'s script check against statement smuggling on Snowflake and Databricks, its Jinja - * literal against breaking out of the string, and its plan parsers against hostile JSON. * - The classifier's hard-deny list for the DROP forms #1644 added, and that Jinja keeps a read from * being read as one. * - `readRunResults` against non-files, non-JSON, prototype keys, an oversized file (the review's size @@ -23,14 +21,6 @@ import path from "path" import { Effect } from "effect" import type { Tool } from "@/tool/tool" import { SessionID, MessageID } from "@/session/schema" -import { - explainJinja, - formatBytes, - mayBeScript, - parseDatabricksExplainCost, - parseSnowflakeExplain, - readsFiles, -} from "@/altimate/tools/dbt-cost-estimate" import { classifyAndCheck, mentionsHardDenyAnywhere } from "@/altimate/tools/sql-classify" import { readRunResults, resolveDbtTargetPath } from "@/altimate/validators/validator-utils" import { dbtAdapterFor } from "@/altimate/tools/dbt-adapter-access" @@ -56,84 +46,6 @@ const ctx = (extra: Partial = {}): Tool.Context => ({ ...extra, }) -describe("v0.12.12: dbt_cost_estimate never sends a second statement", () => { - const smuggled = [ - "select 1; drop table t", - "select 1;\ndrop table t", - "select 1 /* ; */; delete from t", - "select $$; drop table t$$", - "select 1 // ;\n; drop table t", - "!set variable_substitution=true\nselect 1", - "select 1 /* unclosed", - "select 'unclosed", - "execute immediate 'drop table t'", - "select 1;select 2", - ] - for (const sql of smuggled) - test(`Snowflake counts as a script: ${JSON.stringify(sql)}`, () => { - expect(mayBeScript(sql, "snowflake")).toBe(true) - }) - - for (const sql of ["select 1; drop table t", "select 1 /* unclosed", "select `a;b`; drop table t"]) - test(`Databricks counts as a script: ${JSON.stringify(sql)}`, () => { - expect(mayBeScript(sql, "databricks")).toBe(true) - }) - - test("a single statement with quoted semicolons and a trailing one is not a script", () => { - expect(mayBeScript("select ';' as a, \"b;c\" from t -- ; trailing\n;", "snowflake")).toBe(false) - expect(mayBeScript("select `a;b` from t;", "databricks")).toBe(false) - }) - - test("the empty string and whitespace are not scripts", () => { - expect(mayBeScript("", "snowflake")).toBe(false) - expect(mayBeScript(" \n\t ", "databricks")).toBe(false) - }) - - test("the Jinja literal cannot be closed by the SQL it carries", () => { - for (const sql of ["select '}}' as a", "select 'x' ~ '{{ 7*7 }}'", "select '\\' as b", "select 'it''s'", "{% do run_query('drop table t') %}"]) { - const jinja = explainJinja("EXPLAIN USING JSON", sql) - const literal = jinja.match(/run_query\('((?:\\.|[^'\\])*)'\)/) - expect(literal).not.toBeNull() - // Unescaping the literal gives back exactly the statement: nothing leaked outside the quotes. - expect(literal![1].replace(/\\(.)/g, "$1")).toBe(`EXPLAIN USING JSON\n${sql}`) - } - }) - - test("Databricks queries that read files are refused", () => { - for (const sql of ["select * from read_files('s3://b/x')", "SELECT * FROM cloud_files('/p', 'json')", "select * from json.`/tmp/a.json`"]) - expect(readsFiles(sql)).toBe(true) - expect(readsFiles("select read_files_count from t")).toBe(false) - }) -}) - -describe("v0.12.12: plan parsers against hostile JSON", () => { - const junk: unknown[] = [null, undefined, 0, -1, NaN, "", "{}", [], [null], {}, { __proto__: { bytesAssigned: 5 } }, JSON.parse('{"__proto__":{"GlobalStats":{"bytesAssigned":5}}}')] - test("Snowflake: junk gives no estimate and does not throw", () => { - for (const value of junk) expect(parseSnowflakeExplain(value)).toBeUndefined() - }) - test("Snowflake: negative or non-numeric bytes give no estimate", () => { - for (const bytesAssigned of [-1, "12", NaN, Infinity]) - expect(parseSnowflakeExplain(JSON.stringify({ GlobalStats: { bytesAssigned, partitionsAssigned: 1, partitionsTotal: 1 } }))).toBeUndefined() - // The same plan with a real count is read, so the cases above fail on the bytes, not the shape. - expect(parseSnowflakeExplain(JSON.stringify({ GlobalStats: { bytesAssigned: 5, partitionsAssigned: 1, partitionsTotal: 1 } }))).toBeDefined() - }) - test("Databricks: junk gives no estimate and does not throw", () => { - for (const value of junk) expect(() => parseDatabricksExplainCost(value)).not.toThrow() - for (const value of [null, undefined, 0, "", [], {}]) { - const r = parseDatabricksExplainCost(value) - expect(r === undefined || (typeof r === "object" && "noStats" in r)).toBe(true) - } - }) - test("formatBytes at the boundaries", () => { - expect(formatBytes(0)).toBe("0.0 Bytes") - expect(formatBytes(1023)).toBe("1023.0 Bytes") - expect(formatBytes(1024)).not.toContain("Bytes") - // The largest unit holds any size: no "undefined" unit. - expect(formatBytes(Number.MAX_SAFE_INTEGER)).not.toContain("undefined") - expect(formatBytes(1024 ** 8)).not.toContain("undefined") - }) -}) - describe("v0.12.12: SQL classification hardening (#1644)", () => { test("the new DROP forms are hard-denied wherever they appear", () => { for (const sql of ["DROP CATALOG c", "drop namespace n", "DROP EXTERNAL SCHEMA s", "DROP PLUGGABLE DATABASE p", "select 1; DROP CATALOG c"]) {