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
2 changes: 1 addition & 1 deletion packages/dbt-tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"scripts": {
"build": "bun build src/index.ts --outdir dist --target node --format esm && bun run script/copy-python.ts",
"typecheck": "tsc --noEmit",
"test": "bun test test/check.test.ts test/cli.test.ts test/config.test.ts test/dbt-cli.test.ts test/dbt-resolve.test.ts test/adapter-bun.test.ts test/stale-manifest.test.ts test/build-integrity.test.ts test/adapter-target-path.test.ts --timeout 30000",
"test": "bun test test/check.test.ts test/cli.test.ts test/config.test.ts test/dbt-cli.test.ts test/dbt-resolve.test.ts test/adapter-bun.test.ts test/stale-manifest.test.ts test/partial-manifest.test.ts test/build-integrity.test.ts test/adapter-target-path.test.ts --timeout 30000",
"test:e2e": "bun test test/e2e/ --timeout 300000"
},
"dependencies": {
Expand Down
7 changes: 6 additions & 1 deletion packages/dbt-tools/src/adapter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Config } from "./config"
import { bufferLog } from "./log-buffer"
import { recordManifest } from "./stale-manifest"
import { recordPartialManifest } from "./partial-manifest"
export { getRecentDbtLogs, clearDbtLogs } from "./log-buffer"
import {
DBTProjectIntegrationAdapter,
Expand Down Expand Up @@ -38,6 +39,7 @@ import type {
DBTProjectIntegration,
DBTDiagnosticData,
DeferConfig,
ParsedManifest,
RuntimePythonEnvironment,
} from "@altimateai/dbt-integration"

Expand Down Expand Up @@ -231,7 +233,10 @@ export async function create(cfg: Config, options: CreateOptions = {}): Promise<
)

// Before `initialize`, whose parse is the one the commands answer from.
adapter.on(DBTProjectIntegrationAdapterEvents.MANIFEST_PARSED, recordManifest)
adapter.on(DBTProjectIntegrationAdapterEvents.MANIFEST_PARSED, (parsed: ParsedManifest) => {
recordManifest(parsed)
recordPartialManifest(adapter, parsed)
})
try {
await adapter.initialize()
} catch (e) {
Expand Down
46 changes: 46 additions & 0 deletions packages/dbt-tools/src/partial-manifest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import path from "path"
import type { ParsedManifest, PartialManifest } from "@altimateai/dbt-integration"

// Each adapter's last parse errors, kept while the manifest dbt Fusion wrote for it is missing what failed to parse.
const partial = new WeakMap<object, PartialManifest>()

/** Takes each manifest an adapter parsed: a later parse with no errors clears the mark. */
export function recordPartialManifest(adapter: object, parsed: ParsedManifest): void {
if (parsed.partial?.errors.length) partial.set(adapter, parsed.partial)
else partial.delete(adapter)
}

/** Files named in the note's sentence; the rest are counted. */
const NAMED_FILES = 5
/** Errors the note carries; the rest are counted. Every answer carries the note, so a parse failing everywhere can't swell it. */
const KEPT_ERRORS = 10

/**
* What an answer built from the adapter's manifest adds, or undefined when its last parse had no errors.
* Paths inside `projectRoot` are given relative to it.
*/
export function partialManifestNote(adapter: object, projectRoot?: string) {
const mark = partial.get(adapter)
if (!mark) return undefined
const shown = (file: string) => {
if (!projectRoot) return file
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
const inside = path.relative(projectRoot, file)
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
const outside = !inside || inside === ".." || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)
return outside ? file : inside.split(path.sep).join("/")
}
const errors = mark.errors.map((e) => ({ file_path: shown(e.filePath), message: e.message }))
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
const files = [...new Set(errors.map((e) => e.file_path))]
const named = files.slice(0, NAMED_FILES)
const more = files.length - named.length
const list =
more > 0
? `${named.join(", ")} and ${more} more file${more === 1 ? "" : "s"}`
: named.length > 1
? `${named.slice(0, -1).join(", ")} and ${named[named.length - 1]}`
: named[0]
return {
message: `This graph is missing parts because ${list} failed to parse.`,
errors: errors.slice(0, KEPT_ERRORS),
...(errors.length > KEPT_ERRORS && { omitted_errors: errors.length - KEPT_ERRORS }),
}
}
113 changes: 113 additions & 0 deletions packages/dbt-tools/test/partial-manifest.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { describe, expect, spyOn, test } from "bun:test"
import { DBTProjectIntegrationAdapter, DBTProjectIntegrationAdapterEvents } from "@altimateai/dbt-integration"
import type { ParsedManifest } from "@altimateai/dbt-integration"
import { create } from "../src/adapter"
import { partialManifestNote, recordPartialManifest } from "../src/partial-manifest"

const ROOT = "/p"
const MISSING_REF = "Ref 'stg_orderz' not found in project. Searched for 'jaffle_shop.stg_orderz, stg_orderz'"

const parsed = (...errors: { filePath: string; message: string }[]) =>
(errors.length ? { partial: { errors } } : {}) as ParsedManifest

describe("the partial manifest note", () => {
test("is absent for an adapter whose last parse had no errors", () => {
const adapter = {}
expect(partialManifestNote(adapter, ROOT)).toBeUndefined()
recordPartialManifest(adapter, parsed())
expect(partialManifestNote(adapter, ROOT)).toBeUndefined()
})

test("names the file that failed to parse, relative to the project, with its error", () => {
const adapter = {}
recordPartialManifest(adapter, parsed({ filePath: "/p/models/customers.sql", message: MISSING_REF }))
expect(partialManifestNote(adapter, ROOT)).toEqual({
message: "This graph is missing parts because models/customers.sql failed to parse.",
errors: [{ file_path: "models/customers.sql", message: MISSING_REF }],
})
})

test("keeps a path outside the project, or one given with no project, as dbt wrote it", () => {
const adapter = {}
recordPartialManifest(adapter, parsed({ filePath: "/elsewhere/models/a.sql", message: "x" }))
expect(partialManifestNote(adapter, ROOT)?.errors[0]?.file_path).toBe("/elsewhere/models/a.sql")
// A sibling folder whose name starts with the project's is outside it.
recordPartialManifest(adapter, parsed({ filePath: "/p2/models/a.sql", message: "x" }))
expect(partialManifestNote(adapter, ROOT)?.errors[0]?.file_path).toBe("/p2/models/a.sql")
recordPartialManifest(adapter, parsed({ filePath: "models/a.sql", message: "x" }))
expect(partialManifestNote(adapter)?.errors[0]?.file_path).toBe("models/a.sql")
})

test("names each file once, however many errors it has", () => {
const adapter = {}
recordPartialManifest(
adapter,
parsed(
{ filePath: "/p/models/a.sql", message: "one" },
{ filePath: "/p/models/a.sql", message: "two" },
{ filePath: "/p/models/b.sql", message: "three" },
),
)
const note = partialManifestNote(adapter, ROOT)
expect(note?.message).toBe("This graph is missing parts because models/a.sql and models/b.sql failed to parse.")
expect(note?.errors).toHaveLength(3)
})

test("counts the files past the fifth instead of naming them", () => {
const adapter = {}
const errors = ["a", "b", "c", "d", "e", "f", "g"].map((name) => ({ filePath: `/p/models/${name}.sql`, message: "x" }))
recordPartialManifest(adapter, parsed(...errors))
expect(partialManifestNote(adapter, ROOT)?.message).toBe(
"This graph is missing parts because models/a.sql, models/b.sql, models/c.sql, models/d.sql, models/e.sql and 2 more files failed to parse.",
)
recordPartialManifest(adapter, parsed(...errors.slice(0, 6)))
expect(partialManifestNote(adapter, ROOT)?.message).toContain("models/e.sql and 1 more file failed to parse.")
})

test("carries the first ten errors and counts the rest", () => {
const adapter = {}
const errors = Array.from({ length: 12 }, (_, i) => ({ filePath: `/p/models/m${i}.sql`, message: `error ${i}` }))
recordPartialManifest(adapter, parsed(...errors))
const note = partialManifestNote(adapter, ROOT)
expect(note?.errors.map((e) => e.message)).toEqual(errors.slice(0, 10).map((e) => e.message))
expect(note?.omitted_errors).toBe(2)
expect(note?.message).toContain("and 7 more files failed to parse.")
recordPartialManifest(adapter, parsed(...errors.slice(0, 10)))
expect(partialManifestNote(adapter, ROOT)).not.toHaveProperty("omitted_errors")
})

test("goes once a later parse has no errors", () => {
const adapter = {}
recordPartialManifest(adapter, parsed({ filePath: "/p/models/customers.sql", message: MISSING_REF }))
recordPartialManifest(adapter, parsed())
expect(partialManifestNote(adapter, ROOT)).toBeUndefined()
})

test("is each adapter's own", () => {
const broken = {}
const whole = {}
recordPartialManifest(broken, parsed({ filePath: "/p/models/customers.sql", message: MISSING_REF }))
recordPartialManifest(whole, parsed())
expect(partialManifestNote(broken, ROOT)).toBeDefined()
expect(partialManifestNote(whole, ROOT)).toBeUndefined()
})
})

describe("create", () => {
test("hears the partial parse `initialize` runs, and the clean one after it", async () => {
const partial = { errors: [{ filePath: "/p/models/customers.sql", message: MISSING_REF }] }
const initialize = spyOn(DBTProjectIntegrationAdapter.prototype, "initialize").mockImplementation(async function (
this: DBTProjectIntegrationAdapter,
) {
this.emit(DBTProjectIntegrationAdapterEvents.MANIFEST_PARSED, { partial })
})
try {
const adapter = await create({ projectRoot: ROOT, pythonPath: "python3", dbtIntegration: "fusion", queryLimit: 500 })
expect(partialManifestNote(adapter, ROOT)?.errors).toEqual([{ file_path: "models/customers.sql", message: MISSING_REF }])
adapter.emit(DBTProjectIntegrationAdapterEvents.MANIFEST_PARSED, {})
expect(partialManifestNote(adapter, ROOT)).toBeUndefined()
} finally {
initialize.mockRestore()
}
})
})
6 changes: 4 additions & 2 deletions packages/opencode/src/altimate/mcp-server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export async function serverInstructions(): Promise<string> {
// text (for dbt_lineage only its header: the mappings and edges travel as data), only the lineage
// fields are passed, and the whole is capped.
const STRUCTURED_FIELDS: Record<string, readonly string[]> = {
dbt_lineage: ["model_name", "model_unique_id", "confidence", "confidence_factors", "upstream", "columns", "edges", "error"],
dbt_lineage: ["model_name", "model_unique_id", "confidence", "partial_manifest", "confidence_factors", "upstream", "columns", "edges", "error"],
dbt_sql_graph: ["model", "nodes", "edges", "error"],
impact_analysis: [
"model",
Expand Down Expand Up @@ -93,7 +93,9 @@ export function structuredResult(tool: string, metadata: Record<string, unknown>
if (own && typeof own === "object" && !Array.isArray(own)) {
// The text repeats every edge that `columnLineage` already carries: only its header goes with them.
const head = report.split(/\n(?:Column edges \(|Trace of )/)[0]!.trim()
const full = { ...(own as Record<string, unknown>), report: head }
// The partial-parse mark is the tool's, not the integration's: it goes beside the result.
const mark = "partial_manifest" in metadata ? { partial_manifest: metadata.partial_manifest } : {}
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
const full = { ...(own as Record<string, unknown>), ...mark, report: head }
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
return Buffer.byteLength(JSON.stringify(full)) <= STRUCTURED_MAX_BYTES ? full : capReport(report, true)
}
const fields = Object.fromEntries((STRUCTURED_FIELDS[tool] ?? []).filter((key) => key in metadata).map((key) => [key, metadata[key]]))
Expand Down
19 changes: 19 additions & 0 deletions packages/opencode/src/altimate/native/connections/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,25 @@ export async function dbtAdapterHasLineage(): Promise<boolean> {
}
}

/**
* The running dbt adapter's note when its last parse had errors and the manifest dbt wrote is missing
* what failed to parse (dbt Fusion), or undefined. Asking starts nothing: with no adapter running there
* is no parse to ask about.
*/
export async function dbtPartialManifestNote(): Promise<
{ message: string; errors: { file_path: string; message: string }[]; omitted_errors?: number } | undefined
> {
const adapter = dbtAdapter
if (!adapter) return undefined
try {
const { partialManifestNote } = await import("../../../../../dbt-tools/src/partial-manifest")
return partialManifestNote(adapter, dbtProjectRoot ?? undefined)
} catch {
// dbt-tools not available
return undefined
}
}

/**
* Stops the cached dbt adapter (its Python bridge and file watchers), for a server that is shutting
* down. An attempt still starting is stopped once it settles.
Expand Down
44 changes: 39 additions & 5 deletions packages/opencode/src/altimate/tools/dbt-lineage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { DbtLineageResult } from "../native/types"
import { loadRawManifest } from "../native/dbt/helpers"
import { lineageGraph } from "../native/dbt/graph"
import { projectRoot } from "../native/connections/registry"
import type { dbtPartialManifestNote } from "../native/connections/register"

/** The structured result of dbt-integration's `getModelLineage` (version 1), relayed as is. */
export type ModelLineage = {
Expand Down Expand Up @@ -38,7 +39,7 @@ export type ModelLineage = {

export const DbtLineageTool = Tool.define("dbt_lineage", {
description:
"Column-level lineage for a dbt model: its upstream models, seeds and sources, its downstream models, their columns, and the column edges between them. Pass `column` to trace one column. Where writes are allowed, uses the project's dbt integration (compiles on demand, no `dbt compile` needed; up to 3 hops each way) and returns the result as structured content; a read-only call, or one without the integration, reads the compiled SQL in the manifest and traces the model's own SQL.",
"Column-level lineage for a dbt model: its upstream models, seeds and sources, its downstream models, their columns, and the column edges between them. Pass `column` to trace one column. Where writes are allowed, uses the project's dbt integration (compiles on demand, no `dbt compile` needed; up to 3 hops each way) and returns the result as structured content; a read-only call, or one without the integration, reads the compiled SQL in the manifest and traces the model's own SQL. While the dbt integration is running and its last parse had errors, the answer starts with a note naming the files that failed to parse: dbt Fusion leaves them out of the manifest, so the graph is missing parts.",
parameters: z.object({
model: z
.string()
Expand Down Expand Up @@ -75,22 +76,30 @@ export const DbtLineageTool = Tool.define("dbt_lineage", {
const what = result.focus.column ? `${result.focus.name}.${result.focus.column}` : result.focus.name
// A lineage viewer also wants the manifest's graph: exposures and tests sit there, not here.
const graph = args.include_graph ? manifestGraph(args.manifest_path ?? (await defaultManifestPath(session)), result.focus.uniqueId) : undefined
const partial = await partialManifest(readOnly)
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
// A call cancelled while the answer was put together doesn't answer.
ctx.abort.throwIfAborted()
return {
title: `dbt Lineage: ${what} [${result.confidence}]`,
metadata: {
model_name: result.focus.name,
model_unique_id: result.focus.uniqueId,
confidence: result.confidence,
...(partial && { partial_manifest: partial }),
structuredContent: result,
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
...(graph?.graph && { graph: graph.graph }),
...(graph?.error && { graph_error: graph.error }),
},
output: formatModelLineage(result),
output: withPartialNote(partial, formatModelLineage(result)),
}
}
const notUsed = viaAdapter.reason ? `dbt integration not used: ${viaAdapter.reason}` : undefined
const manifestPath = args.manifest_path ?? (await defaultManifestPath(session))
ctx.abort.throwIfAborted()
// The manifest read here is the one the running adapter's last parse wrote only when it lies in that
// adapter's project.
const partial = await partialManifest(readOnly, manifestPath)
ctx.abort.throwIfAborted()
try {
const result = await Dispatcher.call("dbt.lineage", {
manifest_path: manifestPath,
Expand All @@ -111,25 +120,50 @@ export const DbtLineageTool = Tool.define("dbt_lineage", {
model_name: result.model_name,
model_unique_id: result.model_unique_id ?? null,
confidence: result.confidence,
...(partial && { partial_manifest: partial }),
confidence_factors: result.confidence_factors,
upstream: result.upstream ?? [],
columns: lineage?.column_dict ?? {},
edges: Array.isArray(lineage?.column_lineage) ? lineage.column_lineage : [],
...(result.graph && { graph: result.graph }),
},
output: formatDbtLineage(result),
output: withPartialNote(partial, formatDbtLineage(result)),
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return {
title: "dbt Lineage: ERROR",
metadata: { model_name: args.model, confidence: "unknown", error: msg },
output: `Failed: ${msg}${notUsed ? `\n(${notUsed})` : ""}`,
metadata: { model_name: args.model, confidence: "unknown", ...(partial && { partial_manifest: partial }), error: msg },
output: withPartialNote(partial, `Failed: ${msg}${notUsed ? `\n(${notUsed})` : ""}`),
}
}
},
})

type PartialManifestNote = NonNullable<Awaited<ReturnType<typeof dbtPartialManifestNote>>>

/**
* The running dbt adapter's note when its last parse had errors, so the manifest dbt wrote is missing
* what failed to parse. It answers for the adapter's own lineage, and for a manifest that exists in the
* adapter's project. A read-only call never asks: it never uses the adapter.
*/
async function partialManifest(readOnly: boolean, manifest?: string): Promise<PartialManifestNote | undefined> {
if (readOnly) return undefined
const { dbtPartialManifestNote } = await import("../native/connections/register")
const note = await dbtPartialManifestNote()
if (!note || manifest === undefined) return note
return fs.existsSync(manifest) && !(await manifestOutsideAdapterProject(manifest)) ? note : undefined
}

/** The answer led by the partial manifest's note: a long answer can be cut off on its way to the reader. */
function withPartialNote(note: PartialManifestNote | undefined, text: string): string {
if (!note) return text
const errors = note.errors.map((e) => ` ${e.file_path}: ${e.message.split("\n").join("\n ")}`)
const more = note.omitted_errors ?? 0
if (more > 0) errors.push(` … ${more} more error${more === 1 ? "" : "s"}`)
return [note.message, ...errors, "", text].join("\n")
}

/**
* Why a named manifest is not the adapter's project's, or undefined when it is: it must lie in that
* project's folder (links resolved) with no other dbt_project.yml between (a nested project or an
Expand Down
Loading
Loading