import { Dispatcher } from "../native" import { EngineCoerce } from "../native/engine-coerce" import { parseManifest } from "../native/dbt/manifest" import { findModel, loadRawManifest } from "../native/dbt/helpers" import { columnReach } from "../native/dbt/column-reach" import { isRootPackage } from "../native/dbt/graph" import { isExistenceError } from "../native/existence-error" import type { CheckResult, EquivalenceResult, GradeResult, ImpactResult, ReviewRunner } from "./orchestrate" import { buildReviewSchemaContext, type SchemaContext } from "./schema-context" import { logDetail, reportFailure, type FailureFacts } from "./failure" import type { MacroCard, ModelCard } from "./ai-context-card" import { maskForAi } from "./ai-review" import { Log } from "@/altimate/util/log" const log = Log.create({ service: "review", tag: "runner" }) /** * Production ReviewRunner backed by the native Dispatcher (the Rust core). * * Every method is defensive: on any error or unexpected shape it degrades to a * safe, lint-only result rather than throwing — a review must never crash CI. * That is the "degrade loudly" contract: when the manifest/schema is missing, * findings are emitted as unverified rather than silently dropped or fabricated. */ interface ManifestModel { unique_id: string name: string depends_on: string[] path?: string } interface CachedManifest { models: Map // unique_id -> model byName: Map children: Map // unique_id -> direct child unique_ids testDeps: Map> // model unique_id -> set of test unique_ids depending on it schemaContext?: SchemaContext // model/source columns for equivalence resolution ok: boolean } const NOT_FOUND_MESSAGE = /^(table|column) .+ not found/i /** Which relation part an engine existence error names, or undefined for any other validation error. */ function existenceKind(e: any): "table" | "column" | undefined { if (!isExistenceError(e) && !NOT_FOUND_MESSAGE.test(String(e?.message ?? ""))) return undefined const type = String(e?.kind?.type ?? "") if (String(e?.code) === "E002" || type === "ColumnNotFound") return "column" if (String(e?.code) === "E001" || type === "TableNotFound") return "table" return /^column/i.test(String(e?.message ?? "")) ? "column" : "table" } function asArray(v: unknown): T[] { return Array.isArray(v) ? (v as T[]) : [] } /** A repo-relative changed path names the manifest's project-relative `file` (same path, or under a project subdirectory). */ function pathMatches(path: string, file: unknown): boolean { return typeof file === "string" && !!file && (path === file || path.endsWith("/" + file)) } type IndexedNode = [string, any] /** Manifest lookups for the AI lane's context cards, built once per loaded manifest. */ interface CardIndex { raw: any project?: string /** Models, snapshots and seeds by `original_file_path`, and by name. */ byFile: Map byName: Map /** This project's models, snapshots and seeds by the yml file that patches them. */ patched: Map /** Models by directory (with trailing slash). */ modelsByDir: Map /** Node id → names of the models that depend on it. */ children: Map /** Node id → exposure names. */ exposures: Map /** Node id → lowercased column → attached test names. */ tests: Map> macrosByFile: Map macrosByName: Map /** `package\0base` → the base macro and its `__` variants. */ macrosByBase: Map /** Macro id → names of the models whose `depends_on.macros` include it. */ macroCallers: Map } const cardIndexes = new WeakMap() function push(map: Map, key: K, value: V) { const list = map.get(key) if (list) list.push(value) else map.set(key, [value]) } function dirOf(p: unknown): string | undefined { return typeof p === "string" ? p.slice(0, p.lastIndexOf("/") + 1) : undefined } function macroBase(name: string): string { const sep = name.indexOf("__") return sep > 0 ? name.slice(sep + 2) : name } /** Entries whose project-relative file the repo-relative `path` names, in manifest order. */ function byPath(map: Map, path: string): IndexedNode[] { const keys = [path] for (let i = path.indexOf("/"); i >= 0; i = path.indexOf("/", i + 1)) keys.push(path.slice(i + 1)) return keys.flatMap((k) => (k && pathMatches(path, k) ? (map.get(k) ?? []) : [])) } function cardIndex(raw: any): CardIndex | undefined { if (!raw || typeof raw !== "object") return undefined const cached = cardIndexes.get(raw) if (cached) return cached const project = raw.metadata?.project_name const idx: CardIndex = { raw, project, byFile: new Map(), byName: new Map(), patched: new Map(), modelsByDir: new Map(), children: new Map(), exposures: new Map(), tests: new Map(), macrosByFile: new Map(), macrosByName: new Map(), macrosByBase: new Map(), macroCallers: new Map(), } for (const entry of Object.entries(raw.nodes ?? {})) { const [id, n] = entry if (/^(model|snapshot|seed)\./.test(id)) { if (typeof n?.original_file_path === "string" && n.original_file_path) push(idx.byFile, n.original_file_path, entry) if (n?.name !== undefined) push(idx.byName, String(n.name), entry) if (typeof n?.patch_path === "string" && (!project || n.package_name === project)) push(idx.patched, n.patch_path.replace(/^[^:/]+:\/\//, ""), entry) } if (id.startsWith("model.")) { const dir = dirOf(n?.original_file_path) if (dir !== undefined) push(idx.modelsByDir, dir, entry) for (const p of new Set(asArray(n?.depends_on?.nodes))) push(idx.children, p, String(n.name)) for (const m of new Set(asArray(n?.depends_on?.macros))) push(idx.macroCallers, m, String(n.name)) } if (n?.resource_type === "test" && n.attached_node && n.column_name) { const testName = String(n.test_metadata?.name ?? n.name ?? "") if (!testName) continue const cols = idx.tests.get(n.attached_node) ?? new Map() push(cols, String(n.column_name).toLowerCase(), testName) idx.tests.set(n.attached_node, cols) } } for (const e of Object.values(raw.exposures ?? {})) { const name = String(e?.name ?? "") if (!name) continue for (const id of new Set(asArray(e?.depends_on?.nodes))) push(idx.exposures, id, name) } for (const entry of Object.entries(raw.macros ?? {})) { const [, m] = entry if (typeof m?.original_file_path === "string" && m.original_file_path) push(idx.macrosByFile, m.original_file_path, entry) if (m?.name !== undefined) { push(idx.macrosByName, String(m.name), entry) push(idx.macrosByBase, `${m.package_name}\0${macroBase(String(m.name))}`, entry) } } cardIndexes.set(raw, idx) return idx } /** * A model config value as card text. Scalars as they are; a config object * (`partition_by`, `cluster_by`, `unique_key`) by its known fields only * (`field`, `data_type`, `granularity`, numeric `range` bounds), never the * object itself. Strings are masked: the card goes to the AI provider. */ function cardConfigText(v: unknown): string | undefined { const scalar = (x: unknown): string | undefined => typeof x === "string" ? (x ? maskForAi(x) : undefined) : typeof x === "number" || typeof x === "boolean" ? String(x) : undefined if (v === undefined || v === null) return undefined if (Array.isArray(v)) { const items = v.map(scalar).filter((x): x is string => !!x) return items.length ? items.join(", ") : undefined } if (typeof v !== "object") return scalar(v) const o = v as Record const field = scalar(o.field) const extras = [scalar(o.data_type), scalar(o.granularity)].filter((x): x is string => !!x) const r = o.range as Record | undefined const num = (x: unknown) => (typeof x === "number" && Number.isFinite(x) ? x : undefined) const [start, end, step] = r && typeof r === "object" ? [num(r.start), num(r.end), num(r.interval)] : [] if (start !== undefined && end !== undefined) extras.push(`range ${start}–${end}${step !== undefined ? ` step ${step}` : ""}`) if (!field && !extras.length) return undefined return `${field ?? "(no field)"}${extras.length ? ` (${extras.join(", ")})` : ""}` } /** * Copy `primary_key` from `source` (manifest, which has dbt contract PKs) onto * matching tables in `target` (catalog, which has complete columns but no PK). * Non-destructive: only fills a PK where `target` lacks one. Enables fan-out * detection (L037) on the catalog-preferred path. */ function mergePrimaryKeys( target: Record | undefined, source: Record | undefined, ): Record | undefined { if (!target?.tables || !source?.tables) return target const out = { ...target, tables: { ...target.tables } } for (const [key, t] of Object.entries(out.tables)) { if (t?.primary_key?.length) continue const pk = source.tables[key]?.primary_key if (Array.isArray(pk) && pk.length) out.tables[key] = { ...t, primary_key: pk } } return out } /** Extract a column name from a PII-flavored check issue, best-effort. */ function piiColumnOf(issue: any): string | undefined { return issue?.column ?? issue?.target ?? issue?.name ?? undefined } /** * Map a core lint finding (by rule name / L0xx code) to a review category. * Core's `LintFinding` carries no category, so without this every AST finding * collapses to `sql_quality` — undersells correctness/join/contract risks. */ function lintCategory(rule: string, code: string): string | undefined { const r = `${rule} ${code}`.toLowerCase().replace(/_/g, "-") if (/pii|sensitive/.test(r)) return "pii_exposure" if (/cartesian|cross-join|comma-join|non-equi-join|or-in-join|fan.?out|l037/.test(r)) return "join_risk" if (/non-portable-type|l035/.test(r)) return "contract_violation" if (/division|divide|l032/.test(r)) return "sql_correctness" if (/overflow|l036/.test(r)) return "sql_correctness" if (/timezone-in-hash|hash-key|l038/.test(r)) return "sql_correctness" if (/non-deterministic|dedup|l039/.test(r)) return "sql_correctness" if (/monetary|float-cast|l040/.test(r)) return "sql_correctness" if (/coalesce|typed-coalesce|l041/.test(r)) return "sql_correctness" if (/case-sensitive|l042/.test(r)) return "sql_quality" if (/outer-join-filter|outer_join|left-to-inner|l043/.test(r)) return "join_risk" if (/null-propagating|null.?concat|l044/.test(r)) return "sql_correctness" if (/greatest|least|l045/.test(r)) return "sql_correctness" if (/distinct.?with.?window|l046/.test(r)) return "sql_correctness" if (/cast.?division|cast.?float|l048/.test(r)) return "sql_correctness" if (/clock.?in.?filter|now.?in.?filter|l049/.test(r)) return "idempotency" if (/cast.?in.?join|join-on-cast|l050/.test(r)) return "join_risk" if (/full.?outer|join.?without.?cond|l051|l052/.test(r)) return "join_risk" if (/null.?in.?in.?list|sum.?of.?ratio|l053|l054/.test(r)) return "sql_correctness" if (/not-null-comparison|null-comparison|not-in|nullable|l009/.test(r)) return "sql_correctness" if (/window.*partition|partition.*window/.test(r)) return "sql_correctness" if (/count-star|distinct/.test(r)) return "sql_correctness" if (/missing-where|update|delete/.test(r)) return "sql_correctness" if (/non-portable-function|l033/.test(r)) return "sql_quality" if (/select-star|l001|leading-wildcard|missing-partition-filter|large-in-list|non-sargable/.test(r)) return "warehouse_cost" return undefined // → sql_quality default downstream } /** Core's own SQL parser errors (altimate-core 0.9): `sql parser error: Expected: …`, * `Parse error at line 1, column 11: …`, `Syntax error: …` / `Syntax error at line …`, * `Failed to parse query …` / `Failed to parse MERGE statement`, `Unsupported statement …`, * `Tokenization error at line …` (an unterminated string or escape the dialect lacks). * Generic phrases (`expected 2 arguments, got 1`, `JSON Parse error: Unexpected token`) * are engine faults, not abstentions. */ const PARSE_FAILURE_RE = /\bsql parser error\b|\b(parse|syntax) error at line \d|\bsyntax error:|\bparser error:|\bfailed to parse (query\b|ddl\b|template sql\b|[a-z][a-z _/]* statement\b)|\bunsupported statement\b|\btokenization error\b/i export function isParseFailure(message: string): boolean { return PARSE_FAILURE_RE.test(message) } /** The engine could not parse the SQL: the check abstains on it. */ class CoreParseError extends Error {} /** `data.diff` found no warehouse or driver to run on: the lane skips, as before. * A driver package that is not installed reports `