Repository navigation
feat: dbt_cost_estimate tool for BigQuery dry-run scan estimates #1732
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
b7cfc04
1eb722e
d5e7bc8
d191355
21d0494
d90e334
33e2655
9f19a75
1c23d35
4fa4703
9f4ae46
99e953c
6c2ab6f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import fs from "fs" | ||
| import path from "path" | ||
| import type { Tool } from "../../tool/tool" | ||
| import { projectRoot } from "../native/connections/registry" | ||
|
|
||
| /** Why a tool may not use the dbt adapter. */ | ||
| export type DbtAdapterRefusal = "read_only" | "other_project" | "no_project" | "not_started" | "not_loaded" | ||
|
|
||
| /** The project's dbt adapter, or why this call may not use it (`reason` is a sentence for the user). */ | ||
| export type DbtAdapterAccess = | ||
| | { adapter: any; refusal?: undefined; reason?: undefined } | ||
| | { adapter?: undefined; refusal: DbtAdapterRefusal; reason: string } | ||
|
|
||
| /** Test seams. */ | ||
| export const dbtAdapterAccessInternals = { | ||
| /** How long a call waits for the dbt adapter to start before it gives up; the start goes on for the next call. */ | ||
| adapterStartTimeoutMs: 120_000, | ||
| } | ||
|
|
||
| /** | ||
| * The dbt adapter for a tool call, which every adapter-backed tool goes through. Starting the adapter | ||
| * runs dbt deps and writes target/, and compiling renders Jinja, which can run SQL: a read-only call | ||
| * (no write permission, or plan mode) never starts or uses it. Nor does a session in a dbt project the | ||
| * adapter isn't set up for. The wait for the adapter to start is bounded and follows the call's abort. | ||
| */ | ||
| export async function dbtAdapterFor(ctx: Pick<Tool.Context, "abort" | "agent" | "extra">): Promise<DbtAdapterAccess> { | ||
| const signal = ctx.abort | ||
| if (ctx.extra?.forceReadOnly === true || ctx.agent === "plan") | ||
| return { | ||
| refusal: "read_only", | ||
| reason: "this needs the dbt adapter, which a read-only call doesn't start: it needs write permission (--allow-write on `tool run` or the MCP server, and not plan mode)", | ||
| } | ||
| try { | ||
| const { getDbtAdapter, getDbtProjectRoot } = await import("../native/connections/register") | ||
| // The import yields: a call cancelled meanwhile starts nothing. | ||
| signal.throwIfAborted() | ||
| const project = await sessionProject() | ||
|
hkaltai marked this conversation as resolved.
Resolved
|
||
| signal.throwIfAborted() | ||
| if (project?.other) { | ||
| return { | ||
| refusal: "other_project", | ||
| reason: project.root | ||
| ? `the dbt adapter is set up for ${project.root}, not ${project.other}` | ||
| : `the dbt adapter isn't set up for ${project.other}`, | ||
| } | ||
| } | ||
| let stop = () => {} | ||
| let timer: ReturnType<typeof setTimeout> | undefined | ||
| const waited = new Promise<never>((_, reject) => { | ||
|
hkaltai marked this conversation as resolved.
Resolved
|
||
| stop = () => reject(signal.reason) | ||
| signal.addEventListener("abort", stop, { once: true }) | ||
| const seconds = dbtAdapterAccessInternals.adapterStartTimeoutMs / 1000 | ||
| timer = setTimeout( | ||
| () => reject(new Error(`the dbt adapter didn't start within ${seconds} s`)), | ||
| dbtAdapterAccessInternals.adapterStartTimeoutMs, | ||
| ) | ||
| }) | ||
| const adapter = await Promise.race([getDbtAdapter(), waited]).finally(() => { | ||
| signal.removeEventListener("abort", stop) | ||
| clearTimeout(timer) | ||
| }) | ||
| if (!adapter) { | ||
| // No adapter also when the project exists but the adapter failed to start: say which. | ||
| const root = await getDbtProjectRoot() | ||
| const found = !!root && fs.existsSync(path.join(root, "dbt_project.yml")) | ||
| return found | ||
| ? { refusal: "not_started", reason: "the dbt adapter didn't start" } | ||
| : { refusal: "no_project", reason: "no dbt project here" } | ||
| } | ||
| if (adapter.isInitialized?.() === false) | ||
| return { refusal: "not_loaded", reason: "the dbt adapter didn't load the project" } | ||
| return { adapter } | ||
| } catch (e) { | ||
| if (signal.aborted) throw e | ||
| return { refusal: "not_started", reason: e instanceof Error ? e.message : String(e) } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * The adapter's project root and, when the session's directory is in another dbt project, that one | ||
| * (`other`, both links resolved). Undefined when the session's directory is in no dbt project: the | ||
| * adapter's own discovery (a dbt.json, or a walk up from the working directory) decides then. | ||
| */ | ||
| async function sessionProject(): Promise<{ root?: string; other?: string } | undefined> { | ||
|
hkaltai marked this conversation as resolved.
Resolved
hkaltai marked this conversation as resolved.
Resolved
|
||
| const { findProjectRoot } = await import("../../../../dbt-tools/src/config") | ||
| const found = findProjectRoot(projectRoot()) | ||
| if (!found) return undefined | ||
| const { getDbtProjectRoot } = await import("../native/connections/register") | ||
| const root = await getDbtProjectRoot() | ||
| const real = (p: string) => { | ||
| try { | ||
| return fs.realpathSync(p) | ||
| } catch { | ||
| return path.resolve(p) | ||
| } | ||
| } | ||
| const here = real(found) | ||
| // path.relative ignores case on win32. | ||
| if (!root) return { other: here } | ||
| return path.relative(real(root), here) ? { root: real(root), other: here } : { root } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| import z from "zod" | ||
| import { Tool } from "../../tool/tool" | ||
| import { dbtAdapterFor } from "./dbt-adapter-access" | ||
|
|
||
| /** 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. | ||
| */ | ||
| export function parseBytesProcessed(display: unknown): { bytes: number; maxBytes: number } | undefined { | ||
| if (typeof display === "number") { | ||
| if (!Number.isFinite(display) || display < 0) return undefined | ||
| const bytes = Math.round(display) | ||
| return { bytes, maxBytes: bytes } | ||
| } | ||
| if (typeof display !== "string") return undefined | ||
| const match = /^\s*(\d+(?:\.\d+)?)\s*(Bytes|KiB|MiB|GiB|TiB|PiB)\s*$/i.exec(display) | ||
| if (!match) return undefined | ||
| const unit = UNITS.findIndex((u) => u.toLowerCase() === match[2].toLowerCase()) | ||
| const scale = 1024 ** unit | ||
| const bytes = Math.round(Number(match[1]) * scale) | ||
| if (unit === 0) return { bytes, maxBytes: bytes } | ||
| // Exact in integers: the shown figure is rounded to its last digit, so the true count is at most half | ||
| // of that digit above it. A float product is off by whole bytes past a few TiB. | ||
| const [whole, fraction = ""] = match[1].split(".") | ||
| const digits = BigInt(whole + fraction) | ||
| let upper = ((digits * 2n + 1n) * 1024n ** BigInt(unit) + 2n * 10n ** BigInt(fraction.length) - 1n) / (2n * 10n ** BigInt(fraction.length)) | ||
| // Python divides in floats, so a count within a float's last place of a tie is shown rounded down. | ||
| upper += upper >> 50n | ||
| let maxBytes = Number(upper) | ||
| if (BigInt(Math.trunc(maxBytes)) < upper) maxBytes *= 1 + Number.EPSILON | ||
| return { bytes, maxBytes: Math.max(bytes, maxBytes) } | ||
| } | ||
|
|
||
| /** Starts `start` and waits for it, but gives up as soon as the call is cancelled; a cancelled call starts nothing. */ | ||
| export function untilAbort<T>(start: () => Promise<T>, signal: AbortSignal): Promise<T> { | ||
| if (signal.aborted) return Promise.reject(signal.reason) | ||
| return new Promise<T>((resolve, reject) => { | ||
| const stop = () => reject(signal.reason) | ||
| signal.addEventListener("abort", stop, { once: true }) | ||
| Promise.resolve() | ||
| .then(() => (signal.aborted ? Promise.reject(signal.reason) : start())) | ||
| .then(resolve, reject) | ||
| .finally(() => signal.removeEventListener("abort", stop)) | ||
| }) | ||
| } | ||
|
|
||
| function failure(title: string, message: string, extra: Record<string, unknown> = {}) { | ||
| return { title: `dbt_cost_estimate: ${title}`, metadata: { success: false, error: message, ...extra }, output: message } | ||
| } | ||
|
|
||
| export const DbtCostEstimateTool = Tool.define("dbt_cost_estimate", { | ||
| description: | ||
| "Estimate the bytes a dbt model or a SQL query would scan, from a warehouse dry run. Only BigQuery has a dry run: any other warehouse answers `supported: false` and nothing is compiled. Starts the dbt adapter, so it needs write permission (`--allow-write` on `tool run`). Pass `model` (a model name, compiled as dbt would) or `sql` (may use Jinja).", | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION: the tool description still points only at
|
||
| 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"), | ||
| }), | ||
| async execute(args, ctx) { | ||
| if (!args.model && !args.sql) return failure("nothing to estimate", "Pass a model name or SQL.") | ||
|
hkaltai marked this conversation as resolved.
Resolved
|
||
| if (args.model && args.sql) return failure("ambiguous input", "Pass a model name or SQL, not both.") | ||
| const access = await dbtAdapterFor(ctx) | ||
| 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, so nothing is compiled there. | ||
| 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: dry runs 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 }) | ||
| } | ||
| let display: unknown | ||
| try { | ||
| const result = await untilAbort(() => adapter.validateSQLDryRun(compiled), 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) | ||
| return { | ||
| title: `dbt_cost_estimate: ${shown}`, | ||
| metadata: { success: true, supported: true, adapter: type, ...parsed, display: shown, ...(name && { model: name }) }, | ||
| output: `${name ? `${name} ` : "The query "}would process ${shown} (at most ${parsed.maxBytes} bytes).`, | ||
| } | ||
| }, | ||
| }) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| import z from "zod" | ||
| import { Tool } from "../../tool/tool" | ||
|
|
||
| export const DbtCteProfileTool = Tool.define("dbt_cte_profile", { | ||
| description: "List a dbt model's CTEs, or time one CTE with a row-count query.", | ||
| parameters: z.object({ | ||
| model: z.string().describe("Model name"), | ||
| cte: z.string().optional().describe("CTE to time; without it, the CTE list is returned"), | ||
| }), | ||
| async execute() { | ||
| return { | ||
| title: "dbt_cte_profile: not implemented", | ||
| metadata: { success: false, error: "not implemented" }, | ||
| output: "dbt_cte_profile is not implemented in this build of altimate-code yet.", | ||
| } | ||
| }, | ||
| }) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import z from "zod" | ||
| import { Tool } from "../../tool/tool" | ||
|
|
||
| export const DbtDeferStateTool = Tool.define("dbt_defer_state", { | ||
| description: "dbt Power User's defer-to-production setting for a dbt project, and the profile's default target.", | ||
| parameters: z.object({ | ||
| project_dir: z.string().describe("dbt project folder"), | ||
| }), | ||
| async execute() { | ||
| return { | ||
| title: "dbt_defer_state: not implemented", | ||
| metadata: { success: false, error: "not implemented" }, | ||
| output: "dbt_defer_state is not implemented in this build of altimate-code yet.", | ||
| } | ||
| }, | ||
| }) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import z from "zod" | ||
| import { Tool } from "../../tool/tool" | ||
|
|
||
| export const DbtDocsCoverageTool = Tool.define("dbt_docs_coverage", { | ||
| description: | ||
| "Documentation coverage of a dbt model: which output columns have a description, and whether the model has one.", | ||
| parameters: z.object({ | ||
| model: z.string().describe("Model name"), | ||
| manifest_path: z | ||
| .string() | ||
| .optional() | ||
| .describe("manifest.json to read (default: the dbt project's target/manifest.json)"), | ||
| }), | ||
| async execute() { | ||
| return { | ||
| title: "dbt_docs_coverage: not implemented", | ||
| metadata: { success: false, error: "not implemented" }, | ||
| output: "dbt_docs_coverage is not implemented in this build of altimate-code yet.", | ||
| } | ||
| }, | ||
| }) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import z from "zod" | ||
| import { Tool } from "../../tool/tool" | ||
|
|
||
| export const DbtHealthTool = Tool.define("dbt_health", { | ||
| description: "DataPilot project health insights for the dbt project.", | ||
| parameters: z.object({ | ||
| config_path: z.string().optional().describe("DataPilot config file to use"), | ||
| }), | ||
| async execute() { | ||
| return { | ||
| title: "dbt_health: not implemented", | ||
| metadata: { success: false, error: "not implemented" }, | ||
| output: "dbt_health is not implemented in this build of altimate-code yet.", | ||
| } | ||
| }, | ||
| }) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import z from "zod" | ||
| import { Tool } from "../../tool/tool" | ||
|
|
||
| export const DbtMapRelationsTool = Tool.define("dbt_map_relations", { | ||
| description: "Map each table a raw SQL query reads to the dbt ref() or source() for it, from the manifest.", | ||
| parameters: z.object({ | ||
| sql: z.string().describe("Raw SQL to map"), | ||
| dialect: z.string().optional().describe("SQL dialect of the query"), | ||
| manifest_path: z | ||
| .string() | ||
| .optional() | ||
| .describe("manifest.json to match against (default: the dbt project's target/manifest.json)"), | ||
| }), | ||
| async execute() { | ||
| return { | ||
| title: "dbt_map_relations: not implemented", | ||
| metadata: { success: false, error: "not implemented" }, | ||
| output: "dbt_map_relations is not implemented in this build of altimate-code yet.", | ||
| } | ||
| }, | ||
| }) |
Uh oh!
There was an error while loading. Please reload this page.