diff --git a/packages/opencode/src/altimate/api/client.ts b/packages/opencode/src/altimate/api/client.ts index 7a03aeb906..cb53c0ec7b 100644 --- a/packages/opencode/src/altimate/api/client.ts +++ b/packages/opencode/src/altimate/api/client.ts @@ -347,6 +347,26 @@ export namespace AltimateApi { // altimate_change end } + /** + * Calls an Altimate API endpoint with the stored credentials (Bearer key and x-tenant headers) and + * returns the parsed JSON body. Endpoint functions in other files go through this. Fails with a + * message naming the credentials file when none are stored or they can't be read. + */ + export async function apiRequest(method: string, endpoint: string, body?: unknown): Promise { + let creds: AltimateCredentials + try { + creds = await getCredentials() + } catch (e) { + const p = credentialsPath() + if (!(await Filesystem.exists(p))) + throw new Error( + `No Altimate credentials are stored: sign in to Altimate in altimate-code first (they are saved to ${p}).`, + ) + throw new Error(`The Altimate credentials in ${p} can't be used: ${e instanceof Error ? e.message : String(e)}`) + } + return request(creds, method, endpoint, body) + } + export async function listDatamates(creds?: AltimateCredentials) { creds ??= await getCredentials() const data = await request(creds, "GET", "/datamates/") diff --git a/packages/opencode/src/altimate/tool-cli/allow-list.ts b/packages/opencode/src/altimate/tool-cli/allow-list.ts index 33b452d75c..0bb4f18473 100644 --- a/packages/opencode/src/altimate/tool-cli/allow-list.ts +++ b/packages/opencode/src/altimate/tool-cli/allow-list.ts @@ -35,10 +35,19 @@ import { AltimateCoreTestgenTool } from "../tools/altimate-core-testgen" import { AltimateCoreTrackLineageTool } from "../tools/altimate-core-track-lineage" import { AltimateCoreValidateTool } from "../tools/altimate-core-validate" import { DataDiffTool } from "../tools/data-diff" +import { DbtCostEstimateTool } from "../tools/dbt-cost-estimate" +import { DbtCteProfileTool } from "../tools/dbt-cte-profile" +import { DbtDeferStateTool } from "../tools/dbt-defer-state" +import { DbtDocsCoverageTool } from "../tools/dbt-docs-coverage" +import { DbtHealthTool } from "../tools/dbt-health" import { DbtLineageTool } from "../tools/dbt-lineage" import { DbtManifestTool } from "../tools/dbt-manifest" +import { DbtMapRelationsTool } from "../tools/dbt-map-relations" import { DbtProfilesTool } from "../tools/dbt-profiles" +import { DbtRunResultsTool } from "../tools/dbt-run-results" +import { DbtSqlGraphTool } from "../tools/dbt-sql-graph" import { DbtUnitTestGenTool } from "../tools/dbt-unit-test-gen" +import { DocsShareCommentsTool } from "../tools/docs-share-comments" import { FinopsAnalyzeCreditsTool } from "../tools/finops-analyze-credits" import { FinopsExpensiveQueriesTool } from "../tools/finops-expensive-queries" import { FinopsQueryHistoryTool } from "../tools/finops-query-history" @@ -106,10 +115,19 @@ export const EXPOSED: Record = { altimate_core_track_lineage: AltimateCoreTrackLineageTool, altimate_core_validate: AltimateCoreValidateTool, data_diff: DataDiffTool, + dbt_cost_estimate: DbtCostEstimateTool, + dbt_cte_profile: DbtCteProfileTool, + dbt_defer_state: DbtDeferStateTool, + dbt_docs_coverage: DbtDocsCoverageTool, + dbt_health: DbtHealthTool, dbt_lineage: DbtLineageTool, dbt_manifest: DbtManifestTool, + dbt_map_relations: DbtMapRelationsTool, dbt_profiles: DbtProfilesTool, + dbt_run_results: DbtRunResultsTool, + dbt_sql_graph: DbtSqlGraphTool, dbt_unit_test_gen: DbtUnitTestGenTool, + docs_share_comments: DocsShareCommentsTool, finops_analyze_credits: FinopsAnalyzeCreditsTool, finops_expensive_queries: FinopsExpensiveQueriesTool, finops_query_history: FinopsQueryHistoryTool, diff --git a/packages/opencode/src/altimate/tools/dbt-adapter-access.ts b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts new file mode 100644 index 0000000000..ed4cd620c3 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-adapter-access.ts @@ -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): Promise { + 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() + 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 | undefined + const waited = new Promise((_, reject) => { + 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> { + 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 } +} diff --git a/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts b/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts new file mode 100644 index 0000000000..a3ccc67e99 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-cost-estimate.ts @@ -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(start: () => Promise, signal: AbortSignal): Promise { + if (signal.aborted) return Promise.reject(signal.reason) + return new Promise((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 = {}) { + 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).", + 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.") + 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).`, + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-cte-profile.ts b/packages/opencode/src/altimate/tools/dbt-cte-profile.ts new file mode 100644 index 0000000000..0e4913f06d --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-cte-profile.ts @@ -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.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-defer-state.ts b/packages/opencode/src/altimate/tools/dbt-defer-state.ts new file mode 100644 index 0000000000..9df344ec1b --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-defer-state.ts @@ -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.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-docs-coverage.ts b/packages/opencode/src/altimate/tools/dbt-docs-coverage.ts new file mode 100644 index 0000000000..8990306b72 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-docs-coverage.ts @@ -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.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-health.ts b/packages/opencode/src/altimate/tools/dbt-health.ts new file mode 100644 index 0000000000..096e2bc3f4 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-health.ts @@ -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.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-map-relations.ts b/packages/opencode/src/altimate/tools/dbt-map-relations.ts new file mode 100644 index 0000000000..f949274620 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-map-relations.ts @@ -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.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-run-results.ts b/packages/opencode/src/altimate/tools/dbt-run-results.ts new file mode 100644 index 0000000000..c6f2cf396c --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-run-results.ts @@ -0,0 +1,19 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DbtRunResultsTool = Tool.define("dbt_run_results", { + description: "The latest dbt run's results from target/run_results.json: command, duration and each node's status.", + parameters: z.object({ + project_dir: z + .string() + .optional() + .describe("dbt project folder (default: the dbt project found from the working directory)"), + }), + async execute() { + return { + title: "dbt_run_results: not implemented", + metadata: { success: false, error: "not implemented" }, + output: "dbt_run_results is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/dbt-sql-graph.ts b/packages/opencode/src/altimate/tools/dbt-sql-graph.ts new file mode 100644 index 0000000000..0c4db3c980 --- /dev/null +++ b/packages/opencode/src/altimate/tools/dbt-sql-graph.ts @@ -0,0 +1,16 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DbtSqlGraphTool = Tool.define("dbt_sql_graph", { + description: "A dbt model's SQL as a graph: its CTEs, joins and filters, and the edges between them.", + parameters: z.object({ + model: z.string().describe("Model name"), + }), + async execute() { + return { + title: "dbt_sql_graph: not implemented", + metadata: { success: false, error: "not implemented" }, + output: "dbt_sql_graph is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/src/altimate/tools/docs-share-comments.ts b/packages/opencode/src/altimate/tools/docs-share-comments.ts new file mode 100644 index 0000000000..8963268cdd --- /dev/null +++ b/packages/opencode/src/altimate/tools/docs-share-comments.ts @@ -0,0 +1,20 @@ +import z from "zod" +import { Tool } from "../../tool/tool" + +export const DocsShareCommentsTool = Tool.define("docs_share_comments", { + description: "Comment threads on shared dbt docs: list open threads, reply to one, or resolve one.", + parameters: z.object({ + action: z.enum(["list", "reply", "resolve"]).describe("What to do"), + project: z.string().optional().describe("dbt project name the shared docs belong to"), + share_id: z.number().int().optional().describe("Shared docs id"), + group_id: z.number().int().optional().describe("Comment thread id"), + text: z.string().optional().describe("Reply text"), + }), + async execute() { + return { + title: "docs_share_comments: not implemented", + metadata: { success: false, error: "not implemented" }, + output: "docs_share_comments is not implemented in this build of altimate-code yet.", + } + }, +}) diff --git a/packages/opencode/test/altimate/dbt-adapter-access.test.ts b/packages/opencode/test/altimate/dbt-adapter-access.test.ts new file mode 100644 index 0000000000..e91d254d3f --- /dev/null +++ b/packages/opencode/test/altimate/dbt-adapter-access.test.ts @@ -0,0 +1,272 @@ +// The tools the dbt Power User features call: their allow-list entries and placeholder answers, the +// one gate every dbt-adapter-backed tool goes through, and the API helper for new endpoint files. The +// dbt adapter is replaced through `dbtAdapterInternals`, so these tests need no Python or dbt. +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test" +import { mkdtemp, rm, writeFile } from "node:fs/promises" +import { realpathSync } from "node:fs" +import os from "node:os" +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 { dbtAdapterAccessInternals, dbtAdapterFor } from "@/altimate/tools/dbt-adapter-access" +import { EXPOSED, MCP_OPEN_WRITE_TOOLS, WRITE_TOOLS } from "@/altimate/tool-cli/allow-list" +import { AltimateApi } from "@/altimate/api/client" +import { Instance } from "@/project/instance" +import { disposeInstance } from "@/effect/instance-registry" +import { initTool } from "./tool-fixture" + +/** Each tool with the smallest arguments its parameters accept. */ +const MINIMAL_ARGS: Record> = { + dbt_run_results: {}, + dbt_defer_state: { project_dir: "." }, + dbt_map_relations: { sql: "select 1" }, + docs_share_comments: { action: "list" }, + dbt_cost_estimate: {}, + dbt_health: {}, + dbt_sql_graph: { model: "customers" }, + dbt_docs_coverage: { model: "customers" }, + dbt_cte_profile: { model: "customers" }, +} +const FEATURE_TOOLS = Object.keys(MINIMAL_ARGS) +/** Tools whose real implementation has landed; they no longer answer as placeholders. */ +const IMPLEMENTED = new Set(["dbt_cost_estimate"]) + +const ctx: Tool.Context = { + sessionID: SessionID.make("ses_dbt_adapter_access"), + messageID: MessageID.make("msg_dbt_adapter_access"), + agent: "analyst", + abort: new AbortController().signal, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, +} + +let project: string + +function useConfig() { + dbtAdapterInternals.readConfig = async () => ({ + projectRoot: project, + pythonPath: "python3", + dbtIntegration: "corecommand", + queryLimit: 500, + }) +} + +beforeAll(async () => { + project = await mkdtemp(path.join(os.tmpdir(), "dbt-adapter-access-")) + await writeFile(path.join(project, "dbt_project.yml"), "name: jaffle_shop\n") +}) + +afterAll(async () => { + await rm(project, { recursive: true, force: true }) +}) + +beforeEach(() => resetDbtAdapter()) + +afterEach(() => { + resetDbtAdapter() + delete dbtAdapterInternals.readConfig + delete dbtAdapterInternals.create +}) + +describe("feature tools in the allow-list", () => { + test("all nine are exposed, in the map's alphabetical order, and none is a write tool", () => { + const ids = Object.keys(EXPOSED) + for (const id of FEATURE_TOOLS) { + expect(ids).toContain(id) + expect(WRITE_TOOLS.has(id)).toBe(false) + expect(MCP_OPEN_WRITE_TOOLS.has(id)).toBe(false) + } + const listed = ids.filter((id) => id.startsWith("dbt_") || id.startsWith("docs_")) + expect(listed).toEqual([...listed].sort()) + }) + + test("each placeholder answers that it isn't implemented, as a failure", async () => { + for (const id of FEATURE_TOOLS.filter((id) => !IMPLEMENTED.has(id))) { + const tool = await initTool(EXPOSED[id] as any) + expect(tool.id).toBe(id) + const result = await tool.execute(MINIMAL_ARGS[id], ctx) + expect(result.title).toBe(`${id}: not implemented`) + expect(result.metadata).toEqual({ success: false, error: "not implemented", truncated: false }) + expect(result.output).toContain(id) + } + }) +}) + +describe("dbtAdapterFor", () => { + let created: number + beforeEach(() => { + created = 0 + useConfig() + dbtAdapterInternals.create = async () => { + created += 1 + return { isInitialized: () => true, dispose: async () => {} } + } + }) + + test("refuses a read-only call and never creates the adapter", async () => { + const access = await dbtAdapterFor({ ...ctx, extra: { forceReadOnly: true } }) + expect(access.adapter).toBeUndefined() + expect(access.refusal).toBe("read_only") + expect(access.reason).toContain("--allow-write") + expect(access.reason).toContain("MCP server") + expect(created).toBe(0) + }) + + test("refuses a plan-mode call", async () => { + const access = await dbtAdapterFor({ ...ctx, agent: "plan" }) + expect(access.refusal).toBe("read_only") + expect(created).toBe(0) + }) + + test("returns the adapter where writes are allowed", async () => { + const access = await dbtAdapterFor(ctx) + expect(access.refusal).toBeUndefined() + expect(access.adapter?.isInitialized()).toBe(true) + expect(created).toBe(1) + }) + + test("says when the adapter didn't load the project", async () => { + dbtAdapterInternals.create = async () => ({ isInitialized: () => false, dispose: async () => {} }) + const access = await dbtAdapterFor(ctx) + expect(access).toEqual({ refusal: "not_loaded", reason: "the dbt adapter didn't load the project" }) + }) + + test("says there is no dbt project when the config finds none", async () => { + dbtAdapterInternals.readConfig = async () => null + const access = await dbtAdapterFor(ctx) + expect(access).toEqual({ refusal: "no_project", reason: "no dbt project here" }) + }) + + test("says when the adapter doesn't start in time", async () => { + dbtAdapterInternals.create = () => new Promise(() => {}) + const saved = dbtAdapterAccessInternals.adapterStartTimeoutMs + dbtAdapterAccessInternals.adapterStartTimeoutMs = 20 + try { + const access = await dbtAdapterFor(ctx) + expect(access).toEqual({ refusal: "not_started", reason: "the dbt adapter didn't start within 0.02 s" }) + } finally { + dbtAdapterAccessInternals.adapterStartTimeoutMs = saved + } + }) + + test("says the adapter didn't start when the project exists but creating it fails", async () => { + dbtAdapterInternals.create = async () => { + created += 1 + throw new Error("dbt-integration missing") + } + const access = await dbtAdapterFor(ctx) + expect(access).toEqual({ refusal: "not_started", reason: "the dbt adapter didn't start" }) + expect(created).toBe(1) + }) + + test("a call cancelled while the adapter starts throws and stops waiting", async () => { + let entered = () => {} + const starting = new Promise((resolve) => (entered = resolve)) + dbtAdapterInternals.create = () => { + entered() + return new Promise(() => {}) + } + const controller = new AbortController() + const pending = dbtAdapterFor({ ...ctx, abort: controller.signal }) + await starting + controller.abort(new Error("cancelled")) + await expect(pending).rejects.toThrow("cancelled") + }) + + test("a cancelled call throws rather than answering", async () => { + const controller = new AbortController() + controller.abort() + await expect(dbtAdapterFor({ ...ctx, abort: controller.signal })).rejects.toThrow() + expect(created).toBe(0) + }) + + test("a session in a dbt project the adapter isn't set up for says so", async () => { + dbtAdapterInternals.readConfig = async () => null + try { + const access = await Instance.provide({ directory: project, fn: () => dbtAdapterFor(ctx) }) + expect(access).toEqual({ + refusal: "other_project", + reason: `the dbt adapter isn't set up for ${realpathSync(project)}`, + }) + expect(created).toBe(0) + } finally { + await disposeInstance(project) + } + }) + + test("a session in another dbt project than the adapter's says which", async () => { + const other = await mkdtemp(path.join(os.tmpdir(), "dbt-adapter-other-")) + await writeFile(path.join(other, "dbt_project.yml"), "name: other\n") + dbtAdapterInternals.readConfig = async () => ({ + projectRoot: other, + pythonPath: "python3", + dbtIntegration: "corecommand", + queryLimit: 500, + }) + try { + const access = await Instance.provide({ directory: project, fn: () => dbtAdapterFor(ctx) }) + expect(access).toEqual({ + refusal: "other_project", + reason: `the dbt adapter is set up for ${realpathSync(other)}, not ${realpathSync(project)}`, + }) + expect(created).toBe(0) + } finally { + await disposeInstance(project) + await rm(other, { recursive: true, force: true }) + } + }) +}) + +describe("AltimateApi.apiRequest", () => { + let home: string + let saved: string | undefined + beforeEach(async () => { + home = await mkdtemp(path.join(os.tmpdir(), "altimate-api-home-")) + saved = process.env.OPENCODE_TEST_HOME + process.env.OPENCODE_TEST_HOME = home + }) + afterEach(async () => { + if (saved === undefined) delete process.env.OPENCODE_TEST_HOME + else process.env.OPENCODE_TEST_HOME = saved + await rm(home, { recursive: true, force: true }) + }) + + test("fails with a clear message when no credentials are stored", async () => { + await expect(AltimateApi.apiRequest("GET", "/dbt/v1/x")).rejects.toThrow( + `No Altimate credentials are stored: sign in to Altimate in altimate-code first (they are saved to ${path.join(home, ".altimate", "altimate.json")}).`, + ) + }) + + test("sends the stored key and tenant and returns the JSON body", async () => { + await Bun.write( + path.join(home, ".altimate", "altimate.json"), + JSON.stringify({ altimateUrl: "https://api.example.test/", altimateInstanceName: "acme", altimateApiKey: "k1" }), + ) + const original = globalThis.fetch + const seen: { url: string; init: RequestInit }[] = [] + globalThis.fetch = (async (url: string, init: RequestInit) => { + seen.push({ url, init }) + return new Response(JSON.stringify({ ok: 1 }), { status: 200 }) + }) as unknown as typeof fetch + try { + expect(await AltimateApi.apiRequest("POST", "/dbt/v1/x", { a: 1 })).toEqual({ ok: 1 }) + expect(seen[0].url).toBe("https://api.example.test/dbt/v1/x") + const headers = seen[0].init.headers as Record + expect(headers.Authorization).toBe("Bearer k1") + expect(headers["x-tenant"]).toBe("acme") + expect(seen[0].init.body).toBe(JSON.stringify({ a: 1 })) + } finally { + globalThis.fetch = original + } + }) + + test("names the file when the stored credentials can't be read", async () => { + await Bun.write(path.join(home, ".altimate", "altimate.json"), "{not json") + await expect(AltimateApi.apiRequest("GET", "/dbt/v1/x")).rejects.toThrow( + `The Altimate credentials in ${path.join(home, ".altimate", "altimate.json")} can't be used`, + ) + }) +}) diff --git a/packages/opencode/test/altimate/dbt-cost-estimate.test.ts b/packages/opencode/test/altimate/dbt-cost-estimate.test.ts new file mode 100644 index 0000000000..5ce8e8b76d --- /dev/null +++ b/packages/opencode/test/altimate/dbt-cost-estimate.test.ts @@ -0,0 +1,272 @@ +// dbt_cost_estimate: the dry run's formatted size read back into bytes (and its upper bound) for each unit, +// 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 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, parseBytesProcessed, untilAbort } from "@/altimate/tools/dbt-cost-estimate" +import { initTool } from "./tool-fixture" + +const ctx: Tool.Context = { + sessionID: SessionID.make("ses_dbt_cost_estimate"), + messageID: MessageID.make("msg_dbt_cost_estimate"), + agent: "analyst", + abort: new AbortController().signal, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, +} + +let project: string + +type Calls = { nodes: string[]; queries: [string, string | undefined][]; dryRuns: string[] } + +function fakeAdapter( + calls: Calls, + opts: { type?: string; bytes?: unknown; compileFails?: boolean; dryRunFails?: boolean; compile?: () => Promise } = {}, +) { + return { + isInitialized: () => true, + dispose: async () => {}, + getAdapterType: () => opts.type ?? "bigquery", + unsafeCompileNode: async (model: string) => { + calls.nodes.push(model) + if (opts.compile) return opts.compile() + if (opts.compileFails) throw new Error("compilation failed") + return `compiled(${model})` + }, + unsafeCompileQuery: async (query: string, name?: string) => { + calls.queries.push([query, name]) + if (opts.compileFails) throw new Error("compilation failed") + return `compiled(${query})` + }, + validateSQLDryRun: async (query: string) => { + calls.dryRuns.push(query) + if (opts.dryRunFails) throw new Error("Access Denied: BigQuery job") + return "bytes" in opts && opts.bytes === null ? null : { bytes_processed: "bytes" in opts ? opts.bytes : "4.2 TiB" } + }, + } +} + +function useAdapter(calls: Calls, opts?: Parameters[1]) { + dbtAdapterInternals.readConfig = async () => ({ + projectRoot: project, + pythonPath: "python3", + dbtIntegration: "corecommand", + queryLimit: 500, + }) + dbtAdapterInternals.create = async () => fakeAdapter(calls, opts) +} + +beforeAll(async () => { + project = await mkdtemp(path.join(os.tmpdir(), "dbt-cost-estimate-")) + await writeFile(path.join(project, "dbt_project.yml"), "name: shop\n") +}) + +afterAll(async () => { + await rm(project, { recursive: true, force: true }) +}) + +let calls: Calls +beforeEach(() => { + resetDbtAdapter() + calls = { nodes: [], queries: [], dryRuns: [] } +}) +afterEach(() => { + resetDbtAdapter() + delete dbtAdapterInternals.readConfig + delete dbtAdapterInternals.create +}) + +describe("parseBytesProcessed", () => { + test.each([ + ["0.0 Bytes", 0, 0], + ["512.0 Bytes", 512, 512], + ["1.0 KiB", 1024, Math.ceil(1.05 * 1024)], + ["1.5 KiB", 1536, Math.ceil(1.55 * 1024)], + ["2.0 MiB", 2 * 1024 ** 2, Math.ceil(2.05 * 1024 ** 2)], + ["4.2 GiB", Math.round(4.2 * 1024 ** 3), Math.ceil(4.25 * 1024 ** 3)], + ["4.2 TiB", Math.round(4.2 * 1024 ** 4), Math.ceil(4.25 * 1024 ** 4)], + ["1.0 PiB", 1024 ** 5, Math.ceil(1.05 * 1024 ** 5)], + ["10.5 PiB", Math.round(10.5 * 1024 ** 5), Math.ceil(10.55 * 1024 ** 5)], + [" 7.0 MiB ", 7 * 1024 ** 2, Math.ceil(7.05 * 1024 ** 2)], + ])("reads %s as %d bytes, at most about %d", (display, bytes, maxBytes) => { + const parsed = parseBytesProcessed(display)! + expect(parsed.bytes).toBe(bytes) + // The bound is the figure plus half its last digit; past a PiB it carries a few bytes of float margin. + expect(parsed.maxBytes).toBeGreaterThanOrEqual(maxBytes) + expect(parsed.maxBytes).toBeLessThanOrEqual(maxBytes + maxBytes * 1e-14 + 1) + }) + + test("a rounded figure's upper bound covers a scan just over a limit", () => { + // 10 GiB + 20 MiB is shown as "10.0 GiB": the point estimate sits on the limit, the bound above it. + const over = 10 * 1024 ** 3 + 20 * 1024 ** 2 + const parsed = parseBytesProcessed("10.0 GiB")! + expect(parsed.bytes).toBe(10 * 1024 ** 3) + expect(parsed.maxBytes).toBeGreaterThanOrEqual(over) + }) + + test("the upper bound reaches a count just past a tie that the dry run shows rounded down", () => { + // 9.25 PiB is a tie in the dry run's float formatting, which shows it as "9.2": the bound sits above the tie. + const tie = 37n * 1024n ** 5n / 4n + expect(BigInt(parseBytesProcessed("9.2 PiB")!.maxBytes)).toBeGreaterThan(tie) + }) + + test("takes a number as the exact count", () => { + expect(parseBytesProcessed(2048)).toEqual({ bytes: 2048, maxBytes: 2048 }) + }) + + test.each([["4.2 EiB"], ["4.2"], ["TiB"], [""], ["about 4 GiB"], ["-1.0 KiB"], [null], [undefined], [{}], [Number.NaN], [-5]])( + "does not read %p", + (value) => { + expect(parseBytesProcessed(value)).toBeUndefined() + }, + ) +}) + +describe("dbt_cost_estimate", () => { + test("estimates a model compiled by name", async () => { + useAdapter(calls) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) + expect(calls).toEqual({ nodes: ["orders"], queries: [], dryRuns: ["compiled(orders)"] }) + expect(result.metadata).toEqual({ + success: true, + supported: true, + adapter: "bigquery", + bytes: Math.round(4.2 * 1024 ** 4), + maxBytes: Math.ceil(4.25 * 1024 ** 4), + display: "4.2 TiB", + model: "orders", + truncated: false, + }) + expect(result.output).toContain("orders would process 4.2 TiB") + }) + + test("estimates SQL as given", async () => { + useAdapter(calls, { bytes: "1.0 GiB" }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select 1" }, ctx) + expect(calls).toEqual({ nodes: [], queries: [["select 1", undefined]], dryRuns: ["compiled(select 1)"] }) + expect(result.metadata).toEqual({ + success: true, + supported: true, + adapter: "bigquery", + bytes: 1024 ** 3, + maxBytes: Math.ceil(1.05 * 1024 ** 3), + display: "1.0 GiB", + truncated: false, + }) + }) + + test("a number from the dry run is shown with its unit and is exact", async () => { + useAdapter(calls, { bytes: 2048 }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select 1" }, ctx) + expect(result.metadata).toMatchObject({ bytes: 2048, maxBytes: 2048, display: "2048 Bytes" }) + expect(result.output).toContain("2048 Bytes") + }) + + test.each(["snowflake", "databricks", "duckdb"])("answers supported:false on %s 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).toContain("only available on BigQuery") + expect(calls).toEqual({ nodes: [], queries: [], dryRuns: [] }) + }) + + test("refuses a read-only call and starts no adapter", async () => { + let created = 0 + useAdapter(calls) + const make = dbtAdapterInternals.create! + dbtAdapterInternals.create = async (config) => { + created += 1 + return make(config) + } + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, { ...ctx, extra: { forceReadOnly: true } }) + expect(created).toBe(0) + expect(result.metadata).toMatchObject({ success: false, refusal: "read_only" }) + expect(result.output).toContain("--allow-write") + }) + + test("rejects a call that passes both a model and SQL, estimating neither", async () => { + useAdapter(calls) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders", sql: "select 1" }, ctx) + expect(result.metadata.success).toBe(false) + expect(result.output).toContain("not both") + expect(calls).toEqual({ nodes: [], queries: [], dryRuns: [] }) + }) + + test("asks for something to estimate", async () => { + useAdapter(calls) + const result = await (await initTool(DbtCostEstimateTool)).execute({}, ctx) + expect(result.metadata.success).toBe(false) + expect(calls).toEqual({ nodes: [], queries: [], dryRuns: [] }) + }) + + test("reports a model dbt can't compile, as a compile failure, without a dry run", async () => { + useAdapter(calls, { compileFails: true }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "nope" }, ctx) + expect(result.title).toBe("dbt_cost_estimate: compile failed") + expect(result.metadata).toMatchObject({ success: false, error: "compilation failed" }) + expect(calls.dryRuns).toEqual([]) + }) + + test("reports a compile that produced nothing, without a dry run", async () => { + useAdapter(calls, { compile: async () => " " }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, ctx) + expect(result.metadata).toMatchObject({ success: false, error: "The query compiled to nothing." }) + expect(calls.dryRuns).toEqual([]) + }) + + test("reports a dry run that returns nothing, as dbt-core before 1.6 does", async () => { + useAdapter(calls, { bytes: null }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select 1" }, ctx) + expect(result.metadata).toMatchObject({ success: false }) + expect(result.output).toContain("before 1.6") + }) + + test("a cancelled call stops waiting for a compile that never finishes", async () => { + const abort = new AbortController() + useAdapter(calls, { compile: () => new Promise(() => {}) }) + const run = (await initTool(DbtCostEstimateTool)).execute({ model: "orders" }, { ...ctx, abort: abort.signal }) + await Bun.sleep(20) + abort.abort(new Error("cancelled")) + await expect(run).rejects.toThrow("cancelled") + expect(calls.dryRuns).toEqual([]) + }) + + test("work queued before a cancellation is not started by it", async () => { + // The signal reads as live at the first check and cancelled once the queued work comes to run. + let reads = 0 + const signal = { + get aborted() { + return ++reads > 1 + }, + reason: new Error("cancelled"), + addEventListener() {}, + removeEventListener() {}, + } as unknown as AbortSignal + let started = 0 + await expect(untilAbort(async () => void started++, signal)).rejects.toThrow("cancelled") + expect(started).toBe(0) + }) + + test("reports a dry run the warehouse refused", async () => { + useAdapter(calls, { dryRunFails: true }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select 1" }, ctx) + expect(result.title).toBe("dbt_cost_estimate: dry run failed") + expect(result.metadata).toMatchObject({ success: false, error: "Access Denied: BigQuery job" }) + }) + + test("reports a size it can't read instead of guessing", async () => { + useAdapter(calls, { bytes: "lots" }) + const result = await (await initTool(DbtCostEstimateTool)).execute({ sql: "select 1" }, ctx) + expect(result.metadata.success).toBe(false) + expect(result.metadata.bytes).toBeUndefined() + expect(result.output).toContain('"lots"') + }) +})