From e251251359fa6da3d46df69fd8120f134c2c0f08 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Fri, 27 Nov 2026 23:28:20 +0800 Subject: [PATCH 1/3] fix(dbt_lineage): say when the graph comes from a partial dbt Fusion parse dbt Fusion writes a manifest without what failed to parse. While the dbt adapter runs and its last parse had errors, `dbt_lineage` answers and failures lead with a note naming each file and its error. A clean parse drops it; read-only calls are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvpmBim7nhBFZE99CaJ --- packages/dbt-tools/package.json | 2 +- packages/dbt-tools/src/adapter.ts | 7 +- packages/dbt-tools/src/partial-manifest.ts | 43 ++++ .../dbt-tools/test/partial-manifest.test.ts | 101 ++++++++ .../src/altimate/mcp-server/server.ts | 2 +- .../altimate/native/connections/register.ts | 19 ++ .../src/altimate/tools/dbt-lineage.ts | 46 +++- .../dbt-lineage-partial-manifest.test.ts | 227 ++++++++++++++++++ 8 files changed, 439 insertions(+), 8 deletions(-) create mode 100644 packages/dbt-tools/src/partial-manifest.ts create mode 100644 packages/dbt-tools/test/partial-manifest.test.ts create mode 100644 packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts diff --git a/packages/dbt-tools/package.json b/packages/dbt-tools/package.json index 583834bcf2..efb7a0d7be 100644 --- a/packages/dbt-tools/package.json +++ b/packages/dbt-tools/package.json @@ -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": { diff --git a/packages/dbt-tools/src/adapter.ts b/packages/dbt-tools/src/adapter.ts index 7a8c180c3f..27ba78f0c5 100644 --- a/packages/dbt-tools/src/adapter.ts +++ b/packages/dbt-tools/src/adapter.ts @@ -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, @@ -38,6 +39,7 @@ import type { DBTProjectIntegration, DBTDiagnosticData, DeferConfig, + ParsedManifest, RuntimePythonEnvironment, } from "@altimateai/dbt-integration" @@ -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) { diff --git a/packages/dbt-tools/src/partial-manifest.ts b/packages/dbt-tools/src/partial-manifest.ts new file mode 100644 index 0000000000..f01c467f00 --- /dev/null +++ b/packages/dbt-tools/src/partial-manifest.ts @@ -0,0 +1,43 @@ +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() + +/** 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 + +/** + * 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 + const inside = path.relative(projectRoot, file) + 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 })) + 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, + } +} diff --git a/packages/dbt-tools/test/partial-manifest.test.ts b/packages/dbt-tools/test/partial-manifest.test.ts new file mode 100644 index 0000000000..cba4ec75a0 --- /dev/null +++ b/packages/dbt-tools/test/partial-manifest.test.ts @@ -0,0 +1,101 @@ +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("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() + } + }) +}) diff --git a/packages/opencode/src/altimate/mcp-server/server.ts b/packages/opencode/src/altimate/mcp-server/server.ts index c153e8b921..6ae37bb28e 100644 --- a/packages/opencode/src/altimate/mcp-server/server.ts +++ b/packages/opencode/src/altimate/mcp-server/server.ts @@ -50,7 +50,7 @@ export async function serverInstructions(): Promise { // 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 = { - 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", diff --git a/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index 5fe852961a..2f50da9ce5 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -317,6 +317,25 @@ export async function dbtAdapterHasLineage(): Promise { } } +/** + * 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 }[] } | 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. diff --git a/packages/opencode/src/altimate/tools/dbt-lineage.ts b/packages/opencode/src/altimate/tools/dbt-lineage.ts index a83efb84ae..318bd2aa95 100644 --- a/packages/opencode/src/altimate/tools/dbt-lineage.ts +++ b/packages/opencode/src/altimate/tools/dbt-lineage.ts @@ -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 = { @@ -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() @@ -75,22 +76,28 @@ 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) 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, ...(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, @@ -111,25 +118,54 @@ 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>> + +/** + * 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 { + 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 +} + +/** Text errors listed under the partial manifest's note; the metadata carries them all. */ +const MAX_TEXT_PARSE_ERRORS = 10 + +/** 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 + .slice(0, MAX_TEXT_PARSE_ERRORS) + .map((e) => ` ${e.file_path}: ${e.message.split("\n").join("\n ")}`) + if (note.errors.length > MAX_TEXT_PARSE_ERRORS) errors.push(` … ${note.errors.length - MAX_TEXT_PARSE_ERRORS} more in the metadata`) + 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 diff --git a/packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts b/packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts new file mode 100644 index 0000000000..45f89284e6 --- /dev/null +++ b/packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts @@ -0,0 +1,227 @@ +// altimate_change - new file +// +// dbt_lineage's note when the running dbt adapter's last parse had errors (dbt Fusion writes a manifest +// without what failed to parse): its answers and its failures lead with the note while the mark is set, +// and drop it after a clean parse; a read-only call, a call with no adapter running and a manifest of +// another project carry none. The adapter is replaced through `dbtAdapterInternals`; the mark is +// recorded on it through dbt-tools' own recorder, the one its adapter's parse event feeds. +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from "bun:test" +import { mkdir, 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 { Dispatcher } from "@/altimate/native" +import { dbtAdapterInternals, getDbtAdapter, resetDbtAdapter } from "@/altimate/native/connections/register" +import { DbtLineageTool, type ModelLineage } from "@/altimate/tools/dbt-lineage" +import { structuredResult } from "@/altimate/mcp-server/server" +import { recordPartialManifest } from "../../../dbt-tools/src/partial-manifest" +import { initTool } from "./tool-fixture" + +const ctx: Tool.Context = { + sessionID: SessionID.make("ses_dbt_lineage_partial"), + messageID: MessageID.make("msg_dbt_lineage_partial"), + agent: "analyst", + abort: new AbortController().signal, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, +} + +const CUSTOMERS = "model.jaffle_shop.customers" +const TRACE: ModelLineage = { + version: 1, + project: "jaffle_shop", + dialect: "duckdb", + focus: { uniqueId: CUSTOMERS, name: "customers" }, + nodes: [{ uniqueId: CUSTOMERS, name: "customers", type: "model", direction: "focus", depth: 0, parents: [], columns: [] }], + columnLineage: [], + confidence: "high", + errors: [], + stats: { nodes: 1, edges: 0 }, +} +const MISSING_REF = "Ref 'stg_orderz' not found in project.\n --> models/customers.sql:9:19" +const NOTE = "This graph is missing parts because models/customers.sql failed to parse." + +let project: string +let other: string + +/** The manifest answer, as `dbt.lineage` returns it. */ +const manifestOnly = () => + spyOn(Dispatcher, "call").mockImplementation((async (method: string) => { + if (method !== "dbt.lineage") throw new Error(`unexpected ${method}`) + return { model_name: "customers", raw_lineage: {}, confidence: "low", confidence_factors: [] } + }) as any) + +/** Starts the fake adapter, as another tool's call would, and records its last parse. */ +async function runningAdapter(partial: boolean, lineage?: () => Promise) { + dbtAdapterInternals.create = async () => ({ + isInitialized: () => true, + dispose: async () => {}, + ...(lineage ? { getModelLineage: lineage } : {}), + }) + const adapter = await getDbtAdapter() + recordPartialManifest( + adapter, + (partial ? { partial: { errors: [{ filePath: path.join(project, "models", "customers.sql"), message: MISSING_REF }] } } : {}) as any, + ) + return adapter +} + +const lineage = async (args: Record, context: Tool.Context = ctx) => + (await initTool(DbtLineageTool)).execute({ model: "customers", ...args }, context) + +beforeAll(async () => { + project = await mkdtemp(path.join(os.tmpdir(), "dbt-lineage-partial-")) + await writeFile(path.join(project, "dbt_project.yml"), "name: jaffle_shop\n") + await mkdir(path.join(project, "target")) + await writeFile(path.join(project, "target", "manifest.json"), "{}") + other = await mkdtemp(path.join(os.tmpdir(), "dbt-lineage-partial-other-")) + await writeFile(path.join(other, "dbt_project.yml"), "name: other\n") + await mkdir(path.join(other, "target")) + await writeFile(path.join(other, "target", "manifest.json"), "{}") +}) + +afterAll(async () => { + await rm(project, { recursive: true, force: true }) + await rm(other, { recursive: true, force: true }) +}) + +beforeEach(() => { + resetDbtAdapter() + dbtAdapterInternals.readConfig = async () => ({ + projectRoot: project, + pythonPath: "python3", + dbtIntegration: "fusion", + queryLimit: 500, + }) + // As with the dbt-integration released today: dbt_lineage itself answers from the manifest. + dbtAdapterInternals.hasModelLineage = () => false +}) + +afterEach(() => { + resetDbtAdapter() + delete dbtAdapterInternals.readConfig + delete dbtAdapterInternals.create + delete dbtAdapterInternals.hasModelLineage +}) + +describe("dbt_lineage with the dbt adapter running", () => { + test("a manifest answer leads with the note while the last parse had errors", async () => { + await runningAdapter(true) + const call = manifestOnly() + try { + const result = await lineage({}) + expect(result.output.split("\n").slice(0, 4)).toEqual([ + NOTE, + " models/customers.sql: Ref 'stg_orderz' not found in project.", + " --> models/customers.sql:9:19", + "", + ]) + expect(result.metadata.partial_manifest).toEqual({ + message: NOTE, + errors: [{ file_path: "models/customers.sql", message: MISSING_REF }], + }) + } finally { + call.mockRestore() + } + }) + + test("a failure leads with the note too", async () => { + await runningAdapter(true) + const call = spyOn(Dispatcher, "call").mockImplementation((async () => { + throw new Error("manifest unreadable") + }) as any) + try { + const result = await lineage({}) + expect(result.title).toBe("dbt Lineage: ERROR") + expect(result.output.startsWith(`${NOTE}\n`)).toBe(true) + expect(result.output).toContain("Failed: manifest unreadable") + expect(result.metadata.partial_manifest?.message).toBe(NOTE) + } finally { + call.mockRestore() + } + }) + + test("the adapter's own lineage leads with the note", async () => { + dbtAdapterInternals.hasModelLineage = () => true + await runningAdapter(true, async () => TRACE) + const result = await lineage({}) + expect(result.metadata.structuredContent).toEqual(TRACE) + expect(result.output.startsWith(`${NOTE}\n`)).toBe(true) + expect(result.metadata.partial_manifest?.message).toBe(NOTE) + }) + + test("the note goes after a clean parse", async () => { + const adapter = await runningAdapter(true) + recordPartialManifest(adapter, {} as any) + const call = manifestOnly() + try { + const result = await lineage({}) + expect(result.output).not.toContain("missing parts") + expect(result.metadata.partial_manifest).toBeUndefined() + } finally { + call.mockRestore() + } + }) + + test("a manifest of another dbt project carries no note", async () => { + await runningAdapter(true) + const call = manifestOnly() + try { + const result = await lineage({ manifest_path: path.join(other, "target", "manifest.json") }) + expect(result.output).not.toContain("missing parts") + expect(result.metadata.partial_manifest).toBeUndefined() + } finally { + call.mockRestore() + } + }) + + test("a read-only call carries no note", async () => { + await runningAdapter(true) + const call = manifestOnly() + try { + for (const context of [{ ...ctx, extra: { forceReadOnly: true } }, { ...ctx, agent: "plan" }]) { + const result = await lineage({}, context) + expect(result.output).not.toContain("missing parts") + expect(result.metadata.partial_manifest).toBeUndefined() + } + } finally { + call.mockRestore() + } + }) +}) + +describe("dbt_lineage with no dbt adapter running", () => { + test("carries no note and starts none", async () => { + let created = 0 + dbtAdapterInternals.create = async () => { + created += 1 + return { isInitialized: () => true, dispose: async () => {} } + } + const call = manifestOnly() + try { + const result = await lineage({}) + expect(created).toBe(0) + expect(result.metadata.partial_manifest).toBeUndefined() + } finally { + call.mockRestore() + } + }) +}) + +describe("the MCP server's structured result", () => { + test("carries the note", async () => { + await runningAdapter(true) + const call = manifestOnly() + try { + const result = await lineage({}) + const structured = structuredResult("dbt_lineage", result.metadata, result.output) + expect(structured.partial_manifest).toEqual(result.metadata.partial_manifest) + expect(String(structured.report).startsWith(NOTE)).toBe(true) + } finally { + call.mockRestore() + } + }) +}) From 7cf3b17326b8483f9db16b3ad98fdef879244e1c Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Sat, 28 Nov 2026 20:26:34 +0800 Subject: [PATCH 2/3] fix(opencode): keep `partial_manifest` in the MCP result of adapter lineage `structuredResult` hands the adapter's own lineage over whole, so the partial-parse mark beside it was dropped. It now goes with it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvpmBim7nhBFZE99CaJ --- packages/opencode/src/altimate/mcp-server/server.ts | 4 +++- .../test/altimate/dbt-lineage-partial-manifest.test.ts | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/mcp-server/server.ts b/packages/opencode/src/altimate/mcp-server/server.ts index 6ae37bb28e..80de33c29a 100644 --- a/packages/opencode/src/altimate/mcp-server/server.ts +++ b/packages/opencode/src/altimate/mcp-server/server.ts @@ -93,7 +93,9 @@ export function structuredResult(tool: string, metadata: Record 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), 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 } : {} + const full = { ...(own as Record), ...mark, report: head } 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]])) diff --git a/packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts b/packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts index 45f89284e6..acf0b80838 100644 --- a/packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts +++ b/packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts @@ -224,4 +224,14 @@ describe("the MCP server's structured result", () => { call.mockRestore() } }) + + test("carries the note beside the adapter's own lineage", async () => { + dbtAdapterInternals.hasModelLineage = () => true + await runningAdapter(true, async () => TRACE) + const result = await lineage({}) + const structured = structuredResult("dbt_lineage", result.metadata, result.output) + expect(structured).toMatchObject(TRACE) + expect(structured.partial_manifest).toEqual(result.metadata.partial_manifest) + expect(String(structured.report).startsWith(NOTE)).toBe(true) + }) }) From 8f07229481548ba6c27e3d9e094fe79db4c01088 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Mon, 30 Nov 2026 12:53:23 +0800 Subject: [PATCH 3/3] fix(opencode): bound the `partial_manifest` errors and stop a cancelled `dbt_lineage` The note carries the first 10 errors and counts the rest in `omitted_errors`, so a parse failing in every model can't swell each answer. The adapter path checks for a cancel after reading the note. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvpmBim7nhBFZE99CaJ --- packages/dbt-tools/src/partial-manifest.ts | 5 ++- .../dbt-tools/test/partial-manifest.test.ts | 12 ++++++ .../altimate/native/connections/register.ts | 2 +- .../src/altimate/tools/dbt-lineage.ts | 12 +++--- .../dbt-lineage-partial-manifest.test.ts | 38 +++++++++++++++++++ 5 files changed, 60 insertions(+), 9 deletions(-) diff --git a/packages/dbt-tools/src/partial-manifest.ts b/packages/dbt-tools/src/partial-manifest.ts index f01c467f00..2ccf3457c6 100644 --- a/packages/dbt-tools/src/partial-manifest.ts +++ b/packages/dbt-tools/src/partial-manifest.ts @@ -12,6 +12,8 @@ export function recordPartialManifest(adapter: object, parsed: ParsedManifest): /** 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. @@ -38,6 +40,7 @@ export function partialManifestNote(adapter: object, projectRoot?: string) { : named[0] return { message: `This graph is missing parts because ${list} failed to parse.`, - errors, + errors: errors.slice(0, KEPT_ERRORS), + ...(errors.length > KEPT_ERRORS && { omitted_errors: errors.length - KEPT_ERRORS }), } } diff --git a/packages/dbt-tools/test/partial-manifest.test.ts b/packages/dbt-tools/test/partial-manifest.test.ts index cba4ec75a0..d27bdc42bd 100644 --- a/packages/dbt-tools/test/partial-manifest.test.ts +++ b/packages/dbt-tools/test/partial-manifest.test.ts @@ -64,6 +64,18 @@ describe("the partial manifest note", () => { 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 })) diff --git a/packages/opencode/src/altimate/native/connections/register.ts b/packages/opencode/src/altimate/native/connections/register.ts index 2f50da9ce5..8dba2f5a8a 100644 --- a/packages/opencode/src/altimate/native/connections/register.ts +++ b/packages/opencode/src/altimate/native/connections/register.ts @@ -323,7 +323,7 @@ export async function dbtAdapterHasLineage(): Promise { * is no parse to ask about. */ export async function dbtPartialManifestNote(): Promise< - { message: string; errors: { file_path: string; message: string }[] } | undefined + { message: string; errors: { file_path: string; message: string }[]; omitted_errors?: number } | undefined > { const adapter = dbtAdapter if (!adapter) return undefined diff --git a/packages/opencode/src/altimate/tools/dbt-lineage.ts b/packages/opencode/src/altimate/tools/dbt-lineage.ts index 318bd2aa95..08b095c491 100644 --- a/packages/opencode/src/altimate/tools/dbt-lineage.ts +++ b/packages/opencode/src/altimate/tools/dbt-lineage.ts @@ -77,6 +77,8 @@ export const DbtLineageTool = Tool.define("dbt_lineage", { // 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) + // A call cancelled while the answer was put together doesn't answer. + ctx.abort.throwIfAborted() return { title: `dbt Lineage: ${what} [${result.confidence}]`, metadata: { @@ -153,16 +155,12 @@ async function partialManifest(readOnly: boolean, manifest?: string): Promise ` ${e.file_path}: ${e.message.split("\n").join("\n ")}`) - if (note.errors.length > MAX_TEXT_PARSE_ERRORS) errors.push(` … ${note.errors.length - MAX_TEXT_PARSE_ERRORS} more in the metadata`) + 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") } diff --git a/packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts b/packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts index acf0b80838..9ef047c68e 100644 --- a/packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts +++ b/packages/opencode/test/altimate/dbt-lineage-partial-manifest.test.ts @@ -153,6 +153,44 @@ describe("dbt_lineage with the dbt adapter running", () => { expect(result.metadata.partial_manifest?.message).toBe(NOTE) }) + test("the note lists the errors it carries and counts the rest", async () => { + const adapter = await runningAdapter(false) + const errors = Array.from({ length: 12 }, (_, i) => ({ + filePath: path.join(project, "models", `m${i}.sql`), + message: `error ${i}`, + })) + recordPartialManifest(adapter, { partial: { errors } } as any) + const call = manifestOnly() + try { + const result = await lineage({}) + const lines = result.output.split("\n") + expect(lines.slice(1, 12)).toEqual([ + ...errors.slice(0, 10).map((_, i) => ` models/m${i}.sql: error ${i}`), + " … 2 more errors", + ]) + expect(result.metadata.partial_manifest?.errors).toHaveLength(10) + expect(result.metadata.partial_manifest?.omitted_errors).toBe(2) + } finally { + call.mockRestore() + } + }) + + test("a cancel while the note is read stops the adapter's answer", async () => { + dbtAdapterInternals.hasModelLineage = () => true + const adapter = await runningAdapter(false, async () => TRACE) + const cancel = new AbortController() + // The note reads the failed file's path after the lineage came back: the call is cancelled then. + const error = { + get filePath() { + cancel.abort() + return path.join(project, "models", "customers.sql") + }, + message: MISSING_REF, + } + recordPartialManifest(adapter, { partial: { errors: [error] } } as any) + await expect(lineage({}, { ...ctx, abort: cancel.signal })).rejects.toThrow() + }) + test("the note goes after a clean parse", async () => { const adapter = await runningAdapter(true) recordPartialManifest(adapter, {} as any)