Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions packages/opencode/src/altimate/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<any> {
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)
Comment thread
hkaltai marked this conversation as resolved.
Resolved
}

export async function listDatamates(creds?: AltimateCredentials) {
creds ??= await getCredentials()
const data = await request(creds, "GET", "/datamates/")
Expand Down
108 changes: 102 additions & 6 deletions packages/opencode/src/altimate/native/dbt/column-reach.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
// lineage engine cannot settle is reported as such: models it could not trace (no compiled SQL, or
// SQL it could not parse), models that name the column only outside their select list (where the
// engine reports no edge), and models that read it through a table name several parents share.
import { loadRawManifest, findModel } from "./helpers"
import * as core from "@altimateai/altimate-core"
import { loadRawManifest, findModel, detectDialect } from "./helpers"
import { dbtLineage } from "./lineage"
import { missingColumn, projectLineage, selectsStar, stripSql } from "./project-lineage"

Expand All @@ -15,6 +16,14 @@ export interface ColumnReachModel {
unique_id: string
/** Its output columns that come from the traced column. */
columns: string[]
/**
* How each of those columns (keyed as in `columns`) comes from the traced column, as the lineage
* engine classifies it: Original (carried as is), Alias (renamed), Transformation, Not sure or
* Non select. It covers the whole path from the traced column: a column is Original or Alias only
* when every hop is, so a column read from a calculation is never Original. A column whose
* edges carry no classification has no entry.
*/
lens_types?: Record<string, string>
}

export interface ColumnReachUnsure {
Expand Down Expand Up @@ -58,6 +67,16 @@ export interface ColumnReach {
const MAX_MODELS = 300
const TRACED = new Set(["model", "snapshot"])

// How far a classification is from "the value arrives unchanged", least to most.
const LENS_ORDER = ["Original", "Alias", "Non select", "Not sure", "Transformation"]

/** The classification of a path made of two: the one further from unchanged, unknown if either is. */
function joinLens(a: string | undefined, b: string | undefined): string | undefined {
if (a === undefined || b === undefined) return undefined
const rank = (lens: string) => (LENS_ORDER.includes(lens) ? LENS_ORDER.indexOf(lens) : LENS_ORDER.length)
return rank(a) >= rank(b) ? a : b
}

/** "db"."schema"."orders"."amount" → { parts: ["db","schema","orders"], column: "amount" }, lower-cased. */
function splitSource(source: unknown): { parts: string[]; column: string; exact: string } | null {
const text =
Expand All @@ -66,8 +85,7 @@ function splitSource(source: unknown): { parts: string[]; column: string; exact:
// Split on dots outside quotes: "a"."net.amount" is table a, column net.amount.
// A doubled closing delimiter inside a quoted name is one character ("a""b" is a"b, [a]]b] is a]b).
const raw = [...text.matchAll(/"((?:[^"]|"")*)"|`((?:[^`]|``)*)`|\[((?:[^\]]|\]\])*)\]|([^."`\[\]]+)/g)].map(
(m) =>
m[1]?.replaceAll('""', '"') ?? m[2]?.replaceAll("``", "`") ?? m[3]?.replaceAll("]]", "]") ?? m[4] ?? "",
(m) => m[1]?.replaceAll('""', '"') ?? m[2]?.replaceAll("``", "`") ?? m[3]?.replaceAll("]]", "]") ?? m[4] ?? "",
)
if (raw.length < 2) return null
// `exact` keeps the column's case, for parents that document two columns differing only by case.
Expand All @@ -94,6 +112,59 @@ function relationKeys(node: any): string[] {
return [...keys]
}

type LineageEdge = { source: unknown; target: string; lineage_type?: string; lens_type?: string }

/**
* The engine rates every edge "Not sure" when the table it reads is written with its schema
* ("db"."schema"."orders", as dbt compiles a ref) and its schema lists that table by bare name only.
* The model's SQL is traced again with each parent listed under every way its relation is written,
* and an edge both runs report (matched by output column, table name and source column, as the
* first run drops the qualification) takes the second run's rating. Anything else keeps its own.
*/
function rated(
edges: LineageEdge[],
sql: string,
dialect: string,
parents: string[],
lookup: (id: string) => any,
): LineageEdge[] {
if (!sql || parents.length === 0 || !edges.some((edge) => edge.lens_type === "Not sure")) return edges
try {
const tables: Record<string, { columns: { name: string; type: string }[] }> = {}
for (const parent of parents) {
const node = lookup(parent)
const columns = Object.entries<any>(node?.columns ?? {}).map(([key, col]) => ({
name: String(col?.name ?? key),
type: String(col?.data_type ?? col?.type ?? ""),
}))
Comment thread
hkaltai marked this conversation as resolved.
Resolved
if (columns.length === 0) continue
for (const key of relationKeys(node)) tables[key] = { columns }
Comment thread
hkaltai marked this conversation as resolved.
Resolved
}
if (Object.keys(tables).length === 0) return edges
const schema = core.Schema.fromJson(JSON.stringify({ tables, version: "1" }))
const again: LineageEdge[] =
JSON.parse(JSON.stringify(core.columnLineage(sql, dialect, schema))).column_lineage ?? []
const keyOf = (edge: LineageEdge) => {
const source = splitSource(edge.source)
return source ? `${String(edge.target).toLowerCase()}|${source.parts.at(-1)}.${source.column}` : null
Comment thread
hkaltai marked this conversation as resolved.
Resolved
}
const lenses = new Map<string, string>()
for (const edge of again) {
const key = keyOf(edge)
// Edges into one output from the same column keep the one furthest from unchanged.
if (key && typeof edge.lens_type === "string")
lenses.set(key, joinLens(lenses.get(key), edge.lens_type) ?? edge.lens_type)
}
return edges.map((edge) => {
const key = edge.lens_type === "Not sure" ? keyOf(edge) : null
const lens = key ? lenses.get(key) : undefined
return lens ? { ...edge, lens_type: lens } : edge
})
} catch {
return edges
}
}

/**
* The parents an edge's source table names, matched at the qualification the edge carries: a
* qualified name that matches no parent names none (it is some other relation), and a bare name
Expand Down Expand Up @@ -274,6 +345,8 @@ export function columnReach(manifestPath: string, model: string, column: string,
if (unsettled) spelled = []
else if (!exact && matches.length > 0) spelled = matches
const trackedExact = new Map<string, Set<string>>([[targetId, new Set(spelled)]])
// How each tracked column comes from the traced column, per node (the traced column itself is Original).
const lensOf = new Map<string, Map<string, string | undefined>>([[targetId, new Map([[column0, "Original"]])]])
const carries = (parent: string, source: { column: string; exact: string }) =>
!!tracked.get(parent)?.has(source.column) &&
(!caseCollides(lookup(parent), source.column) || !!trackedExact.get(parent)?.has(source.exact))
Expand Down Expand Up @@ -307,7 +380,7 @@ export function columnReach(manifestPath: string, model: string, column: string,
unsure.add(id)
continue
}
const edges: { source: unknown; target: string; lineage_type?: string }[] = lineage?.column_lineage?.length
const listed: LineageEdge[] = lineage?.column_lineage?.length
? lineage.column_lineage
: Object.entries<any>(lineage?.column_dict ?? {}).flatMap(([out, sources]) =>
(Array.isArray(sources) ? sources : [sources]).map((source) => ({
Expand All @@ -323,6 +396,7 @@ export function columnReach(manifestPath: string, model: string, column: string,
// cannot say which one is read; a `select *` from a parent whose schema does not list the
// column cannot be expanded to it. Both are possible reads with unknown outputs.
const sqlText: string = nodes[id]?.compiled_code || nodes[id]?.compiled_sql || ""
const edges = rated(listed, sqlText, dialect ?? detectDialect(manifest), allParents, lookup)
Comment thread
hkaltai marked this conversation as resolved.
Resolved
const bareName = (p: string) => {
const node = lookup(p)
return String(node?.alias || node?.identifier || node?.name || p).toLowerCase()
Expand All @@ -346,6 +420,7 @@ export function columnReach(manifestPath: string, model: string, column: string,

const carried = new Set<string>()
const carriedExact = new Set<string>()
const carriedLens = new Map<string, string | undefined>()
let reads = false
let ambiguous = false
for (const edge of edges) {
Expand All @@ -360,7 +435,14 @@ export function columnReach(manifestPath: string, model: string, column: string,
}
reads = true
if (edge.lineage_type !== "indirect" && typeof edge.target === "string") {
carried.add(edge.target.toLowerCase())
const out = edge.target.toLowerCase()
const lens = joinLens(
lensOf.get(candidates[0]!)?.get(source.column),
typeof edge.lens_type === "string" ? edge.lens_type : undefined,
)
// Several edges into one output: it is as far from unchanged as the furthest of them.
carriedLens.set(out, carried.has(out) ? joinLens(carriedLens.get(out), lens) : lens)
carried.add(out)
carriedExact.add(edge.target)
}
}
Expand All @@ -376,10 +458,24 @@ export function columnReach(manifestPath: string, model: string, column: string,
if (reads) {
tracked.set(id, carried)
trackedExact.set(id, carriedExact)
lensOf.set(id, carriedLens)
// Outputs fed by an unsettled or ephemeral parent, or read through an ambiguous name, stay unsettled.
// A NATURAL JOIN beside the column may join on it, or carry it on in another output.
if (ambiguous || fromUnsure || viaEphemeral || partial || opaque) unsure.add(id)
reached.push({ name: nodes[id]?.name ?? id, unique_id: id, columns: [...carried].sort() })
const columns = [...carried].sort()
// Built with fromEntries: assigning to a column named __proto__ would set the prototype instead.
const lens_types: Record<string, string> = Object.fromEntries(
columns.flatMap((col) => {
const lens = carriedLens.get(col)
return lens === undefined ? [] : [[col, lens] as const]
}),
)
reached.push({
name: nodes[id]?.name ?? id,
unique_id: id,
columns,
...(Object.keys(lens_types).length > 0 && { lens_types }),
})
continue
}

Expand Down
18 changes: 18 additions & 0 deletions packages/opencode/src/altimate/tool-cli/allow-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -106,10 +115,19 @@ export const EXPOSED: Record<string, Source> = {
altimate_core_track_lineage: AltimateCoreTrackLineageTool,
altimate_core_validate: AltimateCoreValidateTool,
data_diff: DataDiffTool,
dbt_cost_estimate: DbtCostEstimateTool,
Comment thread
hkaltai marked this conversation as resolved.
Resolved
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,
Expand Down
101 changes: 101 additions & 0 deletions packages/opencode/src/altimate/tools/dbt-adapter-access.ts
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> {
Comment thread
hkaltai marked this conversation as resolved.
Resolved
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: re-run with --allow-write",
Comment thread
hkaltai marked this conversation as resolved.
Resolved
}
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<typeof setTimeout> | undefined
const waited = new Promise<never>((_, 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 }
}
17 changes: 17 additions & 0 deletions packages/opencode/src/altimate/tools/dbt-cost-estimate.ts
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 DbtCostEstimateTool = Tool.define("dbt_cost_estimate", {
description: "Estimate the bytes a dbt model or a SQL query would scan, from a warehouse dry run (BigQuery).",
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() {
return {
title: "dbt_cost_estimate: not implemented",
metadata: { success: false, error: "not implemented" },
output: "dbt_cost_estimate is not implemented in this build of altimate-code yet.",
}
},
})
17 changes: 17 additions & 0 deletions packages/opencode/src/altimate/tools/dbt-cte-profile.ts
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.",
}
},
})
Loading
Loading