import path from "node:path" import YAML from "yaml" import { type Finding, type ReviewCategory, type Severity, ReviewCategory as ReviewCategoryEnum, makeFinding, dedupe, mergeRepeats, findingOrigin, repeatGroupId, publicEvidence, SEVERITY_ORDER, ruleId, } from "./finding" import { type ChangedFile, type DbtProjectLayout, type DiffLine, type DiffRow, type NotReviewed, classifyDbtFile, relativeToRoot, hasOldSide, isExcludedPath, looksLikeSourceYml, partitionChangedFiles, walkDiffLines, walkDiffRows, } from "./diff-filter" export { type DiffLine, walkDiffLines } from "./diff-filter" import { classifyPR, compilePathTokenResolver, knownReviewers, TIER_LANES } from "./risk-tier" import { type Rubric, exclusionReason, clampSeverity } from "./rubric" import { type ReviewConfig } from "./config" import { type ReviewMode, type ReviewScope, type VerdictEnvelope, type FailureCategory, buildEnvelope, computeIdealVerdict, signEnvelope, verdictEligible, } from "./verdict" import { detectMacroPatterns, detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" import { type FinalOutputs, type RawReach, type RelationPrefixes, type SelectItem, type SelectItemColumn, finalOutputs, rawReach, explicitProjection, rawRelationsMatch, type RelationMatch, lineageCovered, refCovered, ROOT_SCOPE, SILENT_JINJA_TAG, normalizeSelectLine, selectItems, selectSources, parenBody, } from "./rule-catalog" import { listKey, listLabel, listMirrorsModel, type ConsumerColumnList, type ConsumerListLoad } from "./consumer-lists" import { detectUnitTestFixtures } from "./unit-tests" import { detectTestAdequacy, detectThresholdLoosening, testKeys } from "./test-adequacy" import { incrementalFindings, inlineConfig, snapshotFindings, snapshotYmlFindings } from "./incremental-semantics" import { type AiContextFile, type AiLaneStatus, type AiReviewFile, type AiReviewInput, type AiReviewResult, aiInputBudget, aiLaneTimeoutMs, AI_ONLY_KINDS, holdsCredentials, maskOptInFile, newSideDiff, LANE_DEADLINE_REASON, maskForAi, mayHoldCredentials, selectAiFiles, selectAiFilesByQuota, untilAborted, } from "./ai-review" import { overrideTier, ruleTier } from "./rule-tiers" import { type RulesOff, hiddenByRulesOff } from "./rules-off" import { type RuleVerifierStatus, type RuleVerifyInput, skippedRuleVerifier } from "./ai-verify-rules" import { hasInternalFailure, reportFailure } from "./failure" import { dbtProjectFindings, dispatchKwargFindings, dispatchVariants, docRefFindings, isPackageProject, jinjaFindings, joinTargets, type JoinTarget, missingRefFindings, modelConfigFindings, packageLockFindings, packagesFindings, partitionColumns, projectIncrementalStrategy, quickstartModelFindings, testWindowFindings, testsOnNullColumns, type DocLookup, isDbtProjectYaml, yamlParseFindings, } from "./project-rules" import { codeBlock, codeSpan } from "./format" import { capabilityFor } from "./adapter-capabilities" /** Where an unusable `consumerColumnLists` entry is reported. */ const REVIEW_POLICY_PATH = ".altimate/review.yml" import { type AiVerifyEvidence, inertEvidence } from "./ai-verify" import { type MacroCard, type ModelCard, attachContextCards } from "./ai-context-card" import { type AiSwitches, switchOn } from "./ai-switches" import { isAiOtherFile, isCiOrEnvFile } from "./ai-other-files" import { AI_PYTHON_KIND, isAiPythonFile } from "./ai-python-files" import { type Convention, type ConventionRecord, conventionTexts, isConventionFile } from "./conventions" import type { ColumnReach } from "../native/dbt/column-reach" const AI_SUPPORTING_KINDS = new Set(["macro", "test", "snapshot", "schema_yml", "source_yml", "seed", "project_config"]) /** * The deterministic review recipe. * * The LLM (when present) is a coordinator that turns engine output into prose — * but the findings and the verdict are produced HERE, mechanically, from * deterministic engine calls behind the `ReviewRunner` interface. That is the * defensible core: a generic reviewer guesses; this proves. * * `ReviewRunner` is intentionally high-level so the orchestrator is pure and * unit-testable. Production backs it with the native Dispatcher (see * tools/dbt-pr-review.ts); tests pass a fake. */ /** * Maps a regex-layer check code → a matcher for the equivalent core AST rule. * A regex twin is dropped ONLY when core lint ACTUALLY emitted the matching * finding for that file — not merely because core ran. This is the safe form: * if core's AST rule misses a specific instance (e.g. `= null` it doesn't flag), * the regex finding survives instead of falling through the crack. */ const CORE_AST_COVERED: Record = { "select-star": /select.?star|l001/, "cross-join": /cartesian|cross.?join/, "comma-join": /cartesian|cross.?join/, "constant-join": /cartesian|cross.?join|join.?without.?cond|l052/, "not-in-nullable": /not.?in|nullable/, "window-no-partition": /window.*partition/, "equals-null": /null.?comparison/, "leading-wildcard": /leading.?wildcard|like.?wildcard/, "division-no-guard": /division|divide/, "left-to-inner": /outer.?join|left.?to.?inner|l043/, "null-concat": /null.?propagat|null.?concat|l044/, "greatest-least-null": /greatest|least|l045/, "distinct-with-window": /distinct.?with.?window|l046/, "cast-float-to-int": /cast.?division|cast.?float|l048/, "now-in-filter": /clock.?in.?filter|l049/, "join-on-cast": /cast.?in.?join|join-on-cast|l050/, "full-outer-join": /full.?outer|l051/, "join-no-on": /join.?without.?cond|l052/, "in-with-null": /null.?in.?in.?list|l053/, "sum-of-ratio": /sum.?of.?ratio|l054/, "timezone-naive-now": /clock.?in.?filter|l049/, } /** * Extract function names a finding references in call form `NAME(` or backticked * `NAME`, lowercased — used to reconcile the regex portability catalog against * core's AST L033 (NonPortableFunction). Advice functions (coalesce, etc.) are * harmless: core never flags ANSI functions, so they can't cause suppression. */ function fnTokensOf(text: string): string[] { const out: string[] = [] for (const m of text.matchAll(/`([A-Za-z_][A-Za-z0-9_.]*)`|\b([A-Za-z_][A-Za-z0-9_.]+)\s*\(/g)) { out.push((m[1] ?? m[2]).toLowerCase()) } return out } /** Impact-analysis result, normalized. */ export interface ImpactResult { hasManifest: boolean /** SAFE | LOW | MEDIUM | HIGH | BREAKING (from the DAG walk). */ severity: "SAFE" | "LOW" | "MEDIUM" | "HIGH" | "BREAKING" | "UNKNOWN" directCount: number transitiveCount: number testCount: number } /** Equivalence result, normalized with a first-class undecidable state. */ export interface EquivalenceResult { /** False when the engine could not decide (no schema / undecidable). */ decided: boolean equivalent?: boolean differences?: string[] confidence?: "high" | "medium" | "low" } export interface GradeResult { grade?: string // A–F issues?: Array<{ rule: string; message: string; line?: number; severity?: string }> } export interface CheckResult { issues?: Array<{ rule: string; message: string; line?: number; severity?: string; category?: string }> piiColumns?: string[] /** Core's PII pass could not parse the SQL: `piiColumns` is unknown, not empty. */ piiAbstained?: boolean /** * True when the native core lint actually ran (parsed the SQL via the AST), * even if it found zero issues. Distinguishes "clean SQL" from "core * unavailable / degraded". When true, the orchestrator defers structural SQL * checks to the AST lint and suppresses the fragile regex twins. */ ran?: boolean /** The check failed in the engine (not a parse abstention): the failure is an engine error. */ faulted?: boolean /** A relation the SQL reads has no documented columns (manifest-derived schema): its column references were not verified. */ unresolvedColumns?: boolean } /** High-level engine surface the orchestrator depends on. */ export interface ReviewRunner { /** True when the configured dbt manifest loaded, independent of model lookup. */ manifestAvailable?(): Promise impact(model: string): Promise grade(sql: string, dialect: string): Promise check(sql: string, dialect: string, baseSql?: string): Promise equivalence(oldSql: string, newSql: string, dialect?: string): Promise /** `abstained`: the PII pass could not analyse the SQL, so `columns` is unknown. */ /** `abstained`: the PII columns are unknown; `faulted`: because the engine failed (not a parse abstention). */ detectPii(sql: string, dialect: string): Promise<{ columns: string[]; abstained?: boolean; faulted?: boolean }> /** Engine calls that threw during this review (method, first reason, count). */ failures?(): Array<{ method: string; reason: string; count: number; category?: FailureCategory }> /** Checks that could not parse their input, in call order (method per call, and * the SQL it was asked about when the call is not made inside one file's lanes). */ abstentions?(): Array<{ method: string; sql?: string[] }> /** * Lexical scan (reserved-word aliases + dialect operators) — the curated lists * and detection live in the compiled core; this passes raw added diff lines. * Optional so the orchestrator stays unit-testable with a fake runner. */ lexicalScan?(addedLines: string[]): Promise> /** Direct downstream models (name + file path) of a model, from the manifest DAG. */ downstreamModels?(model: string): Promise> /** Downstream models and exposures that read one column of a model (manifest + compiled SQL). */ columnReach?(model: string, column: string, dialect?: string): Promise /** * Direct dbt parents of the nodes defined in these files (project-relative * paths): models, seeds and snapshots by file, sources with their declared * columns, and the project's own macros. A changed yml maps to the models its * tests cover. Paths of parents are project-relative too. */ graphParents?(paths: string[]): Promise> /** * Consumers of a model that dbt refs don't show: exposures that depend on it, * and whether it has an enforced contract (with the declared columns). * Undefined when the model is not in the manifest. */ modelConsumers?( model: string, /** The model's repository-relative file, to find a versioned model (`fct_orders_v2.sql`). */ file?: string, ): Promise< | { exposures: Array<{ name: string; type?: string }> contractEnforced: boolean contractColumns: string[] /** The manifest node's own name and version (`fct_orders`, `2`). */ name?: string version?: string /** Several manifest nodes fit the file equally: none was picked. */ ambiguous?: boolean } | undefined > /** A model's or snapshot's merged dbt `config` from the manifest (project + yml + inline). */ modelConfig?(name: string): Promise | undefined> /** Manifest facts about a model, snapshot or seed for the AI lane's context card: the * node defined in `path` in this project, else by name (this project first). Never throws. */ modelCard?(name: string, opts?: { path?: string }): Promise /** Models, snapshots and seeds of this project whose yml (`patch_path`) is `path`. Never throws. */ patchedModels?(path: string): Promise /** A macro's callers and adapter variants: a macro defined in `path` in this project * (the one named `name` first), else by name (this project first). Never throws. */ macroCard?(name: string, opts?: { path?: string; changedModels?: string[] }): Promise /** Column sets the model's `unique` / `unique_combination_of_columns` tests declare unique. */ declaredUniqueKeys?(model: string): Promise /** Column-lineage edges for a query: source `"table"."col"` → target output column. */ columnLineage?(sql: string, dialect: string): Promise> /** Classify a set of column names as PII (Email/SSN/…) with confidence + masking. */ classifyPii?( columns: string[], ): Promise> /** Structural complexity (window/subquery/large plan) from core `metadata` — a tiering signal. */ isComplex?(sql: string, dialect?: string): Promise /** Extract a model's grain key (final GROUP BY + dedup PARTITION BY) from its SQL. */ grain?(sql: string): Promise<{ group_by: string[]; dedup_partition: string[] }> /** Declared primary/unique key of a model, from contract or unique test (manifest). */ declaredPrimaryKey?(model: string): Promise /** Per-upstream WHERE-filter columns of a model's SQL (cross-model consistency). */ sourceFilters?(sql: string): Promise> /** dbt config/Jinja lint over RAW model SQL (parses `{{ config() }}` in core). */ dbtConfigLint?( rawSql: string, oldRawSql?: string, ): Promise> /** AST base-vs-head structural diff — the `*_change` rules (parses both versions in core). */ structuralDiff?( baseSql: string, headSql: string, ): Promise> /** * Run a base-vs-head DATA diff (core DataParity over a warehouse connection): * actual row/value deltas. Returns null when no warehouse/driver is configured * (the lane then skips — data-diff is a CI capability, not always present) or * when the diff failed (also reported through `failures`). */ dataDiff?( baseSql: string, headSql: string, keyColumns: string[], /** Warehouse connection name to diff against; omit for the default. */ warehouse?: string, ): Promise<{ rowsOnlyInBase?: number; rowsOnlyInHead?: number; rowsChanged?: number; summary?: string } | null> } export interface OrchestrateInput { changedFiles: ChangedFile[] config: ReviewConfig rubric: Rubric mode: ReviewMode runner: ReviewRunner /** Resolve RAW model contents (Jinja) from the working tree / git refs. */ getContent?: (file: string, side: "old" | "new") => Promise /** Resolve dbt-COMPILED SQL (rendered) for the engine lanes; undefined when * no compiled artifact exists. The dbt-patterns lane always uses raw. */ getCompiled?: (file: string, side: "old" | "new") => Promise /** True for a model the manifest marks disabled: dbt does not compile it, so * its missing head SQL does not make the run incomplete. */ isDisabledModel?: (file: string) => boolean generatedAt?: string manifestHash?: string coreVersion?: string modelVersion?: string /** altimate-code CLI release recorded in engine.cliVersion for audit reconstruction. */ cliVersion?: string /** * Optional LLM reviewer lane. Injected (not imported) so the orchestrator * stays pure/unit-testable: production wires `runAiReview` (harness LLM); * tests pass a fake or omit it (the lane is then skipped). Receives the * deterministic findings as grounding and returns ADVISORY findings only. */ aiReview?: (input: AiReviewInput) => Promise /** Why the AI lane is off when `aiReview` is not injected (shown in the comment). */ aiDisabledReason?: string /** Explicit `provider/model` for the AI lane. */ aiModel?: string /** Send the changed files' unchanged dbt parents to the AI lane as context. */ aiGraphContext?: boolean /** Attach a dbt manifest context card to each AI file (the `contextCard` switch; needs a manifest). */ aiContextCard?: boolean /** Give the AI lane what the dbt-grounded verifier reads (the `verify` switch). */ aiVerify?: boolean /** Tracked files at head (repo-relative), for the verifier's project search. */ projectFiles?: AiVerifyEvidence["projectFiles"] /** Fixed-string search of given files at head, for the verifier. */ grepFiles?: AiVerifyEvidence["grepFiles"] /** Working-tree reviews: whether a path is a symlink (the verifier never reads one). */ isSymlink?: AiVerifyEvidence["isSymlink"] /** Upper bound for the AI lane; past it the review continues without it. Defaults to the lane deadline plus a minute. */ aiLaneTimeoutMs?: number /** The review's resolved AI switches (ai-switches.ts); without them each switch reads its env variable. */ aiSwitches?: Partial /** Changed files outside the dbt project, for the AI lane only (`pythonFiles` switch, off by default). */ aiOutsideFiles?: ChangedFile[] /** The review's repository root (`--cwd`'s git root); env-named files must be outside it. */ reviewDir?: string /** Team conventions from the base commit (`conventions` switch), for the AI finder. */ conventions?: Convention[] /** The envelope record of the convention files: those loaded and those skipped (no text). */ conventionRecords?: ConventionRecord[] /** Rule ids not posted on files the AI lane reviewed (rules-off.ts); undefined hides none. */ rulesOff?: RulesOff /** The rule verifier (`verifyRules` switch; ai-verify-rules.ts). Injected like `aiReview`; it * runs after the AI lane answered, within the lane's deadline, and never throws past it. */ aiRuleVerify?: (input: RuleVerifyInput, deps: { abort: AbortSignal }) => Promise /** Every file the PR changes (repo-relative), including files outside the dbt project: paths * for the AI's test-gap list and the verifier's test files; filtered by exclude globs and credential names. */ prFiles?: string[] /** PR metadata passed to the AI reviewer for intent checking. */ prTitle?: string prBody?: string /** G1 — attach the classifier's reason list to the envelope. */ explainTier?: boolean /** G2 — override the classifier's tier decision. Envelope carries tierForced:true. */ forceTier?: "trivial" | "lite" | "full" /** Manifest was stale relative to change-affecting files (see run.ts::detectStaleManifest). */ staleManifest?: boolean /** The dbt project's directories from dbt_project.yml (custom model-paths). */ layout?: DbtProjectLayout /** Names `ref()` can resolve to at head (repo resources + installed packages); undefined = unknown. */ resourceNames?: () => Promise | undefined> /** What the review covered: base resolution and files left out of scope. */ scope?: Omit & { notReviewed?: NotReviewed[] } /** Drop the regex catalog's cross-engine portability findings (single known engine). */ suppressPortability?: boolean /** Other adapters the project supports (from its adapter-specific macros); portability advice is kept when any of them lacks the construct. */ portabilityTargets?: string[] /** The dialect came from config or the manifest, not the default guess. */ dialectKnown?: boolean /** Opt-in explicit column lists outside dbt, with the lookups that failed * and the unusable patterns (see consumer-lists.ts). */ consumerLists?: ConsumerListLoad /** Which review policy was applied (see config.ts loadReviewPolicy). */ policy?: VerdictEnvelope["policy"] } /** A catalog finding tagged as cross-engine portability advice. */ export function isCatalogPortability(f: Finding): boolean { return f.evidence?.tool === "rule-catalog" && (f.evidence.result as { portability?: boolean })?.portability === true } /** * Portability advice that is noise for a project on `dialect`: dropped only * when the rule names `dialect`, and each of the project's other supported * adapters (`targets`), among the engines that support the construct. * Otherwise (an engine not listed, or support never established) it may be an * error on one of the project's engines and is kept. */ export function isSuppressiblePortability(f: Finding, dialect: string, targets: string[] = []): boolean { if (!isCatalogPortability(f)) return false const worksOn = (f.evidence?.result as { worksOn?: string[] })?.worksOn return !!worksOn && [dialect.toLowerCase(), ...targets].every((d) => worksOn.includes(d)) } /** Head-side line numbers of a unified diff: `commentable` holds the lines * GitHub accepts for an inline comment (added and context lines inside a * hunk); `added` holds only the `+` lines the PR introduced. */ export function scanDiffLines(diff: string | undefined): { commentable: Set; added: Set } { const commentable = new Set() const added = new Set() for (const { line, kind } of walkDiffLines(diff)) { commentable.add(line) if (kind === "+") added.add(line) } return { commentable, added } } /** Head-side line numbers each changed file's diff adds. A newly added file * counts every line of its diff as added. */ export function addedLinesByFile(files: ChangedFile[]): Map> { return new Map( files.map((f) => { const { commentable, added } = scanDiffLines(f.diff) return [f.path, f.status === "added" ? commentable : added] }), ) } /** * Keep a finding's `suggestion` only when GitHub can apply it as written: every * line of the range was added by the PR, the head file has those lines, and * the replacement changes them. Otherwise the replacement moves into the body * as a plain "Suggested fix" block. */ export async function validateSuggestions( findings: Finding[], getContent: OrchestrateInput["getContent"], added: Map>, ): Promise { const heads = new Map>() const head = (file: string) => { if (!heads.has(file)) heads.set(file, getContent?.(file, "new").catch(() => undefined) ?? Promise.resolve(undefined)) return heads.get(file)! } return Promise.all( findings.map(async (f) => { const s = f.suggestion if (!s) return f const lines = added.get(f.file) const range = Array.from({ length: s.endLine - s.startLine + 1 }, (_, i) => s.startLine + i) const inDiff = s.startLine <= s.endLine && !!lines && range.every((n) => lines.has(n)) const text = inDiff ? await head(f.file) : undefined const rows = text?.split("\n") const current = rows && rows.length >= s.endLine ? rows.slice(s.startLine - 1, s.endLine).join("\n") : undefined if (current !== undefined && current !== s.replacement) return f const { suggestion: _drop, ...rest } = f return { ...rest, body: `${f.body}\n\nSuggested fix:\n${codeBlock("sql", s.replacement)}` } as Finding }), ) } /** Shortest evidence text matched as a substring of an added line. */ const EVIDENCE_SUBSTRING_MIN = 12 /** * Give a line-less finding the diff line its rule matched. The rule records * the matched source text in `evidence.result.line`; this finds it in the * file's diff: the first added line with the same trimmed text, else the first * context line with it (which `markPreExisting` then marks pre-existing), else the * first added line containing it when it is long enough to be specific. A * finding whose text isn't in the diff keeps no line and stays in the summary. */ export function anchorByEvidence(findings: Finding[], files: ChangedFile[]): Finding[] { const diffs = new Map(files.map((f) => [f.path, f.diff])) const walked = new Map() return findings.map((f) => { if (typeof f.startLine === "number") return f const raw = (f.evidence?.result as { line?: unknown } | undefined)?.line const want = typeof raw === "string" ? raw.trim() : "" if (!want || !diffs.has(f.file)) return f if (!walked.has(f.file)) walked.set(f.file, [...walkDiffLines(diffs.get(f.file))]) const rows = walked.get(f.file)! const hit = rows.find((r) => r.kind === "+" && r.text.trim() === want) ?? rows.find((r) => r.kind === " " && r.text.trim() === want) ?? (want.length >= EVIDENCE_SUBSTRING_MIN ? rows.find((r) => r.kind === "+" && r.text.includes(want)) : undefined) return hit ? { ...f, startLine: hit.line, endLine: hit.line } : f }) } const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") /** The head line nearest a removed row: the `+` row at the same position in * its change block, else the nearest `+` row in its hunk, else (a pure * deletion) the context row after it, else the one before it. */ function headSiteOfRemoved(rows: DiffRow[], i: number): number | undefined { const hunk = rows[i].hunk let lo = i let hi = i while (lo > 0 && rows[lo - 1].hunk === hunk && rows[lo - 1].kind !== " ") lo-- while (hi < rows.length - 1 && rows[hi + 1].hunk === hunk && rows[hi + 1].kind !== " ") hi++ const block = rows.slice(lo, hi + 1) const plus = block.filter((r) => r.kind === "+") if (plus.length) { const k = block.filter((r) => r.kind === "-").indexOf(rows[i]) return plus[Math.min(k, plus.length - 1)].line } const inHunk = rows.map((r, j) => ({ r, j })).filter(({ r }) => r.hunk === hunk) const nearest = (kind: DiffRow["kind"]) => inHunk.filter(({ r }) => r.kind === kind).sort((a, b) => Math.abs(a.j - i) - Math.abs(b.j - i))[0]?.r const added = nearest("+") if (added) return added.line return ( inHunk.find(({ r, j }) => j > i && r.kind === " ")?.r.line ?? inHunk.filter(({ r, j }) => j < i && r.kind === " ").at(-1)?.r.line ) } /** * Anchor for a finding about removed output columns: the head-side site of * the base line that defined the first removed column the diff shows. The * defining line is the last removed line whose select item ends in the column * (`x.col`, `expr as col`), else the first removed line naming it. The site is * a `deletionSite`: the finding is about the PR's removal, not pre-existing * code. No removed line names a column → no anchor (the finding stays in the * summary). */ export function removedColumnAnchor( diff: string | undefined, columns: string[], ): Pick { const rows = [...walkDiffRows(diff)] const removed = rows.map((r, i) => ({ r, i, code: r.text.replace(/--.*$/, "").trim() })).filter((x) => x.r.kind === "-") for (const col of columns) { const id = `["\`\\[]?${escapeRe(col)}["\`\\]]?` const defines = new RegExp(`^,?\\s*(?:.*\\s+as\\s+|(?:[\\w"\`\\[\\]]+\\.)*)${id}\\s*,?$`, "i") const names = new RegExp(`(^|[^\\w])${escapeRe(col)}([^\\w]|$)`, "i") const def = removed.filter((x) => defines.test(x.code)).at(-1) ?? removed.find((x) => names.test(x.code)) const line = def && headSiteOfRemoved(rows, def.i) if (line !== undefined) return { startLine: line, endLine: line, deletionSite: true } } return {} } /** * Lanes that scan the whole file (the rule catalog, regex patterns, the * lexical scan) and can therefore report code the PR did not touch. The * engine checks compare head with base and report only what is new, so their * line can be an unchanged context line next to the edit and still be the * PR's own change. */ function scansWholeFile(f: Finding): boolean { return findingOrigin(f) === "catalog" || f.evidence?.tool === "altimate_core.lexical" } /** * Mark a finding anchored on a diff context line (one the PR did not add) as * `preExisting`, unless the line is a `deletionSite` standing in for code the * PR removed. Only whole-file scanning lanes are marked (see * `scansWholeFile`). Lines are never removed here: the envelope keeps every * finding's line, and posting filters inline comments to the lines GitHub * accepts. Every line of a newly added file counts as added. */ export function markPreExisting(findings: Finding[], files: ChangedFile[]): Finding[] { const lines = new Map(files.map((f) => [f.path, { ...scanDiffLines(f.diff), isNew: f.status === "added" }])) return findings.map((f) => { if (typeof f.startLine !== "number" || !scansWholeFile(f)) return f const file = lines.get(f.file) if (!file || file.isNew || !file.commentable.has(f.startLine) || file.added.has(f.startLine) || f.deletionSite) return f return { ...f, preExisting: true } }) } /** True when SQL text contains Jinja (`{{ }}`, `{% %}` or `{# #}`). */ export function hasJinja(sql: string | undefined): boolean { return !!sql && /\{\{|\{%|\{#/.test(sql) } /** Derive the dbt model name from a model file path. */ export function modelNameFromPath(p: string): string { return path.basename(p).replace(/\.(sql|py)$/i, "") } const VALID_CATEGORIES = new Set(ReviewCategoryEnum.options) /** * Map a raw engine-issue category to a ReviewCategory WITHOUT discarding it. * Preserving the engine's category is what keeps the rubric's blockers (e.g. * contract_violation) effective — coercing everything to sql_quality would * silently neuter them. */ function mapCheckCategory(raw?: unknown): ReviewCategory { if (typeof raw !== "string" || !raw) return "sql_quality" const norm = raw.toLowerCase() if (VALID_CATEGORIES.has(norm)) return norm as ReviewCategory if (/contract/.test(norm)) return "contract_violation" if (/idempoten/.test(norm)) return "idempotency" if (/\btest\b|coverage/.test(norm)) return "test_coverage" if (/pii|sensitive/.test(norm)) return "pii_exposure" if (/cost|perf|scan|spill|prune/.test(norm)) return "warehouse_cost" if (/freshness|stale/.test(norm)) return "freshness" return "sql_quality" } function lineageBreakageLane(file: ChangedFile & { kind: string }, impact: ImpactResult, rubric: Rubric): Finding[] { const model = modelNameFromPath(file.path) const total = impact.directCount + impact.transitiveCount const degraded = !impact.hasManifest // dbt resolves `ref()` by MODEL NAME, not file path — so a rename that keeps // the same model name (a pure directory move) does NOT break lineage. Only a // rename that changes the model name is a break, alongside a deletion. const modelNameChanged = file.status === "renamed" && !!file.oldPath && modelNameFromPath(file.oldPath) !== model const isBreakingRemoval = file.status === "deleted" || modelNameChanged // Deleted/renamed model with downstream consumers is the canonical break. if (isBreakingRemoval && total >= rubric.thresholds.lineageWarnConsumers) { const sev = clampSeverity( "lineage_breakage", total >= rubric.thresholds.lineageCriticalConsumers ? "critical" : "warning", degraded ? "unknown" : "high", ) return [ makeFinding({ severity: sev, category: "lineage_breakage", title: `Model ${model} ${file.status} — ${total} downstream consumer${total !== 1 ? "s" : ""}`, body: `${inlineCode(model)} is ${file.status} but ${total} downstream model${total !== 1 ? "s" : ""}` + ` (+${impact.testCount} test${impact.testCount !== 1 ? "s" : ""}) still depend on it.` + (degraded ? "\n\n_No manifest available — verify the blast radius locally._" : ""), file: file.path, model, confidence: degraded ? "unknown" : "high", degraded, evidence: { tool: "impact_analysis", result: impact }, ruleKey: `lineage_breakage:${file.status}`, rule: "impact-analysis:downstream-consumers", }), ] } // A modified model's blast radius is not a defect: it feeds risk tiering // (tier reasons name the downstream count), and concrete breakage on a // modified model comes from the column-removal lanes. return [] } async function semanticChangeLane( file: ChangedFile & { kind: string }, runner: ReviewRunner, oldSql: string | undefined, newSql: string | undefined, dialect: string, impact: ImpactResult, rubric: Rubric, unverified: NonNullable, ): Promise { if (!hasOldSide(file)) return [] if (!oldSql || !newSql || oldSql.trim() === newSql.trim()) return [] const model = modelNameFromPath(file.path) const eq = await runner.equivalence(oldSql, newSql, dialect) // Provably equivalent: stay silent — never nitpick what's proven safe. The core // engine models set-vs-multiset semantics (UNION vs UNION ALL, SELECT DISTINCT), // so equivalent:true is trustworthy for row multiplicity. if (eq.decided && eq.equivalent) return [] if (!eq.decided) { // Undecidable / no schema: the engine not knowing is not evidence of a change // (1 of 426 such findings matched a real defect on replay), so it is not a // finding. The model is listed as not fully verified (kind `abstained`): // the headline and the coverage notes say so, and it does not hold back // approval, like any check that could not decide a model. unverified.push({ path: file.path, reason: "equivalence could not be proven (no schema or unsupported SQL); verify with a data-diff", kind: "abstained", }) return [] } // Decided NOT equivalent. THE FUSION: a proven behavior change to a model with // downstream consumers is a genuine break → critical (clamped by confidence, so // only high/medium can block). No downstream → warning. This is what makes // `semantic_change` ∈ blockOn meaningful: "provably not equivalent + N // downstream → BLOCK". const total = impact.directCount + impact.transitiveCount const baseSev: Severity = total >= rubric.thresholds.lineageCriticalConsumers ? "critical" : "warning" const diffs = (eq.differences ?? []).slice(0, 8) return [ makeFinding({ severity: clampSeverity("semantic_change", baseSev, eq.confidence ?? "medium"), category: "semantic_change", title: total > 0 ? `${model}: rewrite is NOT row-equivalent — ${total} downstream consumer${total !== 1 ? "s" : ""} affected` : `${model}: rewrite is NOT row-equivalent`, body: `${inlineCode(model)} is described as a refactor but produces different results:\n` + (diffs.length ? diffs.map((d) => `- ${d}`).join("\n") : "- output differs") + `\n\nConfidence: ${eq.confidence ?? "medium"}.`, file: file.path, model, confidence: eq.confidence ?? "medium", evidence: { tool: "altimate_core.equivalence", result: { equivalent: false, differences: diffs } }, ruleKey: "semantic_change:not-equivalent", rule: "altimate-core.equivalence:not-equivalent", }), ] } /** * A check issue as evidence. On compiled SQL its line number doesn't exist in * the PR's file, so the compiled line's text goes in `line` (the number moves * to `compiledLine`) for `anchorByEvidence` to find among the added lines; * only text that is specific and unique in the compiled SQL. */ function checkEvidence(issue: { line?: number }, sql: string, linesMatchFile: boolean): object { if (linesMatchFile || typeof issue.line !== "number") return issue const rows = sql.split("\n") const text = rows[issue.line - 1]?.trim() ?? "" if (text.length < EVIDENCE_SUBSTRING_MIN || rows.filter((r) => r.trim() === text).length !== 1) return issue return { ...issue, line: text, compiledLine: issue.line } } /** * Fallback line for a non-deterministic-dedup issue on compiled SQL whose * compiled text is not in the raw diff (the window came from a macro, or a * Jinja-built line): the added line that opens a `row_number()` over the * named time column, else the added line ordering by it (`order by col`, * a macro's `order_by='col'`). No added line names the column → no line. */ function anchorDedupIssue(f: Finding, file: ChangedFile): Finding { if (typeof anchorByEvidence([f], [file])[0].startLine === "number") return f const cols = (/\[([^\]]+)\]/.exec(f.body)?.[1] ?? "").split(",").map((c) => c.trim()).filter(Boolean) const names = (t: string) => cols.some((c) => new RegExp(`(^|[^\\w])${escapeRe(c)}([^\\w]|$)`, "i").test(t)) const added = [...walkDiffLines(file.diff)].filter((r) => r.kind === "+") const hit = added.find((r) => /\brow_number\s*\(/i.test(r.text) && names(r.text)) ?? added.find((r) => /\border(\s+by|_by)\b/i.test(r.text) && names(r.text)) return hit ? { ...f, startLine: hit.line, endLine: hit.line } : f } async function qualityLane( file: ChangedFile & { kind: string }, runner: ReviewRunner, sql: string | undefined, dialect: string, oldSql?: string, /** True when `sql` is the raw file; compiled-SQL line numbers do not exist in the PR's file. */ linesMatchFile = false, /** Where a validation the engine could not complete is recorded instead of read as clean. */ report?: { engineError: (message: string) => void; abstain?: (reason: string) => void }, ): Promise { if (!sql || file.status === "deleted") return [] const model = modelNameFromPath(file.path) const isStaging = /(^|\/)stg_|(^|\/)staging\//.test(file.path) || model.startsWith("stg_") const findings: Finding[] = [] // Diff-scoping (surface only findings the PR INTRODUCED, not pre-existing // issues in the changed file) is done IN CORE: we pass the base compiled SQL // and core returns only the findings new relative to it. The structural / // parsing comparison lives in the AST engine, not this plumbing layer. const check = await runner.check(sql, dialect, oldSql) if (check.unresolvedColumns) report?.abstain?.(UNRESOLVED_COLUMNS_REASON) for (const issue of check.issues ?? []) { // dbt-context tuning of the generic core lint ("what NOT to flag"): // dbt models are SELECT definitions, not standalone queries — a missing // LIMIT is correct, not a smell; and `select *` from a source is the // idiomatic staging pattern. Suppress those in the dbt context. const rule = String(issue.rule ?? "").toLowerCase() if (rule === "select-without-limit") continue if (isStaging && (rule === "select-star" || rule === "select_star")) continue // OLTP/index-oriented rules that don't apply to columnar analytics warehouses // (and false-fire on idiomatic dbt SQL like a correlated NOT EXISTS): if (rule === "correlated-subquery" || rule === "correlated_subquery") continue if (rule === "function-on-filter-column" || rule === "function-on-join-column") continue // Injection rules target queries assembled from user input; a model's UNION or // comment is ordinary SQL. if (INJECTION_RULE.test(rule)) continue const msg = String(issue.message ?? "") // A feature the engine does not implement is a gap in the engine, not an error in the // model. It is not clean either: an engine error (the run cannot approve), with no engine // text in public output. Every other planner message describes the query (a column // missing from GROUP BY, UNION arity, a type mismatch) and stays a finding, as on main. if (rule === "validate" && ENGINE_GAP_MESSAGE.test(msg)) { report?.engineError(msg) continue } // SQL that does not parse (syntax or tokenization) would fail in the warehouse too: a // warning with a fixed text naming the model; the engine's message is not shown. if (rule === "validate" && SYNTAX_MESSAGE.test(msg)) { findings.push( makeFinding({ severity: "warning", category: "sql_correctness", title: `${model}: SQL may not parse`, body: `The review's parser for the project's dialect (${inlineCode(dialect || "default")}) could not read the ${linesMatchFile ? "" : "compiled "}SQL of ${inlineCode(model)}. This is usually a syntax error; confirm with \`dbt compile\` or a run on the warehouse.`, file: file.path, model, confidence: "high", evidence: { tool: "altimate_core.check", result: { rule: "validate", kind: "syntax" } }, ruleKey: "quality:validate:syntax", }), ) continue } const cat = mapCheckCategory(issue.category) const isError = issue.severity === "error" // Error-severity contract/PII issues are blockable; others are warning/suggestion. let sev: Severity = isError ? "warning" : "suggestion" if (isError && (cat === "contract_violation" || cat === "pii_exposure")) sev = "critical" sev = clampSeverity(cat, sev, "high") const f = makeFinding({ severity: sev, category: cat, title: `${model}: ${issue.rule}`, body: issue.message, file: file.path, model, startLine: linesMatchFile ? issue.line : undefined, endLine: linesMatchFile ? issue.line : undefined, evidence: { tool: "altimate_core.check", result: checkEvidence(issue, sql, linesMatchFile) }, // Include the message so distinct instances of the same rule (e.g. two // different non-portable functions) don't collapse under one fingerprint. ruleKey: `quality:${issue.rule}:${(issue.message ?? "").slice(0, 60)}`, }) findings.push(!linesMatchFile && rule === "non_deterministic_dedup" ? anchorDedupIssue(f, file) : f) } return findings } /** An AI finding with its model-written text masked (`maskForAi`) before it is posted or * signed: the model can echo a credential it saw. A suggested replacement that masking would * change is dropped rather than offered with a placeholder in it. */ function maskedAiFinding(f: Finding): Finding { const suggestion = f.suggestion && maskForAi(f.suggestion.replacement) === f.suggestion.replacement ? f.suggestion : undefined const { suggestion: _drop, ...rest } = f // A rule id that could carry words of a title masking changed falls back to the category id // the lane and a replay set. const title = maskForAi(f.title)! return { ...rest, title, body: maskForAi(f.body)!, rule: title === f.title ? f.rule : ruleId("ai-review", f.category), ...(suggestion ? { suggestion } : {}), } } /** * Lexical lane — reserved-word aliases + dialect operators, detected by the * compiled core's `review_lexical_scan` over the raw ADDED diff lines (these * are pre-parse lexical checks; the curated lists live in the binary). Advisory. */ // `unbalanced_quote` is kept: an unterminated literal is certain, not a parser gap. const INJECTION_RULE = /injection/ export const UNRESOLVED_COLUMNS_REASON = "column references were not checked: a relation this model reads has no columns documented in yml" const SYNTAX_MESSAGE = /^syntax error|\bsql parser error\b|\b(parse|syntax) error at line \d|\btokeni[sz]ation error\b|\bfailed to parse\b/i const ENGINE_GAP_MESSAGE = /^this feature is not implemented\b/i async function lexicalLane(file: ChangedFile & { kind: string }, runner: ReviewRunner): Promise { if (!runner.lexicalScan || file.status === "deleted") return [] const added = splitDiff(file.diff).added if (!added.length) return [] const model = modelNameFromPath(file.path) const raw = await runner.lexicalScan(added) return raw.map((f) => makeFinding({ severity: "suggestion", category: "sql_quality", title: `${model}: ${f.message.slice(0, 70)}`, body: f.message, file: file.path, model, confidence: "medium", evidence: { tool: "altimate_core.lexical", result: { rule: f.rule } }, ruleKey: `lexical:${f.rule}`, }), ) } /** Parse a column-lineage source `"db"."schema"."table"."col"` → { table, col }. */ function parseLineageSource(src: string): { table: string; col: string } { const parts = src.replace(/"/g, "").split(".").filter(Boolean) return { col: (parts.at(-1) ?? "").toLowerCase(), table: (parts.at(-2) ?? "").toLowerCase() } } /** * COLUMN-LEVEL breakage — the real lineage differentiator a linter can't do. * When a PR removes/renames an OUTPUT column of a model, trace (via the engine's * column lineage) which downstream models actually SELECT that column and flag * the concrete break: "removing `X` breaks `A`, `B`". Needs base+head compiled * SQL, the manifest DAG, and downstream compiled SQL. */ async function columnBreakageLane( ctx: ModelContext, runner: ReviewRunner, getCompiled: ((file: string, side: "old" | "new") => Promise) | undefined, dialect: string, abstain: (reason: string) => void, ): Promise { if (!runner.columnLineage || !runner.downstreamModels || !getCompiled) return [] const { file, engineOldSql, engineNewSql } = ctx if (!engineOldSql || !engineNewSql || !hasOldSide(file)) return [] const model = modelNameFromPath(file.path) // 1. Output columns removed by this change (column-lineage targets, old − new). const oldCols = new Set((await runner.columnLineage(engineOldSql, dialect)).map((e) => e.target.toLowerCase()).filter(Boolean)) // No base column resolved: nothing can be reported removed. The lane records // no abstention of its own: an unexpandable `select *` base is ordinary, and // listing every such model would be noise. A base the engine could not parse // at all is still listed, by the runner's parse abstention. if (!oldCols.size) return [] const newCols = new Set((await runner.columnLineage(engineNewSql, dialect)).map((e) => e.target.toLowerCase()).filter(Boolean)) // Base columns are known but the head's are not (a failed lineage, or a // `select *` it cannot resolve): their fate is undecided. Abstain rather than // report every base column removed, and say so, since "no removed column" was // not established. if (!newCols.size) { // A head the engine could not parse is already listed by the runner's // abstention ("could not parse the SQL"); listing it again here would // show one failure twice. const headUnparsed = (runner.abstentions?.() ?? []).some( (a) => a.method === "columnLineage" && a.sql?.includes(engineNewSql), ) // A head the parser could not read is an abstention like any other parse // gap, which does not hold back approval. if (headUnparsed) return [] abstain("the column lineage check could not resolve the head's output columns") // The head parsed, but its columns cannot be listed (a `select *` over a // table): with models reading this one, a removed column would break them, // so say so as an undecided warning (never blocking), not only a listing. const consumers = await runner.downstreamModels(model) if (!consumers.length) return [] return [ makeFinding({ severity: "warning", category: "lineage_breakage", title: `${model}: could not check its downstream models for removed columns`, body: `The head's output columns could not be resolved, so whether this change removes a column that ` + `${ticks(consumers.map((c) => c.name))} still read${consumers.length === 1 ? "s" : ""} could not be decided. ` + `Confirm the model still outputs: ${ticks([...oldCols])}.`, file: file.path, model, // `unknown`: an undecided result never counts toward the warning pattern. confidence: "unknown", evidence: { tool: "altimate_core.column_lineage", result: { baseColumns: [...oldCols], downstream: consumers.map((c) => c.name) } }, ruleKey: `lineage_breakage:column-undecided`, }), ] } const removed = [...oldCols].filter((c) => !newCols.has(c)) if (!removed.length) return [] const removedSet = new Set(removed) // 2. Which downstream models actually consume a removed column of THIS model? const downstream = await runner.downstreamModels(model) const brokenBy = new Map>() // removedCol -> downstream models for (const d of downstream) { const dSql = await getCompiled(d.path, "new") if (!dSql) continue for (const edge of await runner.columnLineage(dSql, dialect)) { const { table, col } = parseLineageSource(edge.source) if (table === model.toLowerCase() && removedSet.has(col)) { if (!brokenBy.has(col)) brokenBy.set(col, new Set()) brokenBy.get(col)!.add(d.name) } } } if (!brokenBy.size) return [] const detail = [...brokenBy.entries()] .map(([col, models]) => `${inlineCode(col)} → ${ticks([...models])}`) .join("; ") return [ makeFinding({ severity: "critical", category: "lineage_breakage", title: `${model}: removed column(s) break downstream models`, body: `This change removes/renames output column(s) that downstream models still SELECT: ${detail}. ` + `Those models will fail (or silently drop the column) on the next run. Update the consumers or keep the column.`, file: file.path, model, confidence: "high", evidence: { tool: "altimate_core.column_lineage", result: { removed, brokenBy: Object.fromEntries([...brokenBy].map(([k, v]) => [k, [...v]])) } }, ruleKey: `lineage_breakage:column-removed`, rule: "altimate-core.column-lineage:removed-columns", // Anchored on the removed line, so the finding that decides the verdict is the one posted there. ...removedColumnAnchor(file.diff, [...brokenBy.keys()]), }), ] } /** * The model's output column names, read from its final projection (the * select-list parser), with a `*` over CTEs or subqueries whose columns are * known expanded (the usual `select * from final`). Undefined when the list is * not complete: a `*` over a table, a `ref()` or an unknown layout, an unnamed * computed item, or SQL the parser does not model. Column lineage is not used * for names: the engine leaves out outputs with no source column (`count(*)`, * literals) and columns of tables it has no schema for. */ function outputColumns(sql: string): Set | undefined { const columns = finalOutputs(sql).columns if (!columns?.length || columns.some((c) => !c)) return undefined return new Set(columns.map((c) => c!.toLowerCase())) } /** Output columns added and removed by the change; `unknown` when either side's * column list is not complete, so nothing can be said about removals. With * compiled SQL missing on either side (`dbt parse`-only CI, or a base that did * not compile) both sides are read from the raw models instead. */ function columnDelta(ctx: ModelContext): { added: string[]; removed: string[]; unknown: boolean; baseMissing?: boolean } { const none = { added: [], removed: [], unknown: false } const unknown = { added: [], removed: [], unknown: true } const { file, engineNewSql, engineOldSql, newSql, oldSql } = ctx if (file.status === "deleted") return none const withOld = hasOldSide(file) const compiled = !!engineNewSql && (!withOld || !!engineOldSql) const read = compiled ? outputColumns : rawOutputColumns const headSql = compiled ? engineNewSql : newSql if (!headSql) return none const current = read(headSql) if (!current) return unknown if (!withOld) return { added: [...current], removed: [], unknown: false } const baseSql = compiled ? engineOldSql : oldSql // No base SQL to read (unreadable): that gap is already recorded for the // file, under its own reason. if (!baseSql) return { ...unknown, baseMissing: true } const before = read(baseSql) // A base without compiled SQL is already listed as such: its raw code being // unreadable to the parser adds no second reason. if (!before) return !engineOldSql ? { ...unknown, baseMissing: true } : unknown return { added: [...current].filter((c) => !before.has(c)), removed: [...before].filter((c) => !current.has(c)), unknown: false, } } const JINJA_BLOCK_OPEN = /^(if|for|macro|call|filter)$/ const JINJA_BLOCK_CLOSE = /^end(if|for|macro|call|filter|set)$/ const TAG_MARK = "\u0001" const JINJA_PLACEHOLDER = "__jinja__" /** A character that, next to a `{{ … }}`, makes the expression part of a name. */ const GLUE = /[\w"`$]/ /** * Output columns of a raw (Jinja) model, read without rendering it: `{{ … }}` * becomes a placeholder and `{% … %}` tags are dropped. Undefined whenever the * template could change the list: * - a column name holding a Jinja expression (`{{ var('c') }}_amount`, an * alias `"amount_{{ … }}"`) or a Jinja expression standing as an item; * - a tag inside a SELECT list; * - a `select` inside an `{% if %}` / `{% for %}` / `{% set %}` block, other * than a subquery whose parentheses open and close within the block (the * `{% if is_incremental() %} where ts > (select max(ts) …)` filter); * - anything `finalOutputs` cannot name completely, which includes two * top-level SELECTs with no set operator joining them. */ function rawOutputColumns(sql: string): Set | undefined { const parts = sql .replace(/\{#[\s\S]*?#\}/g, (m) => m.replace(/[^\n]/g, " ")) // An expression glued to a name stays part of that name, so the name // holds the placeholder and reads as unknown. .replace(/\{\{[\s\S]*?\}\}/g, (m, at: number, text: string) => GLUE.test(text[at - 1] ?? "") || GLUE.test(text[at + m.length] ?? "") ? JINJA_PLACEHOLDER : ` ${JINJA_PLACEHOLDER} `, ) .split(/(\{%[\s\S]*?%\})/) // `plain`: tags blanked. `flat`: same offsets, string literals and SQL // comments blanked too and each tag marked, for the structural scan. let plain = "" let flat = "" let blocks = 0 for (const [i, part] of parts.entries()) { if (i % 2 === 1) { const word = /^\{%-?\s*(\w+)/.exec(part)?.[1]?.toLowerCase() ?? "" if (JINJA_BLOCK_OPEN.test(word) || (word === "set" && !/=/.test(part))) blocks++ else if (JINJA_BLOCK_CLOSE.test(word)) blocks = Math.max(0, blocks - 1) const blank = part.replace(/[^\n]/g, " ") plain += blank flat += TAG_MARK + blank.slice(1) continue } const stripped = part.replace(/'(?:[^']|'')*'|--[^\n]*|\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")) if (blocks > 0 && selectOutsideOwnParens(stripped)) return undefined plain += part flat += stripped } // Top-level keywords of the flattened statement. const top: Array<{ word: string; at: number }> = [] let depth = 0 for (let i = 0; i < flat.length; i++) { const ch = flat[i] if (ch === "(") depth++ else if (ch === ")") depth-- else if (depth === 0 && /[a-z]/i.test(ch) && !/\w/.test(flat[i - 1] ?? "")) { const w = /^(with|select|from|union|intersect|except|minus)\b/i.exec(flat.slice(i, i + 10))?.[1]?.toLowerCase() if (w) top.push({ word: w, at: i }) } } const selects = top.filter((t) => t.word === "select") if (!selects.length) return undefined // A tag inside any top-level SELECT list makes its columns conditional. for (const s of selects) { const listEnd = top.find((t) => t.at > s.at && t.word !== "with")?.at ?? flat.length if (flat.slice(s.at, listEnd).includes(TAG_MARK)) return undefined } // Text before the statement (`{{ config(…) }}`) is not SQL. const begin = top.find((t) => t.word === "with" || t.word === "select")!.at const columns = finalOutputs(" ".repeat(begin) + plain.slice(begin)).columns if (!columns?.length || columns.some((c) => !c || c.toLowerCase().includes(JINJA_PLACEHOLDER))) return undefined return new Set(columns.map((c) => c!.toLowerCase())) } /** True when `text` (one stretch of SQL inside a Jinja block) has a `select` * that is not inside parentheses opened within the stretch. */ function selectOutsideOwnParens(text: string): boolean { let depth = 0 for (const m of text.matchAll(/[()]|\bselect\b/gi)) { if (m[0] === "(") depth++ else if (m[0] === ")") depth-- else if (depth <= 0) return true } return false } /** Names from the repository or the manifest, as code spans that a backtick, * `@` or line break inside cannot break out of. */ const inlineCode = (x: string) => codeSpan(x.replace(/\s+/g, " ")) const ticks = (xs: string[]) => xs.map(inlineCode).join(", ") const FINAL_LAYER = /(^|\/)(marts?|reporting|dimensional|presentation|extracts|exports)\//i // Intermediate/staging models nested under a final-layer folder are not read directly. const NOT_FINAL = /(^|\/)(intermediate|staging|base)\/|(^|\/)(int|stg|base)_[^/]*$/i /** Column names (lowercased) the given schema yml texts declare for `model`: * the `models:` entry with that name (all its versions), or a versioned * model's file name (`orders_v2` → `orders`, version 2). Unparsable files * declare nothing. */ export function ymlModelColumns( texts: string[], model: string, /** The manifest node's name and version, when known: matched as such, so a version's * `defined_in` file name never selects another version. */ identity?: { name: string; version?: string | number }, ): Set { const out = new Set() const target = model.toLowerCase() const names = (cols: unknown) => { if (Array.isArray(cols)) for (const c of cols) if (c && typeof c === "object" && "name" in c) out.add(String((c as any).name).toLowerCase()) } for (const text of texts) { let doc: any try { doc = YAML.parse(text) } catch { continue } for (const m of Array.isArray(doc?.models) ? doc.models : []) { const name = String(m?.name ?? "").toLowerCase() if (!name) continue const versions: any[] = Array.isArray(m.versions) ? m.versions : [] const wanted = identity?.version === undefined ? undefined : String(identity.version).toLowerCase() if (identity ? name === identity.name.toLowerCase() && wanted === undefined : name === target) { names(m.columns) for (const v of versions) names(v?.columns) continue } if (identity && name !== identity.name.toLowerCase()) continue const v = versions.find((v) => identity ? String(v?.v ?? "").toLowerCase() === wanted : `${name}_v${String(v?.v ?? "").toLowerCase()}` === target || String(v?.defined_in ?? "").toLowerCase() === target, ) if (v) { // A version inherits the model's columns through `include` (default // all) less `exclude`; its own entries add to them. const selector = (Array.isArray(v.columns) ? v.columns : []).find( (c: any) => c && typeof c === "object" && ("include" in c || "exclude" in c), ) const include = selector?.include ?? "all" const listed = (x: unknown) => new Set((Array.isArray(x) ? x : []).map((c) => String(c).toLowerCase())) const included = listed(include) const excluded = listed(selector?.exclude) for (const c of Array.isArray(m.columns) ? m.columns : []) { const col = String(c?.name ?? "").toLowerCase() if (!col) continue if ((include === "all" || include === "*" || included.has(col)) && !excluded.has(col)) out.add(col) } names(v.columns) } } } return out } /** * Consumers dbt refs don't show. A column removed or renamed on a model that * feeds exposures (dashboards, apps, ML) or has an enforced contract breaks * readers outside the DAG; the finding names them. And a new column missing * from an enforced contract fails `dbt build` — reported only when the project * opts in (`checkContractColumns`); `dbt build` already enforces it. */ async function consumerContractLane( ctx: ModelContext, runner: ReviewRunner, opts: { checkContractColumns: boolean; changedYmlText: () => Promise; abstain: (reason: string) => void }, ): Promise { if (!runner.modelConsumers) return [] const model = modelNameFromPath(ctx.file.path) const consumers = await runner.modelConsumers(model, ctx.file.path) if (consumers?.ambiguous) { opts.abstain("several models in the manifest match this file, so its declared consumers were not checked") return [] } if (!consumers) return [] const declared = consumers.exposures.length > 0 || consumers.contractEnforced // A final-layer model is read outside dbt (BI, exports) even when nothing is declared. const finalLayer = FINAL_LAYER.test(ctx.file.path) && !NOT_FINAL.test(ctx.file.path) if (!declared && !(finalLayer && hasOldSide(ctx.file))) return [] const { added, removed, unknown, baseMissing } = columnDelta(ctx) if (unknown) { // The final-layer suggestion stays silent when the columns cannot be // listed, and a missing base is already listed under its own reason. if (declared && !baseMissing) opts.abstain("the model's output columns could not be listed (a `*`, an unnamed expression or SQL the parser does not follow), so its declared consumers were not checked") return [] } const out: Finding[] = [] if (removed.length && !declared) { out.push( makeFinding({ severity: "suggestion", category: "lineage_breakage", title: `${model}: removed column(s) on a final-layer model`, body: `This change removes ${ticks(removed)} from ${inlineCode(model)}, a final-layer model that dashboards and exports usually read directly; ` + `those readers aren't in the DAG. Keep the old column alongside the new one for a deprecation period, or declare the consumers as exposures.`, file: ctx.file.path, model, confidence: "medium", evidence: { tool: "dbt.manifest", result: { removed, finalLayer: true } }, ruleKey: "lineage_breakage:final-layer-column-removed", rule: "dbt.manifest:removed-final-layer-columns", ...removedColumnAnchor(ctx.file.diff, removed), }), ) } if (removed.length && declared) { const who: string[] = [] if (consumers.exposures.length) who.push(`exposure(s) ${consumers.exposures.map((e) => `${inlineCode(e.name)}${e.type ? ` (${e.type.replace(/[^\w -]/g, "")})` : ""}`).join(", ")}`) if (consumers.contractEnforced) who.push("an enforced contract, so readers outside dbt rely on its columns") out.push( makeFinding({ severity: "warning", category: "lineage_breakage", title: `${model}: removed column(s) on a model with declared consumers`, body: `This change removes ${ticks(removed)}. ${inlineCode(model)} has ${who.join(" and ")}. ` + `Keep the column for a deprecation period, or publish a new model version and migrate the consumers.`, file: ctx.file.path, model, confidence: "high", evidence: { tool: "dbt.manifest", result: { removed, exposures: consumers.exposures.map((e) => e.name), contractEnforced: consumers.contractEnforced }, }, ruleKey: "lineage_breakage:consumer-column-removed", rule: "dbt.manifest:removed-columns-declared-consumers", ...removedColumnAnchor(ctx.file.diff, removed), }), ) } if (consumers.contractEnforced && opts.checkContractColumns && consumers.contractColumns.length && added.length) { const declared = new Set(consumers.contractColumns) // A column the PR declares for THIS model in a changed yml is declared even // when the manifest predates the PR; another model's columns never count. // Matched by the manifest node's own name and version: a version with // `defined_in` lives in a file named otherwise, and that name never selects another version. const ymlTexts = await opts.changedYmlText() if (ymlTexts === undefined) { opts.abstain("a schema file this PR changes could not be read, so the new columns were not checked against the enforced contract") return out } const inChangedYml = consumers.name ? ymlModelColumns(ymlTexts, model, { name: consumers.name, version: consumers.version }) : ymlModelColumns(ymlTexts, model) const missing = added.filter((c) => !declared.has(c) && !inChangedYml.has(c)) if (missing.length) out.push( makeFinding({ severity: "warning", category: "contract_violation", title: `${model}: new column(s) missing from the enforced contract`, body: `${ticks(missing)} ${missing.length === 1 ? "is" : "are"} selected but not declared in ${inlineCode(model)}'s contract, ` + `so \`dbt build\` fails the contract check. Declare ${missing.length === 1 ? "it" : "them"} (with \`data_type\`) in the model's yml.`, file: ctx.file.path, model, confidence: "high", evidence: { tool: "contract-check", result: { missing } }, ruleKey: "contract_violation:contract-missing-column", rule: "contract-check:missing-columns", }), ) } return out } const LINEAGE_REMOVED = "altimate-core.column-lineage:removed-columns" const CONSUMER_REMOVED = "dbt.manifest:removed-columns-declared-consumers" /** * One removed column, one report: when a model's removal both breaks a downstream model * (column lineage, critical) and drops a column from a model with declared consumers (a * warning), the warning is folded into the critical finding, which names the declared * consumers too. The critical one decides the verdict either way; it is the one posted. */ export function foldConsumerDuplicates(findings: Finding[], shown: (f: Finding) => boolean = () => true): Finding[] { const removedOf = (f: Finding) => { const r = (f.evidence?.result as { removed?: unknown } | undefined)?.removed return Array.isArray(r) ? r.map(String) : [] } // Only into a lineage finding that is shown: a lineage rule set to `off` must not take the // declared-consumer finding (another rule) out of the comment with it. const lineage = new Map(findings.filter((f) => f.rule === LINEAGE_REMOVED && shown(f)).map((f) => [f.file, f])) if (!lineage.size) return findings const folded = new Map() const out = findings.filter((f) => { const l = f.rule === CONSUMER_REMOVED ? lineage.get(f.file) : undefined if (!l || !removedOf(f).some((c) => removedOf(l).includes(c))) return true folded.set(f.file, f) return false }) if (!folded.size) return findings return out.map((f) => { const c = f.rule === LINEAGE_REMOVED ? folded.get(f.file) : undefined if (!c) return f const cr = (c.evidence?.result ?? {}) as Record return { ...f, body: `${f.body} ${c.body}`, evidence: { ...f.evidence!, result: { ...(f.evidence!.result as object), declaredConsumers: { removed: removedOf(c), exposures: cr.exposures, contractEnforced: cr.contractEnforced }, }, }, } }) } /** * Opt-in consumer column lists (`consumerColumnLists` in review.yml): when the * PR changes a model's columns, every configured list that mirrors the model * must gain the new columns and drop the removed ones. A list whose model * cannot be told, or a model whose columns cannot be listed, is abstained on. */ function consumerListLane(ctx: ModelContext, lists: ConsumerColumnList[], abstain: (reason: string) => void): Finding[] { if (!lists.length || !hasOldSide(ctx.file)) return [] const model = modelNameFromPath(ctx.file.path) // Each list is classified once, against the lists of its own file only. const byPath = new Map() for (const l of lists) byPath.set(l.path, [...(byPath.get(l.path) ?? []), l]) const mirrors: ConsumerColumnList[] = [] const undecided: ConsumerColumnList[] = [] for (const l of lists) { const state = listMirrorsModel(l, model, byPath.get(l.path)) if (state === true) mirrors.push(l) else if (state === undefined) undecided.push(l) } if (!mirrors.length && !undecided.length) return [] const { added, removed, unknown, baseMissing } = columnDelta(ctx) if (unknown) { if (!baseMissing) abstain("the model's output columns could not be listed (a `*`, an unnamed expression or SQL the parser does not follow), so its consumer column lists were not checked") return [] } if (!added.length && !removed.length) return [] for (const list of undecided) { const label = listLabel(list, byPath.get(list.path)) abstain( `consumerColumnLists: ${list.path}${label ? ` (${label})` : ""} names this model ` + "only away from the list's own lines, so whether the list mirrors it could not be told; set `model` on the entry", ) } const out: Finding[] = [] for (const list of mirrors) { const have = new Set(list.columns) const missing = added.filter((c) => !have.has(c)) const stale = removed.filter((c) => have.has(c)) if (!missing.length && !stale.length) continue const parts: string[] = [] if (missing.length) parts.push(`lacks the new column(s) ${ticks(missing)}`) if (stale.length) parts.push(`still lists the removed column(s) ${ticks(stale)}`) const sameFile = byPath.get(list.path) const label = listLabel(list, sameFile) // The path and identifier are the repository's, not ours: code spans, so a // backtick or `@` in them can neither break the comment nor ping anyone. const named = `${label ? `${inlineCode(label)} in ` : ""}${inlineCode(list.path)}` out.push( makeFinding({ severity: "warning", category: "lineage_breakage", title: `${model}: column list ${named} is out of step`, body: `The column list ${named} mirrors ${inlineCode(model)} and ${parts.join(" and ")}. ` + `Readers of that list will drop or fail on these columns; update it in this PR.`, file: ctx.file.path, model, confidence: "high", evidence: { tool: "consumer-column-list", result: { list: list.path, name: list.name, line: list.line, missing, stale } }, // No line number: the fingerprint must survive an edit above the list. ruleKey: `lineage_breakage:consumer-list:${list.path}:${listKey(list, sameFile)}`, rule: "consumer-column-list:stale", }), ) } return out } /** Incremental / table-replace semantics (incremental-semantics.ts). */ async function incrementalSemanticsLane( ctx: ModelContext, runner: ReviewRunner, dialect: string, dialectKnown: boolean, prText: string, sliceVars: string[], abstain: (reason: string) => void, blockingRules: string[], ): Promise { const { file, newSql, oldSql } = ctx if (!newSql || file.status === "deleted") return [] const model = modelNameFromPath(file.path) // Looked up by file first, as the consumer lane does: a versioned or package // model is found under its own node. const consumers = await runner.modelConsumers?.(model, file.path) return incrementalFindings({ file, model, newSql, oldSql: hasOldSide(file) ? oldSql : undefined, manifestConfig: await runner.modelConfig?.(model), added: splitDiff(file.diff).added, dialect, dialectKnown, prText, hasExposures: !!consumers?.exposures.length, sliceVars, columnDelta: () => columnDelta(ctx), outputColumns: () => { const cols = ctx.engineNewSql ? outputColumns(ctx.engineNewSql) : undefined return cols && [...cols] }, abstain, blockingRules, }) } /** * DATA-DIFF — the showcase: actually run base vs head against the warehouse * (core DataParity) and report row/value deltas a linter can never see. Needs a * configured warehouse connection (CI); skips gracefully when absent. Key * columns are inferred from the model's `*_id`/`id` output columns. */ async function dataDiffLane( ctx: ModelContext, runner: ReviewRunner, dialect: string, cfg: { enabled: boolean; warehouse: string }, ): Promise { // Opt-in: data-diff costs warehouse compute and needs credentials, so it only // runs when explicitly enabled in `.altimate/review.yml`. if (!cfg.enabled) return [] if (!runner.dataDiff || !runner.columnLineage) return [] const { file, engineOldSql, engineNewSql } = ctx if (!engineOldSql || !engineNewSql || !hasOldSide(file)) return [] const model = modelNameFromPath(file.path) const cols = (await runner.columnLineage(engineNewSql, dialect)).map((e) => e.target.toLowerCase()) const keys = [...new Set(cols.filter((c) => c === "id" || /_id$/.test(c)))].slice(0, 1) if (!keys.length) return [] // no inferable key → can't data-diff const diff = await runner.dataDiff(engineOldSql, engineNewSql, keys, cfg.warehouse || undefined) // null: no warehouse/driver configured (a skip), or a failed diff, which the // runner records as an engine error so the run is not complete. if (!diff) return [] const base = diff.rowsOnlyInBase ?? 0 const head = diff.rowsOnlyInHead ?? 0 const changed = diff.rowsChanged ?? 0 if (base + head + changed === 0) return [] return [ makeFinding({ severity: "warning", category: "semantic_change", title: `${model}: data-diff shows output rows change vs base`, body: `Run against the warehouse, this change produces a different result than the base on key ${inlineCode(String(keys[0]))}: ` + `${base} only-in-base, ${head} only-in-head, ${changed} changed` + (diff.summary ? ` — ${diff.summary}` : "") + `. Confirm the data impact is intended.`, file: file.path, model, confidence: "high", evidence: { tool: "data.diff", result: diff }, ruleKey: "semantic_change:data-diff", rule: "data.diff:row-delta", }), ] } /** Count leading `_`-separated segments two model names share (a merge-stem signal). */ function leadingSegMatch(a: string, b: string): number { const A = a.split("_") const B = b.split("_") let n = 0 while (n < A.length && n < B.length && A[n] === B[n]) n++ return n } /** Strip a trailing semicolon so a model's compiled SQL can be wrapped as a subquery. */ function asSubquery(sql: string, alias: string): string { return `select * from (\n${sql.trim().replace(/;\s*$/, "")}\n) as ${alias}` } /** * TOPOLOGY-AWARE equivalence — covers the merge refactor that model-level * equivalence misses. When a PR DELETES N models {X,Y,Z} and ADDS one model W * that supersedes them (e.g. `int_column_access_{base,direct,modified}` → * `int_column_access_daily`), W has no 1:1 base, so `semanticChangeLane` skips * it entirely. Here we compose the BASE compiled SQL of the replaced set as * `UNION ALL` and ask the engine whether W reproduces it. * * FP-safe BY CONSTRUCTION: the `UNION ALL` composition is INFERRED (the replaced * models might have been combined differently downstream), so this lane is * ADVISORY ONLY — it is hard-capped at `warning` and can never block. It surfaces * "this merge isn't proven equivalent — verify" rather than asserting a break, * and stays SILENT when the engine PROVES the merge equivalent. */ async function topologyEquivalenceLane( modelFiles: (ChangedFile & { kind: string })[], runner: ReviewRunner, getCompiled: ((file: string, side: "old" | "new") => Promise) | undefined, dialect: string, ): Promise { if (!getCompiled) return [] const deleted = modelFiles.filter((f) => f.status === "deleted") const added = modelFiles.filter((f) => f.status === "added") if (deleted.length < 2 || !added.length) return [] const out: Finding[] = [] for (const w of added) { const wName = modelNameFromPath(w.path) // Pair: replaced set = deleted models sharing the MAXIMAL leading-segment // stem with W, requiring ≥2 shared segments and ≥2 such models (a real merge, // not a coincidental name overlap). let maxSeg = 0 for (const d of deleted) maxSeg = Math.max(maxSeg, leadingSegMatch(wName, modelNameFromPath(d.path))) if (maxSeg < 2) continue const replaced = deleted.filter((d) => leadingSegMatch(wName, modelNameFromPath(d.path)) === maxSeg) if (replaced.length < 2) continue // Compose the BASE side: UNION ALL of the replaced models' base compiled SQL. const parts: string[] = [] let ok = true for (let i = 0; i < replaced.length; i++) { const sql = await getCompiled(replaced[i].path, "old") if (!sql || !sql.trim()) { ok = false break } parts.push(asSubquery(sql, `_repl_${i}`)) } if (!ok || parts.length < 2) continue const headSql = await getCompiled(w.path, "new") if (!headSql || !headSql.trim()) continue const baseComposition = parts.join("\nunion all\n") const eq = await runner.equivalence(baseComposition, headSql.trim().replace(/;\s*$/, ""), dialect) // Proven equivalent → the merge is safe; stay silent (never nitpick what's proven). if (eq.decided && eq.equivalent) continue const replacedNames = ticks(replaced.map((d) => modelNameFromPath(d.path))) const diffs = (eq.differences ?? []).slice(0, 6) const detail = eq.decided ? `the merged model is **NOT row-equivalent** to \`UNION ALL\` of the replaced models` + (diffs.length ? `:\n${diffs.map((d) => `- ${d}`).join("\n")}` : ".") : `equivalence could not be decided (no schema / unsupported SQL).` out.push( makeFinding({ // Hard-capped at warning: the composition is inferred, so this never blocks. severity: clampSeverity("semantic_change", "warning", eq.confidence ?? "low"), category: "semantic_change", title: `${wName}: merges ${replaced.length} models — not proven equivalent`, body: `${inlineCode(wName)} replaces ${replacedNames}. This is a TOPOLOGY refactor (the new model has ` + `no 1:1 base), so model-level equivalence can't check it directly. Composing the replaced ` + `models as \`UNION ALL\`, ${detail}\n\n` + `_The \`UNION ALL\` composition is inferred — if the replaced models were combined differently ` + `(e.g. \`UNION\` / a join) by their consumer, a difference here may be expected. Confirm the ` + `data impact with a data-diff._`, file: w.path, model: wName, confidence: eq.decided ? eq.confidence ?? "low" : "unknown", degraded: !eq.decided, evidence: { tool: "altimate_core.equivalence", result: { topology: "merge", replaced: replaced.map((d) => modelNameFromPath(d.path)), decided: eq.decided, equivalent: eq.equivalent ?? null, }, }, ruleKey: `semantic_change:topology-merge:${wName}`, rule: "altimate-core.equivalence:not-equivalent", }), ) } return out } /** * GRAIN MISMATCH — the model's SQL dedups/groups by a key that conflicts with its * DECLARED uniqueness (primary key / `unique` test). Catches `6c42eab`-class bugs: * deduping on `role_name` while the grain is declared `role_id` keeps the wrong * rows / the uniqueness test silently won't hold. Sound: needs a declared key AND a * clear grain key in the SQL; fires only when the SQL grain has a column the * declared key lacks (so the declared key isn't actually unique). */ async function grainMismatchLane(ctx: ModelContext, runner: ReviewRunner): Promise { if (!runner.grain || !runner.declaredPrimaryKey) return [] const { file, engineNewSql } = ctx if (!engineNewSql || file.status === "deleted") return [] const model = modelNameFromPath(file.path) const pk = await runner.declaredPrimaryKey(model) if (!pk || !pk.length) return [] // no declared grain → nothing to check against const grain = await runner.grain(engineNewSql) const actual = grain.group_by.length ? grain.group_by : grain.dedup_partition if (!actual.length) return [] // no clear grain in the SQL → stay silent const pkLower = new Set(pk.map((c) => c.toLowerCase())) const extra = actual.filter((c) => !pkLower.has(c.toLowerCase())) if (!extra.length) return [] // grain ⊆ declared key → the key is still unique const how = grain.group_by.length ? "grouped by" : "deduped (PARTITION BY) on" return [ makeFinding({ severity: clampSeverity("sql_correctness", "warning", "medium"), category: "sql_correctness", title: `${model}: grain key conflicts with declared uniqueness`, body: `${inlineCode(model)} is ${how} [${actual.join(", ")}], but it declares uniqueness on ` + `[${pk.join(", ")}] (contract / unique test). Column(s) [${extra.join(", ")}] are in the ` + `grain but not the declared key, so the model can emit multiple rows per declared key — ` + `the uniqueness test will fail or the dedup keeps the wrong row. Align the GROUP BY / ` + `PARTITION BY with the declared key (e.g. dedup on the id, not the name).`, file: file.path, model, confidence: "medium", evidence: { tool: "altimate_core.grain", result: { grain: actual, declared: pk, extra } }, ruleKey: "sql_correctness:grain-mismatch", rule: "altimate-core.grain:conflicts-declared-uniqueness", }), ] } /** * MISSING GRAIN TEST — a NEW grain-bearing model (intermediate / mart / fact / dim) * with no declared uniqueness (`unique` / `unique_combination_of_columns` / contract * PK). Most of the dedup/grain/fan-out bugs in practice trace back to a model whose * grain was never asserted, so a silent dup never trips a test. Advisory (suggestion) * and scoped to grain-bearing models so staging passthroughs aren't nagged. */ async function missingGrainTestLane(ctx: ModelContext, runner: ReviewRunner): Promise { if (!runner.declaredPrimaryKey) return [] const { file } = ctx if (file.status !== "added") return [] const model = modelNameFromPath(file.path) const grainBearing = /(^|\/)(marts|intermediate|reporting)\//.test(file.path) || /^(int_|mrt_|fct_|fact_|dim_|agg_|rpt_)/.test(model) if (!grainBearing) return [] const pk = await runner.declaredPrimaryKey(model) if (pk && pk.length) return [] // grain is asserted — good return [ makeFinding({ severity: clampSeverity("test_coverage", "suggestion", "medium"), category: "test_coverage", title: `${model}: new model has no uniqueness/grain test`, body: `${inlineCode(model)} is a new grain-bearing model but declares no \`unique\` / ` + `\`unique_combination_of_columns\` test (and no contract primary key). Without a grain ` + `assertion, a fan-out or wrong-dedup bug silently doubles rows and no test catches it. ` + `Add a uniqueness test on the model's grain so the contract is enforced in CI.`, file: file.path, model, confidence: "medium", evidence: { tool: "dbt.manifest", result: { hasGrainTest: false } }, ruleKey: "test_coverage:missing-grain-test", rule: "dbt.manifest:new-model-no-grain-test", }), ] } /** Var names defined under `vars:` in dbt_project.yml (top level and project-scoped). */ export function definedVars(projectYml?: string): Set { const out = new Set() if (!projectYml) return out let doc: any try { doc = YAML.parse(projectYml) } catch { return out } const vars = doc?.vars if (!vars || typeof vars !== "object") return out for (const [k, v] of Object.entries(vars)) { out.add(k) if (v && typeof v === "object" && !Array.isArray(v)) for (const k2 of Object.keys(v)) out.add(k2) } return out } /** * `{% set cfg = {"materialized": "incremental", ...} %}` + `config(**cfg)` is a * common way to share config; inline a flat literal dict's entries as kwargs so * the config lint sees them. */ export function inlineConfigSplats(sql: string): string { const dicts = new Map() for (const m of sql.matchAll(/\{%-?\s*set\s+(\w+)\s*=\s*\{/g)) { // The dict body up to its matching brace; nested dicts (a BigQuery partition_by) stay as written. const open = m.index! + m[0].length - 1 let depth = 0 let end = -1 for (let i = open; i < sql.length; i++) { if (sql[i] === "{") depth++ else if (sql[i] === "}" && --depth === 0) { end = i break } } if (end < 0 || !/^\s*-?%\}/.test(sql.slice(end + 1))) continue const body = sql.slice(open + 1, end) // Only top-level `"key":` becomes `key=`. let out = "" let d = 0 for (let i = 0; i < body.length; i++) { const c = body[i] if ("{[(".includes(c)) d++ else if ("}])".includes(c)) d-- const key = d === 0 ? /^["'](\w+)["']\s*:/.exec(body.slice(i)) : null if (key) { out += key[1] + "=" i += key[0].length - 1 } else out += c } dicts.set(m[1], out.replace(/,\s*$/, "")) } if (!dicts.size) return sql return sql.replace(/\bconfig\s*\(([\s\S]*?)\)\s*\}\}/g, (whole) => whole.replace(/\*\*(\w+)/g, (splat, name) => dicts.get(name) ?? splat), ) } const MUTABLE_TIME_COLUMN = /(^|_)(updated|modified|changed|synced|loaded|ingested|refreshed|extracted)(_at|_on|_ts|_time|_date)?$|^_?(fivetran|airbyte|stitch|sdc)_/i const MATERIALIZED = /\bmaterialized\s*=\s*['"](\w+)['"]/i const MICROBATCH = /\bincremental_strategy\s*=\s*['"]microbatch['"]/i /** * An unguarded incremental model is this PR's problem only when the PR creates it: a model * whose SQL a macro generates carries its guard in the macro, and a model that was already * incremental without a guard (same materialization, no `is_incremental()`) predates the PR. */ function introducesUnguardedIncremental(newSql: string, oldSql: string | undefined): boolean { const outsideJinja = newSql.replace(/\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}|\{#[\s\S]*?#\}/g, " ") if (!/\bselect\b/i.test(outsideJinja)) return false if (oldSql === undefined) return true // Read through `config(**cfg)` splats, as the config lint did. const materialized = (sql: string) => MATERIALIZED.exec(inlineConfigSplats(sql))?.[1]?.toLowerCase() const sameMaterialization = materialized(oldSql) === materialized(newSql) return !(sameMaterialization && !/\bis_incremental\s*\(/.test(oldSql)) } /** * A `unique_key` change moves the merge grain, except under microbatch (which replaces by * `event_time` batch and ignores `unique_key`) and when the only added key columns are the * model's partition columns (a coarser column derived from the row, added for pruning). */ function changesMergeGrain(message: string, newSql: string, oldSql: string | undefined): boolean { if (MICROBATCH.test(newSql) || (oldSql && MICROBATCH.test(oldSql))) return false const m = /\[([^\]]*)\]\s*→\s*\[([^\]]*)\]/.exec(message) if (!m) return true const cols = (s: string) => s.split(",").map((c) => c.trim().toLowerCase()).filter(Boolean) const before = cols(m[1]) const after = cols(m[2]) const added = after.filter((c) => !before.includes(c)) if (!before.length || !before.every((c) => after.includes(c)) || !added.length) return true const partition = new Set(partitionColumns(inlineConfig(inlineConfigSplats(newSql)).partition_by)) // Only an immutable date/event partition column keeps the grain: a row's `updated_at` or // sync time changes, so merging on it inserts a new row per change. return !added.every((c) => partition.has(c) && !MUTABLE_TIME_COLUMN.test(c)) } /** * The changed files' unchanged dbt parents, read at head, for the AI lane's * cross-file checks: an upstream model's columns, a seed's rows, a macro's * signature. Manifest paths are project-relative; changed paths may carry a * prefix (review run from the repo root), which is reapplied to the parents. */ type RunnerFailure = ReturnType>[number] /** The files the AI lane sends: its file cap, or the per-kind quotas in coverage mode. */ function aiLaneFiles(files: AiReviewFile[], switches?: Partial): AiReviewFile[] { const budget = aiInputBudget(process.env, switches) return budget.coverage ? selectAiFilesByQuota(files, budget.coverage.quotas, budget.coverage).sent : selectAiFiles(files, budget.maxFiles) } /** Engine failures recorded so far, by method. */ function engineFailureCounts(runner: ReviewRunner): Map { return new Map((runner.failures?.() ?? []).map((f) => [f.method, f.count])) } /** Failures recorded between two snapshots, by method. */ function engineFailureDelta(before: Map, after: Map): Map { const out = new Map() for (const [method, n] of after) if (n > (before.get(method) ?? 0)) out.set(method, n - (before.get(method) ?? 0)) return out } /** Engine failures without those the advisory AI lane caused. */ function withoutAiFailures(all: RunnerFailure[], ai: Map): RunnerFailure[] { return all.flatMap((f) => { const count = f.count - (ai.get(f.method) ?? 0) return count > 0 ? [{ ...f, count }] : [] }) } /** An unchanged seed as graph context: its header and how many data rows were left out. */ function seedSummary(content: string): string { const [header = "", ...rows] = content.replace(/\n$/, "").split("\n") const n = rows.filter((r) => r.trim()).length return `${header}\n(${n} data row(s) not sent)` } /** Why a file's content never reaches the AI provider (`ai.notSentReasons`). */ export type NotSentReason = "symlink" | "credential_name" | "key_material" export interface AiScreen { /** Every path whose content may never be sent: each withheld file, and the old path of a withheld rename. */ readonly blocked: ReadonlySet /** Withheld files (changed files the lane would send, graph parents) by path, with the reason. */ readonly reasons: ReadonlyMap /** Whether a path is a symlink or under one (cached; a failed check counts as one). */ symlink(path: string): Promise /** Whether a file may be sent: decided from its name and link first, then from its text * (read only when the name and link allow it). A withheld file is recorded. */ allow(f: { path: string; oldPath?: string }, texts?: () => Promise>): Promise /** The same decision for a path the lane does not send (a verifier read, a search hit); nothing is recorded. */ pathOk(path: string, text?: string): Promise } /** * The one decision on what may reach the AI provider, applied at every exit: the finder's files * and focused batches, related files (graph context), compiled SQL, every verifier tool, the rule * verifier and replay (which read the same evidence). Never sent: a path that is a symlink or sits * under one (working tree: the read follows it, and dbt compiled through it; git ref: tree mode * 120000), a credential name on the new or the old path, or text holding key material. */ export function aiScreen(isSymlink?: (path: string) => Promise): AiScreen { const blocked = new Set() const reasons = new Map() const links = new Map>() const symlink = (path: string) => { if (!isSymlink) return Promise.resolve(false) let hit = links.get(path) if (!hit) { hit = isSymlink(path).catch(() => true) links.set(path, hit) } return hit } const named = (f: { path: string; oldPath?: string }) => mayHoldCredentials(f.path) || (!!f.oldPath && mayHoldCredentials(f.oldPath)) return { blocked, reasons, symlink, async allow(f, texts) { let reason: NotSentReason | undefined = reasons.get(f.path) if (!reason && named(f)) reason = "credential_name" if (!reason && (await symlink(f.path))) reason = "symlink" if (!reason && texts && (await texts()).some((t) => holdsCredentials(t))) reason = "key_material" if (!reason) return !blocked.has(f.path) if (!reasons.has(f.path)) reasons.set(f.path, reason) blocked.add(f.path) if (f.oldPath) blocked.add(f.oldPath) return false }, async pathOk(path, text) { return !blocked.has(path) && !mayHoldCredentials(path) && !(await symlink(path)) && !holdsCredentials(text) }, } } async function aiGraphContext( paths: string[], runner: ReviewRunner, getContent: OrchestrateInput["getContent"], screen: AiScreen, ): Promise { if (!runner.graphParents || !getContent || !paths.length) return undefined try { const parents = await runner.graphParents(paths) const out: AiContextFile[] = [] for (const p of parents) { if (p.kind === "source") { if (!p.columns?.length) continue out.push({ path: p.path, kind: p.kind, name: p.name, forPaths: p.forPaths, content: `columns: ${p.columns.join(", ")}` }) continue } // A parent goes through the same screen as a changed file (name, link, then key material). let content: string | undefined const ok = await screen.allow({ path: p.path }, async () => { content = await getContent(p.path, "new").catch(() => undefined) return [content] }) if (!ok || !content) continue // A seed's rows can be personal data: its header and row count only, as for a changed seed. const seed = p.kind === "seed" || /\.csv$/i.test(p.path) out.push({ path: p.path, kind: p.kind, name: p.name, forPaths: p.forPaths, content: seed ? seedSummary(content) : content }) } return out } catch { // Context is an enrichment: without it the lane reviews the changed files alone. return undefined } } /** * dbt CONFIG lint — runs the core dbt-config parser (minijinja) over the RAW model * (the `{{ config() }}` block + body) and emits the config/Jinja findings: incremental * guard / unique_key, microbatch lookback, enforced-contract on_table_exists, * var-without-default, and materialization change (vs base). This replaces the regex * dbt-patterns config detectors — the parsing now lives in core. */ async function dbtConfigLane(ctx: ModelContext, runner: ReviewRunner, projectVars: Set = new Set()): Promise { if (!runner.dbtConfigLint) return [] const { file, newSql, oldSql } = ctx if (!newSql || file.status === "deleted") return [] const model = modelNameFromPath(file.path) const raw = await runner.dbtConfigLint(inlineConfigSplats(newSql), hasOldSide(file) && oldSql ? inlineConfigSplats(oldSql) : undefined) const out: Finding[] = [] for (const f of raw) { // A var defined in dbt_project.yml, or given a default elsewhere in the model, compiles fine. if (f.rule === "var_no_default") { const name = /var\(\s*['"]([^'"]+)['"]/.exec(f.message)?.[1] const esc = name?.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") if (name && (projectVars.has(name) || new RegExp(`var\\(\\s*['"]${esc}['"]\\s*,`).test(newSql))) continue } if (f.rule === "incremental_no_guard" && !introducesUnguardedIncremental(newSql, hasOldSide(file) ? oldSql : undefined)) continue if (f.rule === "unique_key_change" && !changesMergeGrain(f.message, newSql, hasOldSide(file) ? oldSql : undefined)) continue const cat: ReviewCategory = /var_no_default|microbatch|incremental|materialization/.test(f.rule) ? "materialization" : /contract/.test(f.rule) ? "contract_violation" : "sql_correctness" const isError = f.severity === "error" let sev: Severity = isError ? "warning" : "suggestion" if (isError && cat === "contract_violation") sev = "critical" sev = clampSeverity(cat, sev, "high") out.push( makeFinding({ severity: sev, category: cat, title: `${model}: ${f.rule.replace(/_/g, " ")}`, body: f.message + (f.suggestion ? `\n\n${f.suggestion}` : ""), file: file.path, model, confidence: "high", evidence: { tool: "altimate_core.dbt_config", result: { code: f.code, rule: f.rule } }, ruleKey: `${cat}:dbt-config:${f.code}`, }), ) } return out } /** * A new LEFT JOIN onto a model whose declared uniqueness tests don't cover the * join key: the joined model has stated its grain and the join ignores it (an * SCD2 dimension joined without `is_current`, a natural key instead of the * declared one), so a repeated key multiplies the left rows. Inner joins are * skipped, since they are often one-to-many on purpose, as are models with no * declared key, where nothing says what one row means. */ async function joinKeyUniquenessLane(ctx: ModelContext, runner: ReviewRunner): Promise { if (!runner.declaredUniqueKeys || !runner.modelConfig || !ctx.newSql || ctx.file.status === "deleted") return [] const added = (ctx.file.diff ?? "").split("\n").filter((l) => l.startsWith("+") && !l.startsWith("+++")).map((l) => l.slice(1)) const out: Finding[] = [] const model = modelNameFromPath(ctx.file.path) // The base's joins, matched by joined model, LEFT-ness and key set: a join the PR only // reformats or moves is not new. const before = ctx.oldSql ? joinTargets(ctx.oldSql, ctx.oldSql.split("\n")) : [] const sameJoin = (a: JoinTarget, b: JoinTarget) => a.model === b.model && a.left === b.left && a.keys.length === b.keys.length && a.keys.every((k) => b.keys.includes(k)) for (const t of joinTargets(ctx.newSql, added)) { // Unknown to the manifest (a package model, a typo): nothing to compare against. if (!t.left || !(await runner.modelConfig(t.model))) continue // Joined rows aggregated back to the left side's grain: the fan-out is the intent. if (t.aggregated || before.some((b) => sameJoin(b, t))) continue const declared = (await runner.declaredUniqueKeys(t.model)).filter((k) => k.length) if (!declared.length || declared.some((k) => k.every((c) => t.keys.includes(c.toLowerCase())))) continue out.push( makeFinding({ severity: "suggestion", category: "fanout", title: `${model}: LEFT JOIN key on ${inlineCode(t.model)} isn't its declared unique key`, body: `This LEFT JOIN matches ${inlineCode(t.model)} on [${ticks(t.keys)}], but its uniqueness tests cover ` + `${declared.map((k) => `[${ticks(k)}]`).join(", ")}, which the join doesn't fully constrain.` + ` If a key repeats there, this join multiplies rows. Add a \`unique\` / \`unique_combination_of_columns\` test on the join key, or join on the declared key.`, file: ctx.file.path, model, confidence: "medium", evidence: { tool: "dbt.manifest", result: { joined: t.model, keys: t.keys, declared } }, ruleKey: `fanout:join-key-untested:${t.model}`, rule: "dbt.manifest:left-join-key-not-unique", }), ) } return out } const TIME_PARTITION_COLUMN = /(^|_)(date|day|week|month|quarter|year|period|hour|ts|time|timestamp)(_|$)|_at$/i const HASH_FN = /\b(?:dbt_utils\.)?(?:generate_surrogate_key|surrogate_key|md5|sha1|sha2|sha256|sha512|hash|farm_fingerprint)\s*\(/gi /** Words in a hash's argument text that are not column names. */ const HASH_ARG_WORDS = new Set( "as cast try_cast safe_cast varchar nvarchar char string text int integer bigint smallint int64 number numeric decimal float float64 double real bool boolean date timestamp coalesce ifnull nvl concat concat_ws to_varchar to_char lower upper trim null and or case when then else end is not".split(" "), ) /** The column names a hash reads: the quoted list of `generate_surrogate_key(['a', 'b'])`, * or the bare column references of `md5(a || '-' || cast(b as varchar))`. Undefined when * that cannot be told: a list item that is not a plain (optionally qualified) column name, * or a surrogate-key macro given something other than a literal list (a Jinja variable). */ function hashInputs(fn: string, args: string): Set | undefined { const list = /^\s*\[([\s\S]*)\]\s*$/.exec(args) if (list) { const items = list[1].split(",").map((i) => i.trim()).filter(Boolean) const names = items.map((i) => /^(['"])((?:\w+\.)?\w+)\1$/.exec(i)?.[2]) if (!names.length || names.some((n) => !n)) return undefined return new Set(names.map((n) => n!.toLowerCase().replace(/^.*\./, ""))) } if (/surrogate_key/i.test(fn)) return undefined const plain = args.replace(/'(?:[^']|'')*'/g, " ") return new Set( [...plain.matchAll(/(? m[1].toLowerCase()).filter((w) => !HASH_ARG_WORDS.has(w)), ) } /** True when the model computes `column` as one hash of exactly `keyColumns`, or as a hash * whose inputs cannot be told * (`{{ dbt_utils.generate_surrogate_key(['a', 'b']) }} as order_sk`, `md5(a || b) as order_sk`). * A hash of more columns (an `updated_at`) or fewer is a different key. */ function hashedSurrogateOf(sql: string, column: string, keyColumns: string[]): boolean { const key = new Set(keyColumns.map((c) => c.toLowerCase())) for (const m of sql.matchAll(HASH_FN)) { const open = m.index! + m[0].length - 1 const args = parenBody(sql, open) const after = sql.slice(open + args.length + 2) if (!new RegExp(String.raw`^\s*(?:\}\}\s*)?(?:as\s+)?["\x60]?${column.replace(/\W/g, "")}["\x60]?(?!\w)`, "i").test(after)) continue const inputs = hashInputs(m[0], args) // Inputs that cannot be told: no suggestion rather than a guess. if (!inputs) return true if (inputs.size === key.size && [...key].every((c) => inputs.has(c))) return true } return false } /** * An incremental merge key that differs from every uniqueness test on the model: * one of the two may be wrong. Advice only (a suggestion, never verdict-eligible): * the manifest cannot tell which side is intended. Reported when the PR touches * the model's own config (or adds the model) or its own yml, only for a strategy * that matches on `unique_key` (merge, delete+insert; unset = the adapter's * keyed default), and not for a single hashed surrogate of the tested columns. * * `ownYmlChanged`: whether a schema yml in the PR declares this model. */ async function uniqueKeyMismatchLane( ctx: ModelContext, runner: ReviewRunner, dialect: string, ownYmlChanged: (model: string) => boolean, ): Promise { if (!runner.modelConfig || !runner.declaredUniqueKeys || ctx.file.status === "deleted") return [] const model = modelNameFromPath(ctx.file.path) // A long-standing mismatch is not re-reported on every edit to the model. const configTouched = splitDiff(ctx.file.diff).added.some((l) => /\b(unique_key|materialized|incremental_strategy)\b/i.test(l)) if (!configTouched && ctx.file.status !== "added" && !ownYmlChanged(model)) return [] const cfg = await runner.modelConfig(model) if (cfg?.materialized !== "incremental" || !cfg.unique_key) return [] const uk = (Array.isArray(cfg.unique_key) ? cfg.unique_key : String(cfg.unique_key).split(",")) .map((c) => String(c).trim().toLowerCase()) .filter(Boolean) const strategy = String(cfg.incremental_strategy ?? "").toLowerCase() || (uk.length ? capabilityFor(dialect)?.keyedDefaultStrategy : undefined) if (strategy !== "merge" && strategy !== "delete+insert") return [] const declared = await runner.declaredUniqueKeys(model) if (!uk.length || !declared.length) return [] const same = (k: string[]) => k.length === uk.length && k.every((c) => uk.includes(c.toLowerCase())) if (declared.some(same)) return [] // A merge key that is a declared key plus date/partition columns (`block_month`, // `effective_date`) is the common pruning pattern; those columns don't change which rows match. const timeOnlyExtra = (k: string[]) => { const lk = k.map((c) => c.toLowerCase()) return lk.every((c) => uk.includes(c)) && uk.filter((c) => !lk.includes(c)).every((c) => TIME_PARTITION_COLUMN.test(c)) } if (declared.some(timeOnlyExtra)) return [] // One hashed surrogate of a tested column set is that key in another form. const sql = ctx.newSql ?? "" if (uk.length === 1 && declared.some((k) => hashedSurrogateOf(sql, uk[0], k))) return [] const tests = declared.map((k) => `[${ticks(k)}]`).join(", ") return [ makeFinding({ severity: "suggestion", category: "materialization", title: `${model}: incremental unique_key differs from the declared uniqueness test`, body: `${inlineCode(model)} merges on \`unique_key\` [${ticks(uk)}], but its uniqueness test${declared.length > 1 ? "s declare" : " declares"} ${tests}. ` + `If the merge key is right the test fails as soon as two rows share the test key; if the test is right the merge collapses or duplicates rows. Check they describe the same grain.`, file: ctx.file.path, model, confidence: "medium", // Not engine evidence: the comparison is advice and never counts toward the verdict. evidence: { tool: "dbt-project-rules", result: { rule: "unique-key-test-mismatch", unique_key: uk, declared, strategy } }, ruleKey: "materialization:unique-key-test-mismatch", rule: "dbt.manifest:unique-key-differs-from-test", }), ] } /** * STRUCTURAL base-vs-head diff — the `*_change` SQL rules (DISTINCT/UNION flip, * GROUP BY grain shift, surrogate-key change, COALESCE removed, predicate * removed, type narrowing). These moved off diff-LINE regex onto a core AST * comparison (`structural_diff`): it parses BOTH versions, so it no longer * mistakes a moved line for a change or an ON-clause `and` for a WHERE. Cheap * and schema-free, so it runs at every tier the regex twins used to. */ const STRUCTURAL_CATEGORY: Record = { distinct_added: "semantic_change", distinct_removed: "semantic_change", union_all_to_union: "warehouse_cost", union_to_union_all: "sql_correctness", group_by_change: "semantic_change", surrogate_key_change: "dedup", coalesce_removed: "semantic_change", removed_predicate: "semantic_change", type_narrowing: "contract_violation", join_key_regression: "join_risk", } // PII classification thresholds for the diff-scoped lane. Names/addresses are // common, lower-sensitivity PII that the broad name-pattern detector over-flags, // so the precise lane requires higher confidence before surfacing them. Kept a // named constant (not a magic number) and deliberately narrow: broadening the // low-risk set to variants would suppress MORE real columns, hurting recall. const PII_LOW_RISK_CLASS = /^(name|address)$/i const PII_LOW_RISK_MIN_CONFIDENCE = 0.9 const PII_DEFAULT_MIN_CONFIDENCE = 0.7 async function structuralChangeLane(ctx: ModelContext, runner: ReviewRunner): Promise { if (!runner.structuralDiff) return [] // Use the ENGINE (compiled) SQL — structural_diff parses with a real SQL parser, // so raw Jinja (`{{ ref() }}`) would fail to parse and the lane would silently // return nothing. engineOldSql/engineNewSql fall back to raw only when it holds no Jinja. const { file, engineNewSql, engineOldSql } = ctx if (!hasOldSide(file) || !engineNewSql || !engineOldSql || engineNewSql.trim() === engineOldSql.trim()) return [] const model = modelNameFromPath(file.path) const raw = await runner.structuralDiff(engineOldSql, engineNewSql) const out: Finding[] = [] for (const f of raw) { const cat: ReviewCategory = STRUCTURAL_CATEGORY[f.rule] ?? "semantic_change" // Only `join_risk` (SC010 join-key regression) is allowed to block: a changed // join key silently corrupts row sets. Other structural rules core marks // `error` stay advisory (warning) so this lane never over-blocks on a rule // it wasn't designed to gate. const sev = clampSeverity(cat, cat === "join_risk" && f.severity === "error" ? "critical" : "warning", "high") out.push( makeFinding({ severity: sev, category: cat, title: `${model}: ${f.rule.replace(/_/g, " ")}`, body: f.message + (f.suggestion ? `\n\n${f.suggestion}` : ""), file: file.path, model, confidence: "high", evidence: { tool: "altimate_core.structural_diff", result: { code: f.code, rule: f.rule } }, ruleKey: `${cat}:structural:${f.code}`, }), ) } return out } /** * CROSS-MODEL SIBLING CONSISTENCY — when two+ changed models read the SAME * upstream but filter it differently, one is likely missing a guard the others * apply (ingestion `d1fe5cf`: one of three sibling loaders lacked a NULL filter → * 23.7k leaked rows). Per-upstream filter columns come from the core AST * (`source_filters`); this PR-level lane compares them. Advisory (siblings may * legitimately differ), so it surfaces the divergence to confirm, never blocks. */ async function siblingConsistencyLane(ctxs: ModelContext[], runner: ReviewRunner): Promise { if (!runner.sourceFilters) return [] const perModel: Array<{ model: string; file: string; filters: Map> }> = [] for (const ctx of ctxs) { if (!ctx.engineNewSql || ctx.file.status === "deleted") continue const sf = await runner.sourceFilters(ctx.engineNewSql) const filters = new Map>() for (const [u, cols] of Object.entries(sf)) filters.set(u, new Set(cols.map((c) => c.toLowerCase()))) if (filters.size) perModel.push({ model: modelNameFromPath(ctx.file.path), file: ctx.file.path, filters }) } if (perModel.length < 2) return [] // upstream → sibling models that read it (within this PR). const byUpstream = new Map() for (const pm of perModel) { for (const u of pm.filters.keys()) { if (!byUpstream.has(u)) byUpstream.set(u, []) byUpstream.get(u)!.push(pm) } } const out: Finding[] = [] const seen = new Set() for (const [u, models] of byUpstream) { if (models.length < 2) continue const union = new Set() for (const m of models) for (const c of m.filters.get(u) ?? []) union.add(c) for (const m of models) { const mine = m.filters.get(u) ?? new Set() const missing = [...union].filter((c) => !mine.has(c)) if (!missing.length) continue const key = `${m.file}|${u}` if (seen.has(key)) continue seen.add(key) const others = models.filter((x) => x.file !== m.file).map((x) => inlineCode(x.model)) out.push( makeFinding({ severity: clampSeverity("sql_correctness", "warning", "medium"), category: "sql_correctness", title: `${m.model}: filters ${inlineCode(u)} differently from sibling model(s)`, body: `${inlineCode(m.model)} reads ${inlineCode(u)} but does not filter it on [${missing.join(", ")}], while sibling ` + `model(s) ${others.join(", ")} (also reading ${inlineCode(u)} in this PR) do. A missing row filter silently ` + `leaks rows. Confirm the difference is intentional, or apply the same predicate.`, file: m.file, model: m.model, confidence: "medium", evidence: { tool: "altimate_core.source_filters", result: { upstream: u, missing } }, ruleKey: `sql_correctness:sibling-filter:${u}`, rule: "altimate-core.source-filters:sibling-mismatch", }), ) } } return out } /** * PII exposure via core's `classify_pii` — flags columns the change INTRODUCES * that classify as PII (Email/SSN/…), with the masking suggestion. Diff-scoped: * only NEW PII (a column whose name appears in the added diff), so it never nags * about pre-existing PII columns the PR didn't touch. */ async function piiClassifyLane( ctx: ModelContext, runner: ReviewRunner, dialect: string, /** The file's raw base as `rawBaseCode` reads it, parsed once per file. */ baseLacks: (column: string) => boolean, /** The PII check could not analyse the compiled base. */ baseAbstained = false, ): Promise<{ findings: Finding[]; classifiedColumns: Set; completed: boolean }> { const empty = { findings: [], classifiedColumns: new Set(), completed: false } if (!runner.classifyPii) return empty const { file, engineNewSql } = ctx if (!engineNewSql || file.status === "deleted") return empty const model = modelNameFromPath(file.path) if (!runner.columnLineage) return empty // Output columns the change INTRODUCED = head targets − base targets (precise; // a pre-existing column merely mentioned in the diff is NOT counted). let newCols: string[] // A compiled base whose lineage resolves no output column (it did not // parse) says nothing about which head columns already existed. let baseUnresolved = false try { const headCols = [...new Set((await runner.columnLineage(engineNewSql, dialect)).map((e) => e.target).filter(Boolean))] // Zero head targets means lineage could NOT resolve this model's output // columns — the classifier considered nothing, so this is uncertainty, not a // confident "no new PII". Returning `completed: false` keeps the deterministic // regex fallback alive (vs. the `!newCols.length` case below, where lineage // DID resolve columns but none are newly introduced — that is genuinely done). if (!headCols.length) return empty const baseCols = ctx.engineOldSql ? new Set((await runner.columnLineage(ctx.engineOldSql, dialect)).map((e) => e.target.toLowerCase())) : undefined baseUnresolved = baseCols !== undefined && baseCols.size === 0 newCols = baseCols ? headCols.filter((c) => !baseCols.has(c.toLowerCase())) : headCols } catch { return empty } if (!newCols.length) return { findings: [], classifiedColumns: new Set(), completed: true } let pii try { pii = await runner.classifyPii(newCols) } catch { return empty } // Columns core's classifier actually CONSIDERED (returned a verdict for), even // if below threshold. The broad fallback and the regex twins dedup against THIS // set — not all introduced columns — so a column core simply MISSED (never // classified) stays eligible for the broad name-pattern detector instead of // being silently dropped. const classifiedColumns = new Set(pii.map((p) => String(p.column ?? "").toLowerCase()).filter(Boolean)) const out: Finding[] = [] // "Exposure" severity only escalates for published/broadly-read layers // (marts/reporting). This is intentionally narrower than where grain tests // apply (`missingGrainTestLane` also includes `intermediate`): an internal // intermediate model surfacing PII is a warning, not a hard block. const highExposureLayer = /(^|\/)(marts|reporting)\//.test(file.path) // Without a compiled base, every head column counts as "introduced", so a // pre-existing column can't be told apart: never escalate to critical then, // unless the raw base provably lacks the output (`baseLacks`: it cannot have exposed it). const baseUnknown = hasOldSide(file) && !ctx.engineOldSql // A base whose lineage resolved no column leaves every column undecided (a // warning that never blocks). A base whose PII pass abstained may have had // only part of its lineage resolved, so a column missing from that lineage is // not proved new: the raw base decides, as for a base without compiled SQL. // A column the raw base never mentions is new. for (const p of pii) { const classification = String(p.classification ?? "") const lowRiskClass = PII_LOW_RISK_CLASS.test(classification) const minConfidence = lowRiskClass ? PII_LOW_RISK_MIN_CONFIDENCE : PII_DEFAULT_MIN_CONFIDENCE if (p.confidence < minConfidence || !p.column) continue const col = p.column.toLowerCase() const unanalysed = baseUnresolved || (baseAbstained && !baseLacks(col)) const undecided = unanalysed || (baseUnknown && !baseLacks(col)) const highConfidence = p.confidence >= 0.9 const severity: Severity = highExposureLayer && highConfidence && !lowRiskClass && !undecided ? "critical" : "warning" out.push( makeFinding({ severity: clampSeverity("pii_exposure", severity, highConfidence ? "high" : "medium"), category: "pii_exposure", title: `${model}: exposes ${p.classification} column ${inlineCode(p.column)}`, body: `This change surfaces a **${p.classification}**-classified column ${inlineCode(p.column)} ` + `(confidence ${(p.confidence * 100).toFixed(0)}%). Confirm masking / access policy before merging to a non-restricted schema` + (p.masking ? `; suggested masking: ${inlineCode(p.masking)}.` : ".") + (unanalysed ? PII_UNDECIDED_BASE_UNANALYSED : ""), file: file.path, model, // Without a base, exposure is undecided: `unknown` keeps these warnings // out of the warning-pattern count, so they never block. confidence: undecided ? "unknown" : highConfidence ? "high" : "medium", evidence: { tool: "altimate_core.classify_pii", result: p }, ruleKey: `pii_exposure:${col}`, rule: "altimate-core.classify-pii:exposes", }), ) } return { findings: out, classifiedColumns, completed: true } } /** `undecided(column)`: the file had a previous version but its base SQL could * not be compiled and its raw code does not prove the column absent, so the * column may predate the PR. Those are reported as a warning (never blocking) * instead of a critical "newly exposed" finding. */ function piiLane( file: ChangedFile & { kind: string }, columns: string[], undecided: (column: string) => boolean = () => false, undecidedWhy: string = PII_UNDECIDED_BASE_UNKNOWN, ): Finding[] { if (file.status === "deleted" || !columns.length) return [] const provenColumns = columns.filter((c) => !undecided(c)) const undecidedColumns = columns.filter((c) => undecided(c)) return [ ...piiLaneFinding(file, provenColumns, false, "pii:exposure"), // Its own key when beside a proven finding: findings with one fingerprint // are merged into one. The finding has no line, so it is never an inline // comment and no later run matches it by fingerprint. ...piiLaneFinding( file, undecidedColumns, true, provenColumns.length ? "pii:exposure:undecided" : "pii:exposure", undecidedWhy, ), ] } /** Why an undecided PII column may predate the PR, appended to its finding. */ const PII_UNDECIDED_BASE_UNKNOWN = " These columns may already be exposed before this PR: the base version could not be compiled, or it read a table under another schema that the model's code does not explain." const PII_UNDECIDED_BASE_UNANALYSED = " The base model could not be analysed, so whether this column is new could not be decided." function piiLaneFinding( file: ChangedFile & { kind: string }, columns: string[], undecided: boolean, ruleKey: string, undecidedWhy: string = PII_UNDECIDED_BASE_UNKNOWN, ): Finding[] { if (!columns.length) return [] const model = modelNameFromPath(file.path) return [ makeFinding({ severity: undecided ? "warning" : "critical", category: "pii_exposure", title: `${model}: exposes PII column${columns.length !== 1 ? "s" : ""} (${columns.join(", ")})`, body: `This model surfaces PII-classified column(s): ${ticks(columns)}.` + ` Confirm masking/access policy before merging to a non-restricted schema.` + (undecided ? undecidedWhy : ""), file: file.path, model, // `unknown`: undecided exposure never counts toward the warning pattern. confidence: undecided ? "unknown" : "high", evidence: { tool: "schema.detect_pii", result: { columns } }, ruleKey, rule: "schema.detect-pii:exposes", }), ] } /** * Run the full review and return a signed verdict envelope. */ interface ModelContext { file: ChangedFile & { kind: string } impact: ImpactResult pii: string[] /** RAW Jinja SQL (for the dbt-patterns lane + the diff). */ newSql?: string oldSql?: string /** dbt-COMPILED SQL (preferred) for the engine lanes; falls back to raw. */ engineNewSql?: string engineOldSql?: string /** Structurally complex change (window/subquery/large plan) — a tiering signal. */ complex?: boolean } /** * The raw (uncompiled) base cannot expose any of the source columns `names`: * none appears in it as a word outside comments, no select item reads a `*`, its * only Jinja expressions are `ref`, `source`, `config` or `this`, and its only * Jinja statements are control flow (`if`/`for`/`set` and their ends), which * emit no text of their own. A macro (`dbt_utils.star(…)`), a variable, a * `{{ col }}` loop, an `{% include %}` or a `{% call %}` block could emit any * column, so any other tag proves nothing. String literals still count as * evidence: a JSON path (`payload:ssn`, `'$.ssn'`) can expose the column. * A `*` is any `*` token not preceded by a word (`*`, `c.*`, `*except(email)`, * `as struct *`, `object_construct(*)`, `* like 'e%'`); `count(*)` reads no * column. Spaced multiplication (`a * b`) also matches, which only leaves the * base undecided. A DuckDB `COLUMNS(…)` selector picks columns by a pattern or * a lambda (`COLUMNS('^e')`), so it counts like a `*`. */ const RAW_BASE_PLAIN_EXPR = /^\{\{-?\s*(?:(?:ref|source|config)\s*\([^{}]*\)|this)\s*-?\}\}$/ const RAW_BASE_STAR = /(?:^|[\s.(])\*(?=\s|$|[a-z(),])|(? RAW_BASE_PLAIN_EXPR.test(e))) return undefined if (!(oldSql.match(/\{%[\s\S]*?%\}/g) ?? []).every((t) => SILENT_JINJA_TAG.test(t))) return undefined const texts = rawBaseTexts(oldSql) if (!texts) return undefined const { code, readable } = texts // Only the final query's own select lists can prove a column absent: a CTE's // list does not (`with u as (select id from c) table c`), nor a final query // without one, nor a whole row or a struct expansion (`select c`, `unnest(s)`). // The base must be read fully. if (!explicitProjection(readable)) return undefined // A Unicode-escaped name (`U&"e\006Dail"` is `email`) is not searched as written. if (/(? RAW_BASE_STAR.test(i.text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ")))) return undefined return code } function rawBaseLacks(code: string | undefined, names: string[]): boolean { if (code === undefined || !names.length) return false return names.every((n) => !new RegExp(`(? { if (!/\.ya?ml$/i.test(file.path) || classifyDbtFile(file.path, layout) === "project_config") return false const read = (path: string, side: "old" | "new") => Promise.resolve(getContent?.(path, side)).catch(() => undefined) const contents = ( await Promise.all([ file.status !== "deleted" ? read(file.path, "new") : undefined, file.status !== "added" ? read(file.oldPath ?? file.path, "old") : undefined, ]) ).filter((c): c is string => !!c?.trim()) const declaresSources = contents.some((c) => /^["']?sources["']?\s*:/m.test(c)) || looksLikeSourceYml(file.diff) if (contents.length && !declaresSources) return false if (file.status === "deleted" || !file.diff?.trim()) return true // A key whose line changed only in its trailing comment or spacing did not move. const keyLines = file.diff.split("\n").filter((line) => !/^(?:\+\+\+|---)(?:\s|$)/.test(line) && SOURCE_KEY_EDIT.test(line)) const written = (sign: string) => keyLines .filter((line) => line.startsWith(sign)) .map((line) => line.slice(1).replace(/\s+#.*$/, "").trim()) .sort() .join("\n") return keyLines.length > 0 && written("-") !== written("+") } /** Names of the engine checks in a parse-abstention reason. */ const ABSTAIN_CHECK_NAME: Record = { check: "SQL", structuralDiff: "structural diff", dbtConfigDiff: "dbt config diff", dbtConfigLint: "dbt config lint", columnLineage: "column lineage", lexicalScan: "lexical scan", grain: "grain", sourceFilters: "source filter", equivalence: "equivalence", } const abstainReason = (method: string) => `the ${ABSTAIN_CHECK_NAME[method] ?? method} check could not parse the SQL` /** The rule verifier's record as the envelope keeps it: a fixed reason per state, model text * through `inertEvidence`, known fields only. */ function publicRuleVerifier(rv: RuleVerifierStatus, candidates: number, engineFailures: number): RuleVerifierStatus { const count = (n: unknown) => (typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0) const state = (["ok", "skipped", "timeout", "error", "budget"] as const).find((s) => s === rv?.state) ?? "error" const reason = { ok: undefined, budget: "the budget left some batches no tool round; their findings are posted unverified", timeout: rv?.reason === RULE_VERIFIER_DEADLINE ? RULE_VERIFIER_DEADLINE : "the rule verifier timed out; rule findings are shown unverified", error: "the rule verifier failed; rule findings are shown unverified. See the job log.", skipped: "the rule verifier did not run; rule findings are shown unverified", }[state] const verdicts = Array.isArray(rv?.verdicts) ? rv.verdicts.map((v) => ({ id: String(v.id), file: String(v.file ?? ""), ...(typeof v.rule === "string" ? { rule: v.rule } : {}), verdict: (["confirmed", "refuted", "unverifiable"] as const).find((x) => x === v.verdict) ?? null, evidence: inertEvidence(String(v.evidence ?? "")), toolsUsed: (Array.isArray(v.toolsUsed) ? v.toolsUsed : []).filter((t): t is string => typeof t === "string" && /^[a-z_]{2,40}$/.test(t)), ...(typeof v.batch === "number" && v.batch >= 0 ? { batch: Math.floor(v.batch) } : {}), grounded: v.grounded === true, })) : undefined const toolErrors = count(rv?.toolErrors) + engineFailures return { state, ...(reason ? { reason } : {}), ...(typeof rv?.model === "string" ? { model: rv.model } : {}), durationMs: count(rv?.durationMs), ...(rv?.tokens ? { tokens: rv.tokens } : {}), ...(typeof rv?.cost === "number" && rv.cost >= 0 ? { cost: rv.cost } : {}), turns: count(rv?.turns), toolCalls: count(rv?.toolCalls), ...(toolErrors ? { toolErrors } : {}), candidates, sent: Math.min(count(rv?.sent), candidates), reviewed: Math.min(count(rv?.reviewed), candidates), withheld: 0, ...(verdicts ? { verdicts } : {}), ...(Array.isArray(rv?.batches) ? { batches: rv.batches } : {}), } } /** Why the rule verifier did not run when the AI lane did not answer (fixed text). */ export const RULE_VERIFIER_NOT_RUN = "the AI review did not answer, so the rule verifier did not run" /** Why the rule verifier stopped at the lane deadline (fixed text). */ export const RULE_VERIFIER_DEADLINE = "the rule verifier ran out of time at the AI review's deadline" export async function runReview(input: OrchestrateInput): Promise { const { reviewable, dropped } = partitionChangedFiles( input.changedFiles, input.rubric.exclusions.excludeGlobs, input.layout, ) // Files some lane received (the coverage ledger lists the rest). const touched = new Set() const touch = (files: Array<{ path: string }>) => { for (const f of files) touched.add(f.path) } const dialect = input.config.dialect const getContent = input.getContent const getCompiled = input.getCompiled // Pre-compute every engine result ONCE per model file: blast radius (for // tiering + lineage), PII columns (hard-floor → must precede tiering), and // both SQL sides. This avoids duplicate engine calls and lets tiering see PII. const modelFiles = reviewable.filter((f) => f.kind === "model_sql" || f.kind === "python_model") // Every model gets at least the PII check; one that fails is recorded as unverified. touch(modelFiles) const ctxByPath = new Map() const unverified: NonNullable = [] const disabledModels: string[] = [] let anyManifest = false let manifestMissing = false if (input.runner.manifestAvailable) { anyManifest = await input.runner.manifestAvailable().catch(() => false) manifestMissing = !anyManifest } // PR-level lanes (across files) that threw: reported with the engine errors. const laneErrors: Array<{ method: string; reason: string; count: number; category: FailureCategory }> = [] const prLevel = (method: string, lane: Promise) => lane.catch((err) => { laneErrors.push({ method, reason: reportFailure("internal_error", { check: method }, err).message, count: 1, category: "internal_error" }) return [] as Finding[] }) // A file's review threw (`err`), or a side of it could not be read (`side`). const failedFile = (file: { path: string }, err: unknown, side?: "head" | "base") => { const failure = side ? reportFailure("file_unreadable", { path: file.path, side }) : reportFailure("internal_error", { path: file.path }, err) unverified.push({ path: file.path, reason: failure.message, kind: "failed", category: failure.category, }) } await Promise.all( modelFiles.map(async (file) => { try { const model = modelNameFromPath(file.path) // For renames the previous content lives at oldPath, not the new path. const oldRef = file.oldPath ?? file.path const withOld = hasOldSide(file) const [newSql, oldSql, compiledNew, compiledOld] = await Promise.all([ file.status !== "deleted" ? getContent?.(file.path, "new") : Promise.resolve(undefined), withOld ? getContent?.(oldRef, "old") : Promise.resolve(undefined), file.status !== "deleted" ? getCompiled?.(file.path, "new") : Promise.resolve(undefined), withOld ? getCompiled?.(oldRef, "old") : Promise.resolve(undefined), ]) // The content resolvers return undefined on a git or filesystem error. A // side the diff says exists but that could not be read was not reviewed. if (getContent) { if (file.status !== "deleted" && newSql === undefined) failedFile(file, undefined, "head") if (withOld && oldSql === undefined) failedFile(file, undefined, "base") } // Engine lanes need dbt-compiled SQL. Raw SQL is used only when it holds // no Jinja: the AST engine reads `{{ config() }}` as an injection attempt // and a mixed raw-vs-compiled pair can never be proven equivalent, so a // Jinja model without compiled output is marked unverified instead of // producing warnings about its template syntax. The dbt-patterns lane // always uses raw (it needs the Jinja). // A blank compiled file is no SQL at all, on either side. const engineSql = (compiled: string | undefined, raw: string | undefined) => compiled !== undefined ? compiled.trim() ? compiled : undefined : file.kind === "model_sql" && hasJinja(raw) ? undefined : raw const engineNewSql = engineSql(compiledNew, newSql) const engineOldSql = engineSql(compiledOld, oldSql) // A model the manifest marks disabled is listed. dbt does not build it, // so missing compiled SQL is expected and not a gap; every check that // reads its own SQL still runs, since "disabled" comes from the PR's own // manifest and must not let a PR switch off its review. const disabled = file.status !== "deleted" && input.isDisabledModel?.(file.path) === true if (disabled) disabledModels.push(file.path) if (file.status !== "deleted" && newSql && !engineNewSql && !disabled) { unverified.push({ path: file.path, // An empty compiled file is a broken compile, not a missing one. reason: compiledNew !== undefined && !compiledNew.trim() ? "the compiled SQL for the head is empty (re-run dbt compile)" : "no compiled SQL for the head (run dbt compile)", kind: "not_compiled", side: "head", }) } else if (withOld && oldSql && !engineOldSql) unverified.push({ path: file.path, reason: "no compiled SQL for the base (compile the base into target-base)", kind: "not_compiled", side: "base", }) const impact = await input.runner.impact(model) if (impact.hasManifest) anyManifest = true const piiRes = engineNewSql ? await input.runner.detectPii(engineNewSql, dialect) : { columns: [] } // A Python model is not SQL: the SQL PII parser always abstains on it, which // would mark every PR touching one "not fully verified". if (piiRes.abstained && file.kind !== "python_model") unverified.push({ path: file.path, reason: "the PII check could not analyse this model", kind: "abstained" }) const pii = piiRes.columns // Python is not SQL: core cannot tell its complexity. const complex = engineNewSql && file.kind !== "python_model" && input.runner.isComplex ? await input.runner.isComplex(engineNewSql, dialect) : false ctxByPath.set(file.path, { file, impact, pii, newSql, oldSql, engineNewSql, engineOldSql, complex }) } catch (err) { // One file's failure (unreadable content, an engine crash) degrades that // file only; it must not abort the whole review. failedFile(file, err) } }), ) // The map filled in completion order: re-order it by path, so every later lane and the // AI lane's file selection see the same order on every run of the same commit. const settledCtx = [...ctxByPath.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) ctxByPath.clear() for (const [p, ctx] of settledCtx) ctxByPath.set(p, ctx) // A run is degraded when model files exist but none resolved against a manifest. // Nothing to resolve (yml-only, pure moves) is not a lint-only run. const runDegraded = modelFiles.length > 0 && !anyManifest // High-risk path tokens are user-configured (billing/pci/patient/etc.) — // the reviewer core carries no default list. `undefined` when no // categories are configured, which keeps `highRiskPathTokenCategory` // undefined per file and no promotion fires. // // `compilePathTokenResolver` throws on an unknown `preset:` (typo // guard). Catch that here so a single config // typo in `.altimate/review.yml` doesn't crash every review run in the // project's CI — surface the error to stderr AND propagate a // `configError` reason into the envelope so the reader can see what // broke. The review continues with no path-token promotion (the // conservative safe fallback), so users notice their opt-in is dead // rather than getting silent auto-approve on billing/PCI/etc. paths. let pathTokenCategoryOf: ((p: string) => string | undefined) | undefined let pathTokenConfigError: string | undefined try { pathTokenCategoryOf = compilePathTokenResolver(input.config.riskTierPathTokens) } catch (e: any) { pathTokenConfigError = `riskTierPathTokens config invalid: ${e?.message ?? String(e)}` process.stderr.write(`⚠️ ${pathTokenConfigError}\n Review continuing without path-token promotion.\n`) pathTokenCategoryOf = undefined } const tierResult = classifyPR(reviewable, { blastRadiusOf: (p) => { const c = ctxByPath.get(p) return c ? c.impact.directCount + c.impact.transitiveCount : 0 }, touchesPiiOf: (f) => (ctxByPath.get(f.path)?.pii.length ?? 0) > 0, isComplexOf: (f) => ctxByPath.get(f.path)?.complex ?? false, pathTokenCategoryOf, }) // Surface config errors in the tier-reasons stream so a reader of the // envelope (or PR comment) sees WHY their opt-in didn't fire. if (pathTokenConfigError) tierResult.reasons.unshift(pathTokenConfigError) const classifiedTier = tierResult.tier // G2 — --force-tier overrides the classifier. Envelope records both the // forced tier and the original classification whenever the flag is passed // (regardless of whether the forced value happens to match the classifier), // so audits can see the bypass every time the flag was used. The reasons // list gets a leading "forced" marker so downstream doesn't confuse the // forced tier for a natural one. A `!== classifiedTier` gate would hide the // bypass whenever the forced tier matched the classifier's result. const tier = input.forceTier ?? classifiedTier const tierForced = input.forceTier !== undefined // Sorted: the envelope and the comment must not depend on the order the files arrived in. const classifierReasons = [...tierResult.reasons].sort() const tierReasons = tierForced ? [`forced via --force-tier=${input.forceTier} (classifier said ${classifiedTier})`, ...classifierReasons] : classifierReasons const reviewers = knownReviewers(input.config.reviewers).lanes const lanes = new Set(reviewers.length ? reviewers : TIER_LANES[tier]) // The consumer-list check runs with these lanes. A failed list lookup is a // PR-level engine error (the lists it would have found were not checked); an // unusable pattern, and a list the base had that the head no longer yields, // are listed without holding back approval (the policy comes from the base, // so blocking on its pattern would also block the PR that fixes it). // Kept apart from `laneErrors`: a failed read is not a fault in the review's // code, and its category (`file_unreadable`) keeps it from setting // `internalFailure` (`hasInternalFailure`). const listErrors: NonNullable = [] // Engine validations that could not complete: engine errors (not approvable), kept apart // from `laneErrors` for the same reason, so they do not set `internalFailure`. const validationErrors: Array<{ method: string; reason: string; count: number; category: FailureCategory }> = [] if (input.consumerLists && (lanes.has("lineage_breakage") || lanes.has("contract_violation"))) { listErrors.push(...input.consumerLists.errors) for (const reason of input.consumerLists.invalid) unverified.push({ path: REVIEW_POLICY_PATH, reason: `consumerColumnLists: ${reason}`, kind: "abstained" }) for (const d of input.consumerLists.dropped ?? []) unverified.push({ ...d, kind: "abstained" }) } const prText = [input.prTitle, input.prBody].filter(Boolean).join("\n") // New content of the PR's changed schema files, read once and only if a lane asks. // Undefined when a changed schema file could not be read: what it declares is unknown, not empty. let ymlText: Promise | undefined const changedYmlText = () => (ymlText ??= Promise.all( reviewable .filter((f) => f.kind === "schema_yml" && f.status !== "deleted") .map((f) => (getContent ? Promise.resolve(getContent(f.path, "new")).catch(() => undefined) : Promise.resolve("" as string | undefined))), ).then((texts) => (texts.some((t) => t === undefined) ? undefined : (texts as string[])))) const all: Finding[][] = [] // Files where the diff-scoped PII classifier completed (looked at the change), // those where it actually emitted a finding, and — per file — the lowercased // columns it classified and those it flagged. These drive column-aware dedup // of the coarse regex PII twins in the merge step below. const diffScopedPiiCompletedFiles = new Set() const diffScopedPiiFindingFiles = new Set() const classifiedPiiColumnsByFile = new Map>() const flaggedPiiColumnsByFile = new Map>() // Per file: PII columns the compiled base already exposed. Neither the broad // fallback nor the regex twins report these (this PR did not expose them). const basePiiColumnsByFile = new Map>() // Per file, the final output of the base and head models, parsed from the SQL // the engine reads (compiled, or raw only when it holds no Jinja): a raw Jinja // base would credit it with every `{% if %}` branch, including ones the target // never renders. No engine SQL → nothing is known exposed. const outputsByFile = new Map() const outputs = (file: string, side: "old" | "new") => { const key = `${side}\u0000${file}` let parsed = outputsByFile.get(key) if (!parsed) { const ctx = ctxByPath.get(file) parsed = finalOutputs((side === "old" ? ctx?.engineOldSql : ctx?.engineNewSql) ?? "") outputsByFile.set(key, parsed) } return parsed } // The schema prefixes the base reads tables under: a base compiled into // another environment (prod `target-base`, a `+schema` change) reads the same // tables under different prefixes, which `refCovered` then ignores, but only // for tables the raw model code names the same way on both sides. // A source YAML edit may move a `source()` whose text in the model is unchanged. const sourcesEdited = (await Promise.all(input.changedFiles.map((f) => sourceYamlEdited(f, getContent, input.layout)))).some( Boolean, ) // Parsed only when a prefix difference needs it: it re-parses both raw sides. const relationMatchByFile = new Map RelationMatch>() const relationMatch = (file: string, table: string) => { let matchesRaw = relationMatchByFile.get(file) if (!matchesRaw) { const ctx = ctxByPath.get(file) relationMatchByFile.set(file, (matchesRaw = rawRelationsMatch(ctx?.oldSql, ctx?.newSql, sourcesEdited))) } return matchesRaw(table) } // `unknownAsSame`: whether a prefix difference the raw code cannot decide // counts as the same table; `unknownAsked` records that one was asked. const envOf = ( file: string, opts: { unknownAsSame?: boolean; unknownAsked?: { value: boolean } } = {}, ): RelationPrefixes => ({ base: outputs(file, "old").prefixes, sameRelation: (table) => { const match = relationMatch(file, table) if (match === "unknown" && opts.unknownAsked) opts.unknownAsked.value = true return match === "same" || (match === "unknown" && !!opts.unknownAsSame) }, }) // `source.column` refs the base exposed raw under a name its PII detection // reported: named in its final select, or passed through its plain `*` // (`select * from customers` exposes `customers.ssn` when `ssn` is base PII). const baseRawPiiByFile = new Map>() const baseRawPii = (file: string) => { const cached = baseRawPiiByFile.get(file) if (cached) return cached const basePii = basePiiColumnsByFile.get(file) const refs = new Set() if (!basePii) return refs const base = outputs(file, "old") for (const name of basePii) { for (const ref of base.raw.get(name) ?? []) refs.add(ref) if (!base.names.has(name) && base.passthrough) for (const ref of base.starRaw(name)) refs.add(ref) } baseRawPiiByFile.set(file, refs) return refs } // A regex twin's SOURCE column (`ssn`, with its output alias when it has one) is // already exposed only when the head reads it raw from sources that a base PII // output also exposed raw: same table and column (`c.ssn` → `cust.ssn` on // `customers` is not new; `s.ssn` from `spouses` is). An alias alone is not // proof (`c.email as contact` → `c.ssn as contact` newly exposes `ssn`), and // neither is a base output that only masks the column (`sha2(c.ssn) as ssn_hash`) // or a CTE's own alias that never reaches the final select. A column the head's // final output doesn't expose raw under that name is reported. // The output name comes from the head's final-select item that spans the line // and reads the column raw, so an alias on the next line counts; else the // twin's own alias, else the column. const twinOutputNames = (file: string, column: string, alias?: string, line?: string) => { const spanning = line ? headItemsOnLine(file, line).filter((i) => i.scope === ROOT_SCOPE && i.rawColumn === column) : [] return spanning.length ? [...new Set(spanning.map((i) => i.name!))] : [alias ?? column] } const isBaseExposed = (file: string, column: string, alias?: string, line?: string) => { const names = twinOutputNames(file, column, alias, line) const head = outputs(file, "new").raw const exposed = baseRawPii(file) return names.every((name) => { const refs = [...(head.get(name) ?? [])].filter((r) => r.endsWith(`.${column}`)) // An undecided prefix difference is not the same table: it never drops a twin. return refs.length > 0 && refs.every((r) => refCovered(r, exposed, envOf(file))) }) } // A head PII output name the base already exposed. When the head selects a // column raw under it, the base must expose that same source column raw (base // `md5(home_address) as home_address` → head `home_address` is new). A head // output that is not a raw column is base-exposed when every source column its // value is computed from is one a base PII output exposed raw, or when the base // computes the name the same way (same item text with its literals, same // CTEs/subqueries read, over source columns the base's name also read): // `md5(x) as x` → `lower(x) as x` unmasks, and base raw `email` → // `lower(ssn) as email` reads `ssn`. A name the head's final select doesn't // resolve counts as base-exposed only when the head passes it through a plain // `*` and every source column that `*` resolves it to was exposed raw by a // base PII output (named, or through the base's own `*`). const isBaseExposedOutput = (file: string, name: string, basePii: Set, env: RelationPrefixes) => { const head = outputs(file, "new") const rawColumns = head.raw.get(name) if (rawColumns?.size) { const exposed = baseRawPii(file) const covered = (ref: string) => refCovered(ref, exposed, env) if (![...rawColumns].every(covered)) return false // A later UNION branch may compute the name from other columns (base raw // `email` → head adds `lower(ssn) as email`): the raw match alone is not // proof. A read the base exposed raw is covered; so is one the base also // read for this name, when the name is computed as in the base through // the columns it follows (`lineage`), so an unrelated edit to a CTE the // branch reads changes nothing. Anything else falls through. const reads = [...(head.reads.get(name) ?? [])] if (reads.every(covered)) return true const base = outputs(file, "old") const baseReads = base.reads.get(name) ?? new Set() const baseLineage = base.lineage.get(name) if ( reads.every((ref) => covered(ref) || refCovered(ref, baseReads, env)) && !!baseLineage && [...(head.lineage.get(name) ?? [])].every((sig) => lineageCovered(sig, baseLineage, env, { base, head })) ) return true } if (!basePii.has(name)) return false const base = outputs(file, "old") if (head.names.has(name)) { const exposed = baseRawPii(file) const reads = head.reads.get(name) if (reads && [...reads].every((ref) => refCovered(ref, exposed, env))) return true // The same computation counts only over the same source columns: each // lineage record pairs a computation with the columns it reads // (`lower(email)` from `customers` → from `spouses` is new, and so is // `md5` and `lower` swapped between two tables' `email`). A column read // that no source explains keeps its text in the computation. const baseReads = base.reads.get(name) ?? new Set() const sameReads = [...(reads ?? [])] .filter((ref) => !ref.startsWith("?")) .every((ref) => refCovered(ref, baseReads, env)) const baseLineage = base.lineage.get(name) return sameReads && [...(head.lineage.get(name) ?? [])].every((record) => lineageCovered(record, baseLineage, env, { base, head })) } // Unresolved only through a plain `*`: a shape the parser does not model (a // parenthesised top-level union, `* except (…)`) is reported. A `*` the // parser resolves is base-exposed only when every source column it passes // the name through was one a base PII output exposed raw. if (!head.passthrough) return false const starRefs = head.starRaw(name) const exposed = baseRawPii(file) return starRefs.size > 0 && [...starRefs].every((ref) => refCovered(ref, exposed, env)) } // Exposed whatever the undecided prefix differences are; `undecided` when only // reading them as environment changes makes it exposed; else `new`. // Short-circuiting (`every`) may skip some prefix checks, so `unknownAsked` // can miss one: harmless, since a check that fails without asking about an // undecided prefix fails the same way when undecided prefixes count as same. const baseExposure = (file: string, name: string, basePii: Set) => { const unknownAsked = { value: false } if (isBaseExposedOutput(file, name, basePii, envOf(file, { unknownAsked }))) { // A new UNION branch item whose output name cannot be told may compute this one. const unmapped = outputs(file, "old").unmapped const env = envOf(file) return [...outputs(file, "new").unmapped].every((r) => lineageCovered(r, unmapped, env)) ? "exposed" : "undecided" } // The head reads a column no source explains while the base explained all // of its reads, and the head as a whole is in a shape the parser does not // follow (DuckDB `from … select`): what it computes cannot be compared. const unexplained = (side: "old" | "new") => [...(outputs(file, side).reads.get(name) ?? [])].some((ref) => ref.startsWith("?")) // A UNION whose `*` cannot be placed on one side only (a `*` written out // as columns, or the reverse): the name's records are not comparable. const [was, now] = [outputs(file, "old"), outputs(file, "new")] if (was.unionBranches > 1 && now.unionBranches > 1 && was.unionStar !== now.unionStar) return "undecided" const followed = (side: "old" | "new") => !outputs(file, side).unfollowed if (!followed("new") && followed("old") && unexplained("new") && !unexplained("old") && outputs(file, "old").names.has(name)) return "undecided" if (!unknownAsked.value) return "new" return isBaseExposedOutput(file, name, basePii, envOf(file, { unknownAsSame: true })) ? "undecided" : "new" } // The raw base as `rawBaseLacks` reads it, parsed once per file and only when // a PII lane needs it (the engine lanes and the regex twins share it). const rawBaseCodeByFile = new Map() const baseCode = (file: string) => { if (!rawBaseCodeByFile.has(file)) rawBaseCodeByFile.set(file, rawBaseCode(ctxByPath.get(file)?.oldSql)) return rawBaseCodeByFile.get(file) } // The raw base cannot have exposed the head output `column`: it names neither // that output nor any source column the output reads (`email as contact` // over a base that selects `email` is a rename, not a new exposure). const baseLacksOutput = (file: string, column: string) => { const head = outputs(file, "new") // An output the parser does not find in the head: what it reads is unknown. if (!head.names.has(column) && !head.passthrough) return false const reads = [...(head.reads.get(column) ?? [])].map((ref) => ref.slice(ref.lastIndexOf(".") + 1)) return rawBaseLacks(baseCode(file), [...new Set([column, ...reads])]) } // Indexes of the abstentions recorded while some file's lanes ran. const inFileLanes = new Set() // The head's dbt_project.yml, read once: inherited test thresholds and defined vars. const projectYmlPath = `${input.layout?.root ? `${input.layout.root.replace(/\/$/, "")}/` : ""}dbt_project.yml` const projectYml = await Promise.resolve(getContent?.(projectYmlPath, "new")).catch(() => undefined) const projectVars = definedVars(projectYml) // Models a schema yml in the PR declares (either side): their own yml changed. const ymlModels = new Set() await Promise.all( reviewable .filter((f) => f.kind === "schema_yml") .flatMap((f) => [ f.status !== "deleted" ? getContent?.(f.path, "new") : undefined, f.status !== "added" ? getContent?.(f.oldPath ?? f.path, "old") : undefined, ]) .map(async (text) => { let doc: any try { doc = YAML.parse((await Promise.resolve(text).catch(() => undefined)) ?? "") } catch { return } for (const m of Array.isArray(doc?.models) ? doc.models : []) if (m?.name) ymlModels.add(String(m.name).toLowerCase()) }), ) const ownYmlChanged = (model: string) => ymlModels.has(model.toLowerCase()) for (const ctx of ctxByPath.values()) { const tasks: Promise[] = [] // Engine lanes consume COMPILED SQL (rendered by dbt) when available. if (lanes.has("sql_quality") || lanes.has("warehouse_cost")) tasks.push( qualityLane(ctx.file, input.runner, ctx.engineNewSql, dialect, ctx.engineOldSql, ctx.engineNewSql === ctx.newSql, { engineError: (message) => { const failure = reportFailure("engine_error", { check: "check", path: ctx.file.path }, message) const prev = validationErrors.find((e) => e.method === "check") if (prev) prev.count++ else validationErrors.push({ method: "check", reason: failure.message, count: 1, category: "engine_error" }) }, abstain: (reason) => unverified.push({ path: ctx.file.path, reason, kind: "abstained" }), }), ) if (lanes.has("semantic_change")) { tasks.push(dataDiffLane(ctx, input.runner, dialect, input.config.dataDiff)) tasks.push(grainMismatchLane(ctx, input.runner)) tasks.push( semanticChangeLane( ctx.file, input.runner, ctx.engineOldSql, ctx.engineNewSql, dialect, ctx.impact, input.rubric, unverified, ), ) } if (lanes.has("lineage_breakage")) { // Synchronous detectors run as tasks so a throw is isolated to this file. tasks.push(Promise.resolve().then(() => lineageBreakageLane(ctx.file, ctx.impact, input.rubric))) tasks.push( columnBreakageLane( ctx, input.runner, getCompiled, dialect, (reason) => unverified.push({ path: ctx.file.path, reason, kind: "abstained" }), ), ) } if (lanes.has("lineage_breakage") || lanes.has("contract_violation")) { tasks.push( consumerContractLane(ctx, input.runner, { checkContractColumns: input.config.checkContractColumns, changedYmlText, abstain: (reason) => unverified.push({ path: ctx.file.path, reason, kind: "abstained" }), }), ) tasks.push( Promise.resolve().then(() => consumerListLane(ctx, input.consumerLists?.lists ?? [], (reason) => unverified.push({ path: ctx.file.path, reason, kind: "abstained" }), ), ), ) } if (lanes.has("test_coverage")) tasks.push(missingGrainTestLane(ctx, input.runner)) // PII classification always runs (cheap name-pattern check, diff-scoped to // newly-introduced columns) — exposing PII is a hard-floor concern that // shouldn't depend on the cost tier enabling the pii_exposure lane. If core // lineage/classification fails, keep the broad deterministic fallback. // Run it as a concurrent task (not an inline await) so the heavy native // lineage/classify calls overlap the other engine lanes for this file. const currentCtx = ctx tasks.push( (async () => { let basePii = new Set() let baseAbstained = false let baseFaulted = false if (hasOldSide(currentCtx.file) && currentCtx.engineOldSql) { try { const baseRes = await input.runner.detectPii(currentCtx.engineOldSql, dialect) baseAbstained = baseRes.abstained === true baseFaulted = baseRes.faulted === true basePii = new Set(baseRes.columns.map((c) => c.toLowerCase())) } catch { /* unknown base exposure: report as if new */ } basePiiColumnsByFile.set(currentCtx.file.path, basePii) } const diffScopedPii = await piiClassifyLane( currentCtx, input.runner, dialect, (col) => baseLacksOutput(currentCtx.file.path, col), // An engine fault on the base is not an abstention: the column stays critical, as on // main, and the fault is an engine error of the run. baseAbstained && !baseFaulted, ) if (diffScopedPii.completed) { diffScopedPiiCompletedFiles.add(currentCtx.file.path) classifiedPiiColumnsByFile.set(currentCtx.file.path, diffScopedPii.classifiedColumns) } if (diffScopedPii.findings.some((f) => f.confidence !== "unknown")) diffScopedPiiFindingFiles.add(currentCtx.file.path) flaggedPiiColumnsByFile.set( currentCtx.file.path, new Set(diffScopedPii.findings.map((f) => String((f.evidence?.result as any)?.column ?? "").toLowerCase())), ) const findings = [...diffScopedPii.findings] if (lanes.has("pii_exposure")) { // The broad fallback covers output PII columns the precise lane did NOT // classify (pre-existing columns, or ones core's classifier missed) — // dedup against the columns core actually CONSIDERED, never all // introduced columns, so a missed column still surfaces here. let fallbackPii = diffScopedPii.completed ? currentCtx.pii.filter((col) => !diffScopedPii.classifiedColumns.has(col.toLowerCase())) : currentCtx.pii // An unanalysable base says nothing about what it exposed: its columns // are reported as undecided (never blocking), not as newly exposed // and not dropped. if (fallbackPii.length && baseAbstained) { unverified.push({ path: currentCtx.file.path, reason: "the PII check could not analyse the base model", kind: "abstained", }) } // The fallback reports only columns the base did not already expose. const exposure = new Map( fallbackPii.map((col) => [col, baseExposure(currentCtx.file.path, col.toLowerCase(), basePii)]), ) fallbackPii = fallbackPii.filter((col) => exposure.get(col) !== "exposed") // Without a compiled base a column is undecided unless the raw base // provably lacks that output (its name and the columns it reads). const baseUnknown = hasOldSide(currentCtx.file) && !currentCtx.engineOldSql findings.push( ...piiLane( currentCtx.file, fallbackPii, (col) => baseAbstained || exposure.get(col) === "undecided" || (baseUnknown && !baseLacksOutput(currentCtx.file.path, col.toLowerCase())), baseAbstained ? PII_UNDECIDED_BASE_UNANALYSED : PII_UNDECIDED_BASE_UNKNOWN, ), ) } return findings })(), ) // Deterministic dbt anti-pattern detectors run on RAW SQL + diff (need Jinja). if (lanes.has("dbt_patterns")) { tasks.push( Promise.resolve().then(() => detectModelPatterns(ctx.file, ctx.newSql, input.rubric, { dialect, dialectKnown: !!input.dialectKnown, oldSql: hasOldSide(ctx.file) ? ctx.oldSql : undefined, }), ), ) tasks.push(lexicalLane(ctx.file, input.runner)) } if (lanes.has("dbt_patterns") || lanes.has("materialization")) { tasks.push( incrementalSemanticsLane( ctx, input.runner, dialect, !!input.dialectKnown, prText, input.config.incrementalSliceVars, (reason) => unverified.push({ path: ctx.file.path, reason, kind: "abstained" }), input.rubric.blockingRules, ), ) } // dbt config/Jinja lint (materialization / incremental / contract) — gate on its // own concerns, not just dbt_patterns, so it isn't silently dropped on a tier that // enables those concerns without dbt_patterns. if (lanes.has("dbt_patterns") || lanes.has("materialization") || lanes.has("contract_violation")) { tasks.push(dbtConfigLane(ctx, input.runner, projectVars)) tasks.push(uniqueKeyMismatchLane(ctx, input.runner, dialect, ownYmlChanged)) tasks.push(joinKeyUniquenessLane(ctx, input.runner)) tasks.push( (input.runner.modelConfig?.(modelNameFromPath(ctx.file.path)) ?? Promise.resolve(undefined)) .catch(() => undefined) .then((mc) => [ ...jinjaFindings(ctx.file, ctx.oldSql, ctx.newSql, { baseUnknown: hasOldSide(ctx.file) && ctx.oldSql === undefined }), ...modelConfigFindings( ctx.file, ctx.newSql && inlineConfigSplats(ctx.newSql), dialect, mc, !!input.dialectKnown, projectIncrementalStrategy(projectYml, ctx.file.path, input.layout), ), ]), ) } // Base-vs-head structural diff is a `semantic_change` concern (DISTINCT/UNION/grain/ // surrogate-key/predicate changes) — gate on semantic_change, keeping dbt_patterns // so the trivial tier (which has no semantic_change lane) still gets it. if (lanes.has("semantic_change") || lanes.has("dbt_patterns")) { tasks.push(structuralChangeLane(ctx, input.runner)) } // A lane that throws drops only its own findings for this file, recorded // as unverified — never the whole review. let laneFailed = false // Files run one at a time, so a parse abstention recorded while this file's // lanes run (its base, head, or a downstream model it is compared with) // belongs to this file. const abstainedBefore = input.runner.abstentions?.().length ?? 0 const settled = await Promise.all( tasks.map((t) => t.catch((err) => { if (!laneFailed) failedFile(ctx.file, err) laneFailed = true return [] as Finding[] }), ), ) all.push(...settled) const abstainedAfter = input.runner.abstentions?.().length ?? 0 for (let i = abstainedBefore; i < abstainedAfter; i++) inFileLanes.add(i) // Python models are not SQL; the SQL checks' abstentions say nothing about them. if (ctx.file.kind !== "python_model") { for (const method of new Set((input.runner.abstentions?.() ?? []).slice(abstainedBefore, abstainedAfter).map((a) => a.method))) unverified.push({ path: ctx.file.path, reason: abstainReason(method), kind: "abstained" }) } } // PR-level: cross-model sibling filter-consistency (divergent filters on a // shared upstream across the changed models). if (lanes.has("semantic_change")) { all.push(await prLevel("sibling_consistency", siblingConsistencyLane([...ctxByPath.values()], input.runner))) } // PR-level: topology-aware equivalence for merge refactors (N models deleted + // 1 added that supersedes them). Per-model equivalence can't see these because // the new model has no 1:1 base. Advisory only (capped at warning). if (lanes.has("semantic_change")) { all.push(await prLevel("topology_equivalence", topologyEquivalenceLane(modelFiles, input.runner, getCompiled, dialect))) } // Snapshot definitions: a changed `check_cols`/strategy or query on an existing snapshot. if (lanes.has("dbt_patterns") || lanes.has("materialization")) { const snapshots = reviewable.filter((f) => f.kind === "snapshot" && f.status !== "deleted" && f.status !== "added") touch(snapshots) const sets = await Promise.all( snapshots.map(async (file) => { try { // A side that could not be read (or whose read threw) leaves the snapshot not reviewed, // not clean: an unreadable file, never an internal error. const read = (p: string, side: "old" | "new") => Promise.resolve(getContent?.(p, side)).catch(() => undefined) const [oldSql, newSql] = await Promise.all([read(file.oldPath ?? file.path, "old"), read(file.path, "new")]) if (getContent) { if (oldSql === undefined) failedFile(file, undefined, "base") if (newSql === undefined) failedFile(file, undefined, "head") } if (!newSql) return [] const model = modelNameFromPath(file.path) const manifestConfig = await input.runner.modelConfig?.(model) return snapshotFindings({ file, model, newSql, oldSql, prText, manifestConfig, blockingRules: input.rubric.blockingRules }) } catch (err) { failedFile(file, err) return [] } }), ) for (const findings of sets) all.push(findings) } // The repository's head files, listed once; undefined when they cannot be listed. let headFiles: Promise | undefined // A listing or search that throws is logged only: the rules that need it stay silent or abstain. const lookupFailed = (check: string) => (err: unknown) => { reportFailure("internal_error", { check }, err) return undefined } const listHeadFiles = () => (headFiles ??= input.projectFiles ? input.projectFiles().catch(lookupFailed("project-files")) : Promise.resolve(undefined)) /** Fixed-string search of the head files `keep` selects; undefined when the search is unavailable or failed. */ const searchFiles = async (pattern: string, keep: (path: string) => boolean) => { const files = input.grepFiles ? await listHeadFiles() : undefined if (!files) return undefined const chosen = files.filter(keep) return chosen.length ? input.grepFiles!(pattern, chosen).catch(lookupFailed("project-search")) : [] } // An `adapter.dispatch` call that now passes a keyword some `__` variant in the repo doesn't take. // A search that failed leaves the variants unknown: the call is listed as not checked. const dispatchVariantFindings = async (file: ChangedFile, newSql: string): Promise => { if (!/\badapter\.dispatch\b/.test(newSql)) return [] const texts = new Map([[file.path, newSql]]) for (const name of new Set([...newSql.matchAll(/\badapter\.dispatch\s*\(\s*['"](?:\w+\.)?(\w+)['"]/g)].map((m) => m[1]))) { const hits = input.grepFiles ? await searchFiles(`__${name}(`, (p) => /\.sql$/i.test(p)) : [] if (hits === undefined) { unverified.push({ path: file.path, reason: "the repository could not be searched for this macro's `adapter.dispatch` variants, so the keywords it passes were not checked", kind: "abstained", }) return [] } for (const path of new Set(hits.map((h) => h.path))) { if (texts.has(path)) continue const text = await Promise.resolve(getContent?.(path, "new")).catch(() => undefined) // A variant that cannot be read leaves its keywords unknown: listed, not read as empty. if (text === undefined) { unverified.push({ path: file.path, reason: "a variant of this macro's `adapter.dispatch` could not be read, so the keywords it passes were not checked", kind: "abstained", }) return [] } texts.set(path, text) } } return dispatchKwargFindings(file, newSql, (name) => [...texts.values()].flatMap((t) => dispatchVariants(t, name))) } // Macros: the catalog rules that hold in a SQL template, and vars with no default. if (lanes.has("dbt_patterns")) { const macros = reviewable.filter((f) => f.kind === "macro" && f.status !== "deleted") touch(macros) const sets = await Promise.all( macros.map(async (file) => { try { let headErr: unknown const [newSql, oldSql] = await Promise.all([ Promise.resolve(getContent?.(file.path, "new")).catch((err) => { headErr = err ?? "read failed" return undefined }), file.status === "added" ? Promise.resolve(undefined) : Promise.resolve(getContent?.(file.oldPath ?? file.path, "old")).catch(() => undefined), ]) // A head the diff says exists but that could not be read is unreadable, not clean. if (newSql === undefined) { if (getContent || headErr !== undefined) failedFile(file, headErr, "head") return [] } if (!newSql) return [] const baseUnknown = file.status !== "added" && oldSql === undefined if (baseUnknown) failedFile(file, undefined, "base") return [ ...detectMacroPatterns(file, newSql, input.rubric, projectVars, { dialect, dialectKnown: !!input.dialectKnown }), ...jinjaFindings(file, oldSql, newSql, { baseUnknown }), ...(await dispatchVariantFindings(file, newSql)), ] } catch (err) { failedFile(file, err) return [] } }), ) for (const findings of sets) all.push(findings) } // ref() to a name no model, seed or snapshot carries: dbt fails to parse the project. // When the names cannot be listed, the models adding a ref are listed as not fully verified. if (lanes.has("dbt_patterns") && input.resourceNames) { const models = [...ctxByPath.values()].filter((c) => c.file.status !== "deleted" && splitDiff(c.file.diff).added.some((l) => /\bref\s*\(/.test(l))) const names = models.length ? await input.resourceNames().catch(() => undefined) : undefined for (const c of models) { if (names) all.push(missingRefFindings(c.file, names, c.newSql)) else unverified.push({ path: c.file.path, reason: "the project's models, seeds and snapshots could not be listed, so new `ref()` targets were not checked", kind: "abstained", }) } } // Singular tests and snapshots: Jinja structure. packages.yml / dbt_project.yml: pins and config. if (lanes.has("dbt_patterns")) { const others = reviewable.filter( (f) => f.status !== "deleted" && ((f.kind === "test" || f.kind === "snapshot") || f.kind === "project_config"), ) touch(others) const sets = await Promise.all( others.map(async (file) => { try { // A read that throws is an unreadable side, as when the resolver returns nothing. const read = (path: string, side: "old" | "new") => Promise.resolve(getContent?.(path, side)).catch(() => undefined) const [newContent, oldContent] = await Promise.all([ read(file.path, "new"), file.status === "added" ? Promise.resolve(undefined) : read(file.oldPath ?? file.path, "old"), ]) // Snapshots and a modified dbt_project.yml already report an unreadable side below this lane. const reportedElsewhere = file.kind === "snapshot" || (file.status === "modified" && /(^|\/)dbt_project\.ya?ml$/.test(file.path)) if (newContent === undefined) { if (getContent && !reportedElsewhere) failedFile(file, undefined, "head") return [] } // A base that could not be read is unknown, not empty: nothing is compared against it. const baseUnknown = file.status !== "added" && oldContent === undefined const abstain = (reason: string) => unverified.push({ path: file.path, reason, kind: "abstained" }) if (baseUnknown && !reportedElsewhere) failedFile(file, undefined, "base") if (file.kind === "project_config") return [ ...packagesFindings(file, newContent, abstain), ...(baseUnknown ? [] : dbtProjectFindings(file, oldContent, newContent, abstain)), ] return [ ...jinjaFindings(file, oldContent, newContent, { baseUnknown }), ...(file.kind === "test" && !baseUnknown ? testWindowFindings(file, newContent) : []), ] } catch (err) { failedFile(file, err) return [] } }), ) for (const findings of sets) all.push(findings) } // Abstentions of calls made outside one file's lanes (pre-compute, the PR-level // lanes) belong to the changed model whose SQL could not be parsed. const sqlKey = (sql: string | undefined) => sql?.trim().replace(/;\s*$/, "") // Several changed models can share one SQL text (copies, a rename plus its twin). const pathsBySql = new Map() for (const c of ctxByPath.values()) { if (c.file.kind === "python_model") continue for (const sql of [c.engineNewSql, c.engineOldSql]) { const key = sqlKey(sql) if (!key) continue const paths = pathsBySql.get(key) ?? [] if (!paths.includes(c.file.path)) paths.push(c.file.path) pathsBySql.set(key, paths) } } const outsideLanes = new Set() for (const [i, a] of (input.runner.abstentions?.() ?? []).entries()) { if (inFileLanes.has(i)) continue for (const p of new Set((a.sql ?? []).flatMap((sql) => pathsBySql.get(sqlKey(sql) ?? "") ?? []))) { if (outsideLanes.has(`${p}|${a.method}`)) continue outsideLanes.add(`${p}|${a.method}`) unverified.push({ path: p, reason: abstainReason(a.method), kind: "abstained" }) } } // A read whose error is written to the job log only: the file is reported by its own lane, or // stays in the not-reviewed list. const readLogged = (path: string, side: "old" | "new", check: string) => Promise.resolve(getContent?.(path, side)).catch((err) => { reportFailure("file_unreadable", { check, path, side: side === "new" ? "head" : "base" }, err) return undefined }) const projectPrefix = input.layout?.root ? `${input.layout.root.replace(/\/+$/, "")}/` : "" const listed = (files: string[] | undefined, path: string) => files?.includes(path) // dbt project files whatever their dbt role: YAML that no longer parses, `package-lock.yml` // committed in a package, and new models missing from the quickstart `public_models`. An // "other" file counts as reviewed only when a rule evaluated it (a syntax parse does not count). const otherChecked = new Set() const checkedOther = (file: ChangedFile) => { otherChecked.add(file.path) touch([file]) } if (lanes.has("dbt_patterns")) { const ymls = reviewable.filter((f) => f.status !== "deleted" && isDbtProjectYaml(f, input.layout)) const sets = await Promise.all( ymls.map(async (file) => { try { // An unreadable head is reported by the file's own lane. const newContent = await readLogged(file.path, "new", "yaml-parse-error") return await yamlParseFindings( file, newContent, () => readLogged(file.oldPath ?? file.path, "old", "yaml-parse-error"), (reason) => unverified.push({ path: file.path, reason, kind: "abstained" }), ) } catch (err) { failedFile(file, err) return [] } }), ) for (const findings of sets) all.push(findings) for (const file of reviewable.filter((f) => f.status === "added" && /(^|\/)package-lock\.yml$/.test(f.path))) { const dir = file.path.slice(0, file.path.length - "package-lock.yml".length) const files = await listHeadFiles() // A dbt project directory: its `dbt_project.yml` is listed, or (no listing) readable. const project = files ? listed(files, `${dir}dbt_project.yml`) : (await readLogged(`${dir}dbt_project.yml`, "new", "package-lock-in-package")) !== undefined if (!project) continue // A package carries a dbt project under `integration_tests/` (directly or one level deeper). const nested = new RegExp(`^${escapeRe(dir)}integration_tests/(?:[^/]+/)?dbt_project\\.ya?ml$`) const hasTests = files ? files.some((p) => nested.test(p)) : (await readLogged(`${dir}integration_tests/dbt_project.yml`, "new", "package-lock-in-package")) !== undefined checkedOther(file) all.push(packageLockFindings(file, isPackageProject(hasTests))) } const newModels = reviewable.filter((f) => f.kind === "model_sql" && f.status === "added") if (newModels.length) { const QUICKSTART = /(^|\/)\.quickstart\/quickstart\.ya?ml$/ const changed = reviewable.find((f) => QUICKSTART.test(f.path) && f.status !== "deleted") const qsPath = changed?.path ?? `${projectPrefix}.quickstart/quickstart.yml` // Not read when the listing shows there is none. const files = changed ? undefined : await listHeadFiles() const content = changed || !files || listed(files, qsPath) ? await readLogged(qsPath, "new", "quickstart-public-model-missing") : undefined if (content !== undefined) { if (changed) checkedOther(changed) all.push(quickstartModelFindings(changed ?? newModels[0], qsPath, content, newModels.map((f) => modelNameFromPath(f.path)))) } } } // Where a `{% docs name %}` block lives (cached per name): the project's `.md` files, then the // installed packages when the project declares any. A search that failed, or packages that are // declared but not in the repository, leave the name unknown. const DOCS_HIT_CAP = 50 const docLookups = new Map>() const searchDocs = async (name: string, keep: (path: string) => boolean): Promise => { const block = new RegExp(`\\{%-?\\s*docs\\s+${name}\\s*-?%\\}`) const hits = await searchFiles(`docs ${name}`, (p) => /\.md$/i.test(p) && keep(p)) if (hits === undefined) return undefined if (hits.some((h) => block.test(h.text))) return true // A capped result may have left the block out. return hits.length >= DOCS_HIT_CAP ? undefined : false } const installPath = (() => { const doc = (() => { try { return projectYml ? YAML.parse(projectYml) : undefined } catch { return undefined } })() const p = typeof doc?.["packages-install-path"] === "string" ? doc["packages-install-path"] : "dbt_packages" return `${projectPrefix}${p.replace(/^\.\/|\/+$/g, "")}/` })() /** Whether the project installs packages: true, false, or undefined when it cannot be told. */ let declaresPackages: Promise | undefined const projectDeclaresPackages = () => (declaresPackages ??= (async () => { const files = await listHeadFiles() if (!files) return undefined const declared = ["packages.yml", "dependencies.yml"].map((n) => `${projectPrefix}${n}`).filter((p) => files.includes(p)) if (!declared.length) return false for (const p of declared) { const text = await readLogged(p, "new", "doc-block-missing") if (text === undefined) return undefined let doc: any try { doc = YAML.parse(text) } catch { return undefined } if (Array.isArray(doc?.packages) && doc.packages.length) return true } return false })()) const docLookup = (name: string) => { if (!docLookups.has(name)) docLookups.set( name, (async (): Promise => { const inProject = await searchDocs(name, (p) => !p.startsWith(installPath)) if (inProject === undefined) return "unknown" if (inProject) return "project" const packages = await projectDeclaresPackages() if (packages === undefined) return "unknown" if (!packages) return "missing" // Installed packages are usually not in the repository; when none is, nothing rules the name out. const files = await listHeadFiles() if (!files?.some((p) => p.startsWith(installPath))) return "unknown" const inPackage = await searchDocs(name, (p) => p.startsWith(installPath)) return inPackage === undefined ? "unknown" : inPackage ? "package" : "missing" })().catch((err) => { reportFailure("internal_error", { check: "doc-block-missing" }, err) return "unknown" as const }), ) return docLookups.get(name)! } // The project keeps docs blocks of its own (a `{% docs x %}` in its `.md` files, outside the // installed packages): a file's first `doc()` can then be checked. Undefined when the search failed. let docsAny: Promise | undefined const projectHasDocs = () => (docsAny ??= searchFiles("docs ", (p) => /\.md$/i.test(p) && !p.startsWith(installPath)) .then((hits) => (hits === undefined ? undefined : hits.some((h) => /\{%-?\s*docs\s+\w+\s*-?%\}/.test(h.text)))) .catch(() => undefined)) // schema.yml-level detectors (test removal) — run on changed YAML files // regardless of tier, since deleting a guardrail test is always worth flagging. // Pass old + new content when available so the detector diffs structural YAML // (per-(entity, column, test) tuples) instead of walking the unified diff // (which loses context when the model header is outside the -U3 window and // silently drops sibling-column edge cases). Falls back to diff-only line // detection when a content resolver isn't wired (e.g. unit-test callers). // // `oldContent` is fetched for anything that has an old side — MODIFIED, // RENAMED, and DELETED. A schema.yml being renamed (e.g. moved to a new // subdir) that also drops a `unique`/`not_null` guardrail must still surface // as a finding; the earlier `status === "modified"` gate silently skipped // renames. A whole schema.yml being DELETED removes every test declared in // it — an even bigger removal — so the detector runs against `oldContent` // vs an empty new document. // // `newContent` fetch is skipped for deleted files (nothing at HEAD to read; // git-show would fail). // // Fetches run in parallel across schema files (a schema-heavy PR could touch // dozens of yml files; serial `git show` per file adds up). const schemaFiles = reviewable.filter((f) => f.kind === "schema_yml") const abstainOn = (file: { path: string }) => (reason: string) => unverified.push({ path: file.path, reason, kind: "abstained" }) touch(schemaFiles) const sqlByModel = new Map([...ctxByPath.values()].filter((c) => c.newSql).map((c) => [modelNameFromPath(c.file.path).toLowerCase(), c.newSql!])) if (schemaFiles.length) { const contents = await Promise.all( schemaFiles.map(async (file) => { try { const oldRef = file.oldPath ?? file.path const [oldContent, newContent] = await Promise.all([ file.status !== "added" ? getContent?.(oldRef, "old") : Promise.resolve(undefined), file.status !== "deleted" ? getContent?.(file.path, "new") : Promise.resolve(undefined), ]) return { file, oldContent, newContent } } catch (err) { return { file, err } } }), ) // Tests in the base of every yml in the PR: one moved between files is not new. const baseTests = new Set(contents.flatMap((c) => [...testKeys(c.oldContent)])) for (const { file, oldContent, newContent, err } of contents) { try { if (err) throw err // The diff fallback misses inline removals (`tests: [unique]` → `tests: []`), // so a side that could not be read leaves the file not fully reviewed. if (getContent) { if (file.status !== "added" && oldContent === undefined) failedFile(file, undefined, "base") if (file.status !== "deleted" && newContent === undefined) failedFile(file, undefined, "head") } all.push([ ...detectSchemaYmlPatterns(file, input.rubric, { oldContent, newContent }), ...testsOnNullColumns(file, newContent, sqlByModel), // An unreadable base (reported above) cannot tell new unit tests // from unchanged ones: the detector skips the file. ...(getContent && file.status !== "added" && oldContent === undefined ? [] : detectUnitTestFixtures(file, oldContent, newContent)), ...snapshotYmlFindings(file, oldContent, newContent, abstainOn(file)), ...detectTestAdequacy({ file, oldContent, newContent, projectYml, layout: input.layout, baseTests, abstain: abstainOn(file) }), ...(lanes.has("dbt_patterns") && input.grepFiles ? await docRefFindings(file, oldContent, newContent, docLookup, abstainOn(file), projectHasDocs) : []), ]) } catch (err) { // One malformed schema file degrades that file only. failedFile(file, err) } } } // A dbt_project.yml change that loosens test thresholds for a whole path. A // version that cannot be read holds back approval like any unreadable file; // one that does not parse lists the file as not fully verified. for (const file of reviewable.filter((f) => f.kind === "project_config" && /(^|\/)dbt_project\.ya?ml$/.test(f.path))) { if (file.status !== "modified" || !getContent) continue touch([file]) try { const read = (side: "old" | "new") => Promise.resolve(getContent(file.path, side)).then( (text) => ({ text, err: undefined as unknown }), (err: unknown) => ({ text: undefined, err }), ) const [before, after] = await Promise.all([read("old"), read("new")]) // As `failedFile` for a side, with the read error in the job log. const unreadable = (side: "head" | "base", err: unknown) => { const failure = reportFailure("file_unreadable", { path: file.path, side }, err) unverified.push({ path: file.path, reason: failure.message, kind: "failed", category: failure.category }) } if (before.text === undefined) unreadable("base", before.err) if (after.text === undefined) unreadable("head", after.err) if (before.text === undefined || after.text === undefined) continue all.push(detectThresholdLoosening(file, before.text, after.text, abstainOn(file))) } catch (err) { failedFile(file, err) } } // Architectural dedup: the regex `dbt-patterns`/`rule-catalog` layer is a // diff-aware, Jinja-aware, offline fallback. For the STRUCTURAL SQL checks // that the native core lint covers via the parsed AST, the AST version is the // source of truth — it can't be tripped by string literals, aliases, or // leading commas the way regex can. So when core lint actually ran for a // file, drop the regex twins of those AST-covered checks. The dbt-specific / // diff-specific detectors (incremental, materialization, ref conventions, // schema.yml test removal, portability) are NOT covered by core and stay. const coreRanFiles = new Set() if (lanes.has("sql_quality") || lanes.has("warehouse_cost")) { await Promise.all( [...ctxByPath.values()].map(async (ctx) => { if (!ctx.engineNewSql || ctx.file.status === "deleted") return // Cache hit: qualityLane already ran this exact check. const cr = await input.runner .check(ctx.engineNewSql, dialect, ctx.engineOldSql) .catch(() => ({ ran: false }) as CheckResult) if (cr.ran) coreRanFiles.add(ctx.file.path) }), ) } // Per file, the function names core's AST L033 (NonPortableFunction) flagged. // The regex portability catalog defers to core for these (single source); // regex still covers functions core didn't flag (dialect-suppressed / not in // core's set) plus reserved words / types / operators that L033 doesn't do. const flat = foldConsumerDuplicates(all.flat(), (f) => ruleTier(f.rule, input.config.rules, dialect) !== "off") // An undecided (unknown-confidence) finding never stands in for another: it // may not block, so a regex twin it dropped could hide a blocking exposure. const schemaPiiFiles = new Set( flat .filter((f) => f.category === "pii_exposure" && f.evidence?.tool === "schema.detect_pii" && f.confidence !== "unknown") .map((f) => f.file), ) // Per file, the output columns an engine PII lane reported as new (not // undecided), at the highest severity it gave each. A regex twin for such a // column at no higher severity only repeats that finding. const enginePiiByFile = new Map>() // Per file, the output columns an engine PII lane reported as undecided. const undecidedPiiByFile = new Map>() for (const f of flat) { if (f.category !== "pii_exposure") continue const result = (f.evidence?.result ?? {}) as { column?: string; columns?: string[] } const tool = f.evidence?.tool const columns = tool === "altimate_core.classify_pii" ? [result.column] : tool === "schema.detect_pii" ? (result.columns ?? []) : [] for (const c of columns) { if (!c) continue if (f.confidence === "unknown") { undecidedPiiByFile.set(f.file, (undecidedPiiByFile.get(f.file) ?? new Set()).add(c.toLowerCase())) continue } const perFile = enginePiiByFile.get(f.file) ?? new Map() const prev = perFile.get(c.toLowerCase()) if (!prev || SEVERITY_ORDER[f.severity] > SEVERITY_ORDER[prev]) perFile.set(c.toLowerCase(), f.severity) enginePiiByFile.set(f.file, perFile) } } const engineReported = (twin: Finding, output: string) => { const severity = enginePiiByFile.get(twin.file)?.get(output.toLowerCase()) return !!severity && SEVERITY_ORDER[severity] >= SEVERITY_ORDER[twin.severity] } // The engine already reports `output` as undecided: a regex twin for it that // is not proven new would report as new what the engine could not decide. // The output is named as `isBaseExposed` names it: by the select item that // spans the twin's line, so an alias on the next line counts. const engineUndecided = (twin: Finding, column: string, alias?: string, line?: string) => twinOutputNames(twin.file, column, alias, line).every((name) => !!undecidedPiiByFile.get(twin.file)?.has(name.toLowerCase())) // Per file, the concatenated rule names core's AST lint actually emitted — // so we suppress a regex twin only when core genuinely covered that concern. const coreRulesByFile = new Map() for (const f of flat) { if (f.evidence?.tool !== "altimate_core.check") continue const rule = String((f.evidence?.result as any)?.rule ?? "") .toLowerCase() .replace(/_/g, "-") coreRulesByFile.set(f.file, `${coreRulesByFile.get(f.file) ?? ""} ${rule}`) } const corePortabilityFns = new Map>() for (const f of flat) { if (f.evidence?.tool === "altimate_core.check" && (f.evidence?.result as any)?.rule === "non_portable_function") { const m = /([A-Za-z_][A-Za-z0-9_.]*)\s*\(\)/.exec(`${f.title} ${f.body}`) if (m) { const set = corePortabilityFns.get(f.file) ?? new Set() set.add(m[1].toLowerCase()) corePortabilityFns.set(f.file, set) } } } // An added line is a pure reindent (or comment/comma-only edit) only when it // matches a removed line AND every select item it belongs to in the head is the // same item, in the same query scope (CTE, nested query or final select), in the // base. Matching a removed line elsewhere is not enough: `email,` moved from a // CTE into the final select, or `ssn` left behind when `sha2(\n ssn\n) as x` // is unwrapped, exposes something new. The item's FROM/JOIN sources must be // unchanged too: `ssn` reindented while `from customers` became `from // spouses` reads another table's column. Sources the parser cannot name never // match. const reindentByFile = new Map< string, { removed: Set; head: SelectItem[]; headLines: string[]; base: Set; headSources: ReturnType } >() const itemKey = (i: SelectItem, sourcesOf: ReturnType) => { const src = sourcesOf(i.scope, i.branch) return src === undefined ? undefined : `${i.scope}#${i.branch}\u0000${i.text.toLowerCase()}\u0000${src}` } const reindentInfo = (file: string) => { const ctx = ctxByPath.get(file) if (!ctx?.newSql) return undefined let r = reindentByFile.get(file) if (!r) { r = { removed: new Set(splitDiff(ctx.file.diff).removed.map(normalizeSelectLine).filter(Boolean)), // One parse of the head serves the reindent check and the reach analysis. head: headReach(file)!.items, headLines: ctx.newSql.split("\n").map(normalizeSelectLine), base: new Set(), headSources: selectSources(ctx.newSql), } if (ctx.oldSql) { const baseSources = selectSources(ctx.oldSql) for (const i of selectItems(ctx.oldSql)) { const key = itemKey(i, baseSources) if (key !== undefined) r.base.add(key) } } reindentByFile.set(file, r) } return r } // The 1-based head lines equal to `line` (normalised). const headLineNumbers = (file: string, line: string) => { const r = reindentInfo(file) const normalized = normalizeSelectLine(line) if (!r || !normalized) return [] return r.headLines.flatMap((l, i) => (l === normalized ? [i + 1] : [])) } // Head select items spanning any head line equal to `line` (normalised). const headItemsOnLine = (file: string, line: string) => { const lineNos = headLineNumbers(file, line) return (reindentInfo(file)?.head ?? []).filter((i) => lineNos.some((n) => i.startLine <= n && n <= i.endLine)) } const isReindented = (file: string, line: string) => { const r = reindentInfo(file) if (!r || !ctxByPath.get(file)?.oldSql || !r.removed.has(normalizeSelectLine(line))) return false const items = headItemsOnLine(file, line) return items.length > 0 && items.every((i) => { const key = itemKey(i, r.headSources) return key !== undefined && r.base.has(key) }) } // Without a compiled base the other PII lanes are undecided (an unknown- // confidence warning) unless `rawBaseLacks` proves the output name new. A // regex twin whose source columns the raw base cannot expose (`rawBaseLacks`) // is proven new, so undecided findings must not stand in for it: it survives // their dedup and keeps its severity below. // The proof is withheld only on evidence, from the head's raw SQL, that the // column does not reach the model's output unmasked. Both must hold: // - on the twin's line: it lies inside select items and each reads the column // only inside masking calls or a window clause (`sha2(\n ssn\n) as // tax_ref`; not `coalesce(\n ssn,\n '')`, which keeps the value), is a `*` // that excludes it, or sits in a CTE or FROM subquery that no reading query // passes on unmasked (`rawReach`: hashed or dropped on the way, or read only // by an `in`/`exists` condition); or it is in no select item but in a // clause that selects nothing (`order by\n ssn`); // - in the rest of the head: nothing may expose the column (`mayExpose`). The // twin fires only on a line that opens with the column, so the same column // selected elsewhere (`select ssn from …` on one line, a `*` over its // table) still reaches the output when the twin's own line is dropped. // Anything `rawReach` cannot follow counts as reaching, so the twin blocks. const headReachByFile = new Map() const headReach = (file: string) => { if (!headReachByFile.has(file)) { const sql = ctxByPath.get(file)?.newSql headReachByFile.set(file, sql ? rawReach(sql) : undefined) } return headReachByFile.get(file) } // Asked for each twin in the dedup and again for its severity: kept per finding // (per-token twins share a fingerprint, so the finding itself is the key). const provenByFinding = new WeakMap() const provenNewTwin = (f: Finding) => { let proven = provenByFinding.get(f) if (proven === undefined) provenByFinding.set(f, (proven = proveNewTwin(f))) return proven } const proveNewTwin = (f: Finding) => { const ctx = ctxByPath.get(f.file) // With both sides analysable the engine's own PII lanes decide. They need the head too: // a readable base beside a head that is still raw Jinja leaves only this proof. if (!ctx || !hasOldSide(ctx.file) || (ctx.engineOldSql && ctx.engineNewSql)) return false const result = (f.evidence?.result ?? {}) as { column?: string; line?: string; items?: SelectItemColumn[] } const hits = result.items?.length ? result.items : result.column ? [{ column: result.column, line: result.line ?? "" }] : [] if (!hits.length || !rawBaseLacks(baseCode(f.file), hits.map((h) => h.column))) return false const reach = headReach(f.file) const mayReachOutput = (hit: { column: string; line: string }) => { const column = hit.column.toLowerCase() const lineNos = headLineNumbers(f.file, hit.line) if (!reach || !lineNos.length || reach.mayExpose(column)) return true // Any head line with this text counts: the diff does not say which one it is. return lineNos.some((n) => { // The analysis's own items: it knows them by identity. const items = reach.items.filter((i) => i.startLine <= n && n <= i.endLine) return items.length ? items.some((i) => reach.passes(i, column)) : !reach.inClause(n) }) } return hits.every(mayReachOutput) } const merged = flat.filter((f) => { const tool = f.evidence?.tool const fallbackRule = String((f.evidence?.result as any)?.rule ?? "").replace(/_/g, "-") // Dedup the coarse regex PII twins against the precise deterministic PII // detectors — but only when a better detector genuinely COVERS the same // column. Suppressing whenever the classifier merely "ran" hid real PII // (a high-risk column core's classifier missed but the regex would catch, // especially on tiers without the broad `pii_exposure` lane). if ( (tool === "dbt-patterns" || tool === "rule-catalog") && f.category === "pii_exposure" && (fallbackRule === "pii-into-mart" || fallbackRule === "select-pii-columns") ) { const proven = provenNewTwin(f) // The broad `schema.detect_pii` lane already flagged this file → redundant. if (schemaPiiFiles.has(f.file) && !proven) return false const result = (f.evidence?.result ?? {}) as { line?: string column?: string alias?: string items?: SelectItemColumn[] } if (fallbackRule === "pii-into-mart") { // `pii_into_mart` is one finding per column token, carrying the column, // its alias and the line. A reindented base line exposes nothing new. if (result.line && isReindented(f.file, result.line)) return false if (!result.column) return !diffScopedPiiCompletedFiles.has(f.file) if (engineReported(f, result.alias ?? result.column)) return false if (!proven && engineUndecided(f, result.column, result.alias, result.line)) return false // Suppress when core's classifier actually CONSIDERED that column (flagged // or deliberately muted). A column core never classified falls through. // A proven-new twin is dropped only when core muted the column, not when // core flagged it as an undecided warning. const classified = classifiedPiiColumnsByFile.get(f.file) const flagged = flaggedPiiColumnsByFile.get(f.file) const considered = (c?: string) => !!c && !!classified?.has(c) && !(proven && flagged?.has(c)) if (considered(result.column) || considered(result.alias)) return false // A column the base already exposed is not newly exposed by this PR. return !isBaseExposed(f.file, result.column, result.alias, result.line) } // `select-pii-columns` keeps every matched column with its alias and line: // drop it when each one is a reindented base line or already base-exposed. const items = result.items ?? [] if (items.length && items.every((i) => isReindented(f.file, i.line) || isBaseExposed(f.file, i.column, i.alias, i.line))) return false if (items.length && items.every((i) => engineReported(f, i.alias ?? i.column))) return false if (!proven && items.length && items.every((i) => engineUndecided(f, i.column, i.alias, i.line))) return false // Otherwise suppress only when a precise detector actually EMITTED a PII // finding for the file (so the exposure is reported by the better source, // not silently dropped). if (diffScopedPiiFindingFiles.has(f.file) && !proven) return false return true } if (!coreRanFiles.has(f.file)) return true if (tool !== "dbt-patterns" && tool !== "rule-catalog") return true // Structural twins: the check code survives on evidence.result.rule (ruleKey // is stripped by the zod schema). Suppress ONLY if core actually emitted the // equivalent rule for this file (else the issue would fall through). const code = fallbackRule const coreMatcher = CORE_AST_COVERED[code] if (coreMatcher && coreMatcher.test(coreRulesByFile.get(f.file) ?? "")) return false // Portability twins: drop a regex finding ONLY IF it is itself a portability // finding AND core L033 flagged the same function. This spares other // concerns about the same function (e.g. GETDATE() idempotency), which are // distinct findings that must survive. const coreFns = corePortabilityFns.get(f.file) // Portability phrasings used across the catalog ("non-portable", // "dialect-specific", "aren't/isn't standard", "not standard SQL"). Excludes // idempotency/other concerns, which never use this language. const isPortability = /portab|dialect[ -]specific|non-?standard|n't standard|not standard|standard sql/i.test( f.body, ) if (coreFns?.size && isPortability && fnTokensOf(`${f.title} ${f.body}`).some((t) => coreFns.has(t))) return false return true }) // Without a compiled base (raw Jinja on the old side) the regex PII twins can't // tell a new column from one the base already exposed: report them like the // other PII lanes, as a warning of unknown confidence that never blocks. // Unless the raw base proves the column new (`rawBaseLacks`): then the twin // keeps its severity and is marked, so it counts toward the verdict as the // one pattern finding that blocks without being named in `blockingRules`. for (const [i, f] of merged.entries()) { const rule = (f.evidence?.result as { rule?: string } | undefined)?.rule if (f.category !== "pii_exposure" || (rule !== "pii_into_mart" && rule !== "select-pii-columns")) continue const ctx = ctxByPath.get(f.file) if (!ctx || !hasOldSide(ctx.file)) continue if (provenNewTwin(f)) { if (f.evidence) merged[i] = { ...f, evidence: { ...f.evidence, result: { ...(f.evidence.result as object), provenNew: true } } } continue } // A readable base: the twin keeps its severity, as advice. if (ctx.engineOldSql) continue merged[i] = { ...f, severity: f.severity === "critical" ? "warning" : f.severity, confidence: "unknown" } } // The findings a reader sees before the severity threshold: deduped, rubric // exclusions and off-engine portability advice dropped, repeats merged, most // severe first. The AI lane is grounded in this list (its prompt keeps the // top 40), so dropped or repeated findings don't crowd out real ones. const scopedFiles = [...input.changedFiles, ...(input.aiOutsideFiles ?? [])] // Why a finding is hidden from what is posted: its rule is `off` in the // posting policy, or it is on the not-posted list (rules-off.ts) on a file // the AI lane reviewed. Either way it is listed in the envelope's `withheld` // and counts toward the verdict as described where `verdictFindings` is // built. `notPostedOn` stays empty until the AI lane has answered. let notPostedOn = new Set() const hiddenReason = (f: Finding): "rule_off" | "not_posted" | undefined => ruleTier(f.rule, input.config.rules, dialect) === "off" ? "rule_off" : notPostedOn.has(f.file) && hiddenByRulesOff(f, input.rulesOff?.ids) ? "not_posted" : undefined const cleanFindings = (list: Finding[], merge = true, keepOff = false): Finding[] => { let out = dedupe(list) .filter((f) => !exclusionReason(f, input.rubric)) .map((f) => { // The matched source text some lanes record, used to anchor the finding. It is // PR text: URL userinfo and credential-shaped values are masked. It never reaches // posted text or the envelope (`publicEvidence`). const line = (f.evidence?.result as { line?: unknown } | undefined)?.line if (typeof line !== "string") return f return { ...f, evidence: { ...f.evidence!, result: { ...(f.evidence!.result as object), line: maskForAi(line)! } } } }) // Per-rule posting policy: `off` rules are dropped from what is shown (and // so never ground the AI lane), unless `keepOff` asks for them (the verdict // and the withheld counts); the rest are marked for inline or summary-only posting. out = out .filter((f) => keepOff || !hiddenReason(f)) .map((f) => ({ ...f, tier: ruleTier(f.rule, input.config.rules, dialect) === "inline" ? ("inline" as const) : ("summary" as const) })) // Cross-engine portability advice from the regex catalog is noise for a // project that runs on one known engine. Core's dialect-aware check (a // function missing on THIS engine) is a real error and is kept. if (input.suppressPortability) out = out.filter((f) => !isSuppressiblePortability(f, dialect, input.portabilityTargets)) // Outside-project files the AI lane reads are classified like in-project ones. out = markPreExisting(anchorByEvidence(out, scopedFiles), scopedFiles) if (merge) out = mergeRepeats(out) return out.sort((a, b) => SEVERITY_ORDER[b.severity] - SEVERITY_ORDER[a.severity] || a.file.localeCompare(b.file)) } // AI reviewer lane — runs AFTER the deterministic lanes so it can be GROUNDED // in (and told not to duplicate) the engine findings. Advisory only: its // findings are clamped to ≤ warning upstream, so they enrich the review but // never change what blocks. Skipped when no aiReview fn is injected (tests / // headless-without-model) — the review degrades to deterministic-only. let aiStatus: AiLaneStatus | undefined let aiEngineFailures = new Map() // Files the AI lane reviewed (sent in a call that answered); outside-project ones apart. const aiReviewed = new Set() let aiReviewedOutside: string[] = [] // For the rule verifier after the lane: the verifier's evidence, the lane's deadline, and the // text of the files the lane was given (screened for key material like the lane's opt-in files). let ruleEvidence: AiVerifyEvidence | undefined let laneDeadlineAt = 0 const laneText = new Map>() let aiBlocked: ReadonlySet = new Set() if (!lanes.has("ai_review")) { aiStatus = { state: "skipped", reason: `not part of the ${tier} tier` } } else if (!input.aiReview) { aiStatus = { state: "skipped", reason: input.aiDisabledReason ?? "disabled" } } else { // Never sent to the provider by any lane, whatever its kind (`aiScreen`): listed in // `ai.notSent` with the reason; the deterministic lanes read these files as before. const screen = aiScreen(input.isSymlink) const sendable = (f: { path: string; oldPath?: string }, texts: Array) => screen.allow(f, async () => texts) const aiFiles: AiReviewFile[] = [] for (const ctx of ctxByPath.values()) { const sql = ctx.engineNewSql ?? ctx.newSql if (!(await sendable(ctx.file, [ctx.file.diff, sql, ctx.newSql]))) continue aiFiles.push({ path: ctx.file.path, status: ctx.file.status, model: modelNameFromPath(ctx.file.path), kind: ctx.file.kind, diff: ctx.file.diff, sql, }) } // Macros, data tests, snapshots, yml and seeds carry defects no model diff shows. // Seeds go as a diff only: the full CSV is data, not logic. Their text is masked // (URL userinfo, credential-shaped values) before it leaves for the provider. const byPath = (a: { path: string }, b: { path: string }) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0) // A file whose name says it can hold credentials (connection profiles, env files, keys) is // withheld before its content is read, and listed. const supporting = reviewable.filter((f) => AI_SUPPORTING_KINDS.has(f.kind) && f.status !== "deleted").sort(byPath) for (const f of supporting) { let content: string | undefined const ok = await screen.allow(f, async () => { content = f.kind === "seed" ? undefined : await getContent?.(f.path, "new")?.catch(() => undefined) return [f.diff, content] }) if (ok) aiFiles.push({ path: f.path, status: f.status, model: modelNameFromPath(f.path), kind: f.kind, diff: maskForAi(f.diff), sql: maskForAi(content) }) } // Opt-in kinds no rule lane reads (`otherFiles`, `pythonFiles`; both off by default): masked // (`maskOptInFile`, stricter than for dbt files) and new side only, the diff's added and // context lines and the head content, so a PR that removes a secret from such a file does // not send it. Never credential-named files, CI workflows, compose files or env files // (`isCiOrEnvFile`), nor the user's exclusions. // `rank` keeps the groups in order (other files, then Python inside the project, then outside it). const optIn: Array<{ f: ChangedFile; kind: string; rank: number }> = [] if (switchOn("otherFiles", input.aiSwitches)) { const root = input.layout?.root for (const f of reviewable) if ( isAiOtherFile(f) && !isCiOrEnvFile(f.path) && // A team convention file is read from the base only; its PR version is never sent. !isConventionFile(f.path) && (root === undefined || relativeToRoot(f.path, root) !== undefined) ) optIn.push({ f, kind: f.kind, rank: 0 }) } if (switchOn("pythonFiles", input.aiSwitches)) { const queued = new Set([...aiFiles.map((f) => f.path), ...optIn.map((o) => o.f.path)]) const inProject = new Set(reviewable.map((f) => f.path)) for (const f of [...reviewable, ...(input.aiOutsideFiles ?? [])]) if ( isAiPythonFile(f) && !isCiOrEnvFile(f.path) && !isExcludedPath(f.path, input.rubric.exclusions.excludeGlobs) && !queued.has(f.path) ) { queued.add(f.path) optIn.push({ f, kind: AI_PYTHON_KIND, rank: inProject.has(f.path) ? 1 : 2 }) } } optIn.sort((a, b) => a.rank - b.rank || byPath(a.f, b.f)) for (const { f, kind } of optIn) { let sql: string | undefined const ok = await screen.allow(f, async () => { sql = await getContent?.(f.path, "new")?.catch((err) => { // The file is still sent with its diff; the error goes to the job log only. reportFailure("ai_error", { check: "input", path: f.path, side: "head" }, err) return undefined }) return [f.diff, sql] }) if (!ok) continue aiFiles.push({ path: f.path, status: f.status, model: modelNameFromPath(f.path), kind, diff: maskOptInFile(newSideDiff(f.diff)), sql: maskOptInFile(sql), }) } // Engine calls the AI lane makes (context cards, verifier tools) are // advisory: a failure there is the lane's, never an engine error of the // review, so it cannot make the run unapprovable. Counted here and taken // out of `engineErrors` below. const failuresBefore = engineFailureCounts(input.runner) // Cards only for the files the lane will send (its file cap, or the // per-kind quotas in coverage mode); coverage is marked after it answers. const laneFiles = aiLaneFiles(aiFiles, input.aiSwitches) const cardsFailed = input.aiContextCard && anyManifest ? await attachContextCards(laneFiles, input.runner) : 0 const context = input.aiGraphContext ? await aiGraphContext(aiFiles.map((f) => f.path), input.runner, getContent, screen) : undefined // Paths of the files the PR changes, for the test-gap list and the verifier's test files: // never the user's exclusions or a credential-named file. const prFiles = (input.prFiles ?? input.changedFiles.map((f) => f.path)).filter( (p) => !isExcludedPath(p, input.rubric.exclusions.excludeGlobs) && !mayHoldCredentials(p) && !screen.blocked.has(p), ) // The verifier reads engine SQL first (the same SQL the engine lanes saw), then compiled output. const evidence: AiVerifyEvidence | undefined = input.aiVerify ? { dialect, // The tools read dbt files only: an opt-in file (`otherFiles`, `pythonFiles`) gives // its finding a hunk (already masked, new side) but is never readable by a tool. files: aiFiles.filter((f) => !AI_ONLY_KINDS.has(f.kind ?? "")), hunkFiles: aiFiles.filter((f) => AI_ONLY_KINDS.has(f.kind ?? "")), projectRoot: input.layout?.root, dirs: input.layout?.dirs, runner: input.runner, addedLines: addedLinesByFile( [...input.changedFiles, ...(input.aiOutsideFiles ?? [])].filter( (f) => !mayHoldCredentials(f.path) && !screen.blocked.has(f.path), ), ), prTitle: input.prTitle, prBody: input.prBody, projectFiles: input.projectFiles, grepFiles: input.grepFiles, isSymlink: screen.symlink, withheld: screen.blocked, prTestFiles: prFiles, pythonTests: switchOn("pythonFiles", input.aiSwitches), readFile: async (p, side) => getContent?.(p, side), ...(input.conventions?.length ? { conventions: conventionTexts(input.conventions) } : {}), compiledSql: async (p, side) => { const ctx = ctxByPath.get(p) const engine = side === "new" ? ctx?.engineNewSql : ctx?.engineOldSql return engine ?? (await getCompiled?.(ctx?.file.oldPath && side === "old" ? ctx.file.oldPath : p, side)) }, } : undefined // What the reader will see of the engine's findings: the verifier treats // only these as already reported. Rule types on the not-posted list are // left out: on a file the lane reviews they will not be shown. const grounding = cleanFindings(merged).filter((f) => !screen.blocked.has(f.file)) const shownGrounding = grounding.filter( (f) => SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[input.config.severityThreshold] && !f.preExisting && !hiddenByRulesOff(f, input.rulesOff?.ids), ) ruleEvidence = evidence for (const f of aiFiles) laneText.set(f.path, [f.diff, f.sql]) // A lane that never returns (a provider that ignores its abort signal) // cannot hold the review: past the deadline the run continues without it. // The rule verifier after it runs within the same deadline. const laneGuard = new AbortController() const laneMs = input.aiLaneTimeoutMs ?? aiLaneTimeoutMs() + 60_000 laneDeadlineAt = Date.now() + laneMs const laneTimer = setTimeout(() => laneGuard.abort(), laneMs) try { const res = await untilAborted( () => input.aiReview!({ files: aiFiles, context, grounding, prTitle: input.prTitle, prBody: input.prBody, model: input.aiModel, prFiles, ...(evidence ? { evidence, shownGrounding } : {}), ...(input.aiSwitches ? { switches: input.aiSwitches } : {}), ...(otherChecked.size ? { checkedPaths: [...otherChecked] } : {}), ...(input.reviewDir ? { reviewDir: input.reviewDir } : {}), ...(input.conventions?.length ? { conventions: input.conventions } : {}), }), laneGuard.signal, ) const aiFindings = Array.isArray(res) ? res : res.findings aiStatus = Array.isArray(res) ? { state: "ok" } : res.status // Coverage only for files the AI actually reviewed: within the lane's file // cap, in calls that answered. A failed or skipped lane covers nothing; a // replay (no `reviewedPaths`) covers the lane's files minus its failed calls'. if (aiStatus.state === "ok") { const lost = new Set(aiStatus.unreviewed ?? []) const reviewed = Array.isArray(res) || !res.reviewedPaths ? laneFiles.map((f) => f.path).filter((p) => !lost.has(p)) : res.reviewedPaths for (const p of reviewed) aiReviewed.add(p) touch(reviewed.map((p) => ({ path: p }))) } const outsidePaths = new Set((input.aiOutsideFiles ?? []).map((f) => f.path)) aiReviewedOutside = [...aiReviewed].filter((p) => outsidePaths.has(p)) // Defense in depth: the AI never blocks, regardless of what it returns, and an AI finding // never takes a deterministic finding's id (a replayed envelope can carry any id): it would // replace that finding in the dedupe, in the posted list and in the verdict. const deterministicIds = new Set(merged.map((f) => f.id)) for (const f of aiFindings) { if (deterministicIds.has(f.id)) continue merged.push(maskedAiFinding(f.severity === "critical" ? { ...f, severity: "warning" } : f)) } } catch (err) { // A failed AI lane must never fail the review — but it must say so. // Past the outer deadline the lane's files were not reviewed: named, as an inner timeout names them. const unreviewed = laneFiles.map((f) => f.path) aiStatus = laneGuard.signal.aborted ? { state: "timeout", reason: LANE_DEADLINE_REASON, ...(unreviewed.length ? { unreviewed } : {}) } : { state: "error", reason: reportFailure("ai_error", { check: "request" }, err).message } } finally { clearTimeout(laneTimer) } if (screen.reasons.size && aiStatus) { const notSentReasons = [...screen.reasons].map(([path, reason]) => ({ path, reason })).sort((a, b) => byPath(a, b)) aiStatus = { ...aiStatus, notSent: notSentReasons.map((r) => r.path), notSentReasons } } aiBlocked = screen.blocked // Only for a lane that sent something: a skipped lane used no card. if (cardsFailed && aiStatus && aiStatus.state !== "skipped") aiStatus = { ...aiStatus, cardsFailed } // Every convention file found at the base commit, loaded or skipped, whatever the lane did. if (input.conventionRecords?.length && aiStatus) aiStatus = { ...aiStatus, conventions: input.conventionRecords } aiEngineFailures = engineFailureDelta(failuresBefore, engineFailureCounts(input.runner)) const lost = [...aiEngineFailures.values()].reduce((n, c) => n + c, 0) if (lost && aiStatus?.verifier) aiStatus = { ...aiStatus, verifier: { ...aiStatus.verifier, toolErrors: (aiStatus.verifier.toolErrors ?? 0) + lost } } } // Flatten, drop excluded, dedupe, threshold-filter. const validated = await validateSuggestions( merged, getContent, addedLinesByFile([...input.changedFiles, ...(input.aiOutsideFiles ?? [])]), ) const minSev = SEVERITY_ORDER[input.config.severityThreshold] // The not-posted list applies only where the AI lane reviewed the file (a call that answered). // A file the model saw cut is not one it reviewed whole: the list does not apply there. if (aiStatus?.state === "ok" && input.rulesOff?.ids.size) { const cut = new Set(aiStatus.truncated ?? []) notPostedOn = new Set([...aiReviewed].filter((p) => !cut.has(p))) } // A line the model names is checked against the file's diff before it may be posted inline: a // line outside every hunk (or past the end of the file) keeps its place in the summary only. const hunkLines = new Map(scopedFiles.map((f) => [f.path, scanDiffLines(f.diff).commentable])) let findings = cleanFindings(validated) .filter((f) => SEVERITY_ORDER[f.severity] >= minSev) .map((f) => findingOrigin(f) === "ai" && f.tier === "inline" && typeof f.startLine === "number" && !hunkLines.get(f.file)?.has(f.startLine) ? { ...f, tier: "summary" as const } : f, ) // The verdict counts every instance; merging repeats is presentation only. // A hidden finding (`off` tier, not-posted list, refuted by the rule // verifier) is never removed from the verdict: every verdict-eligible // instance counts, and each hidden one is listed in the envelope. const allInstances = cleanFindings(validated, false, true).filter((f) => SEVERITY_ORDER[f.severity] >= minSev) // The rule verifier: catalog findings the review would post, after the AI // lane answered. Only a refutation grounded in a tool result of its batch // hides one (ai-verify-rules.ts); engine, critical and AI findings are never // sent (an AI finding never merges into a rule finding's comment, see // `mergeRepeats`), nor a file whose name or text can hold credentials (the // AI lane's screen). const screenedOut = (p: string) => mayHoldCredentials(p) || aiBlocked.has(p) || (laneText.get(p) ?? []).some((t) => holdsCredentials(t)) const ruleCandidates = findings.filter( (f) => findingOrigin(f) === "catalog" && f.severity !== "critical" && !screenedOut(f.file), ) let ruleVerifier: RuleVerifierStatus | undefined const refuted = new Set() if (switchOn("verifyRules", input.aiSwitches) && input.aiRuleVerify && ruleEvidence && ruleCandidates.length) { if (aiStatus?.state !== "ok") { ruleVerifier = skippedRuleVerifier(RULE_VERIFIER_NOT_RUN, ruleCandidates.length) } else { // Advisory like the lane: its engine calls (verifier tools) are the lane's failures, never // engine errors of the review. const before = engineFailureCounts(input.runner) const guard = new AbortController() const timer = setTimeout(() => guard.abort(), Math.max(0, laneDeadlineAt - Date.now())) try { ruleVerifier = await untilAborted( () => input.aiRuleVerify!({ findings: ruleCandidates, grounding: [], evidence: ruleEvidence!, model: input.aiModel }, { abort: guard.signal }), guard.signal, ) } catch (err) { ruleVerifier = { ...skippedRuleVerifier("", ruleCandidates.length), ...(guard.signal.aborted ? { state: "timeout" as const, reason: RULE_VERIFIER_DEADLINE } : { state: "error" as const, reason: reportFailure("ai_error", { check: "rule_verifier" }, err).message }), } } finally { clearTimeout(timer) } let lost = 0 for (const [method, n] of engineFailureDelta(before, engineFailureCounts(input.runner))) { aiEngineFailures.set(method, (aiEngineFailures.get(method) ?? 0) + n) lost += n } ruleVerifier = publicRuleVerifier(ruleVerifier, ruleCandidates.length, lost) // Only ids that were sent, and only a grounded refutation. const sentIds = new Set(ruleCandidates.map((f) => f.id)) for (const v of ruleVerifier.verdicts ?? []) if (v.grounded && sentIds.has(v.id)) refuted.add(v.id) findings = findings.filter((f) => !refuted.has(f.id)) ruleVerifier = { ...ruleVerifier, withheld: refuted.size } } } const refutedInstance = (f: Finding) => refuted.has(f.id) || refuted.has(repeatGroupId(f)) const withheldReason = (f: Finding) => hiddenReason(f) ?? (refutedInstance(f) ? ("refuted" as const) : undefined) // A rule set to `off` that cannot count toward the verdict is not reported at // all (the posting policy). The not-posted list and the rule verifier never // change the verdict or the tally: every instance they hide still counts. const verdictFindings = allInstances.filter((f) => hiddenReason(f) !== "rule_off" || verdictEligible(f, input.rubric)) type Withheld = NonNullable[number] const withheldBy = new Map; at: string[] }>() for (const f of allInstances) { const reason = withheldReason(f) if (!reason) continue const rule = f.rule ?? "unknown" const key = `${rule}\0${reason}` const w = withheldBy.get(key) ?? { rule, reason, count: 0, verdict: 0, at: [], findings: [] } const counts = verdictEligible(f, input.rubric) w.count++ if (counts) { w.verdict++ const loc = f.file + (f.startLine ? `:${f.startLine}` : "") if (w.at.length < 5 && !w.at.includes(loc)) w.at.push(loc) } w.findings.push({ id: f.id, file: f.file, ...(f.startLine ? { line: f.startLine } : {}), severity: f.severity, verdict: counts }) // Off by the default tier table, not by a `rules:` entry: the banner says so. if (reason === "rule_off" && !overrideTier(rule, input.config.rules)) w.byDefault = true withheldBy.set(key, w) } // Whether the hidden findings decide anything: the verdict with them all shown (an `off` // suggestion included, which turns APPROVE into COMMENT) differs from the verdict without them. const withheldDecides = withheldBy.size > 0 ? computeIdealVerdict(verdictFindings.filter((f) => !withheldReason(f)), input.rubric) !== computeIdealVerdict(allInstances, input.rubric) : undefined const withheld: Withheld[] = [...withheldBy.values()] .map(({ at, ...w }) => ({ ...w, ...(at.length ? { at } : {}) })) .sort((a, b) => a.rule.localeCompare(b.rule) || (a.reason ?? "").localeCompare(b.reason ?? "")) if (aiStatus && (input.rulesOff || ruleVerifier)) { aiStatus = { ...aiStatus, ...(input.rulesOff && aiStatus.state !== "skipped" ? { notPosted: { source: input.rulesOff.source, rules: [...input.rulesOff.ids].sort(), ...(input.rulesOff.error ? { error: input.rulesOff.error } : {}), }, } : {}), ...(ruleVerifier ? { ruleVerifier } : {}), } } // Lint-only means no changed model resolved against a manifest. A single // undecidable finding does not make the whole run lint-only; those findings // carry their own `degraded` flag and are counted separately in the summary. const degraded = runDegraded const engineErrors = [ ...withoutAiFailures(input.runner.failures?.() ?? [], aiEngineFailures), ...laneErrors, ...listErrors, ...validationErrors, ] // An exception in the review's own code (a lane, a file's pre-compute) is a // fault in the review itself, unlike an engine reporting failure, a missing // compile or a side that could not be read. const internalFailure = hasInternalFailure([...laneErrors, ...unverified]) // Coverage ledger: every changed file the review did not look at, and why. // First reason per path wins; `unverified` entries are always kept. const sortedUnverified = unverified.sort((a, b) => a.path.localeCompare(b.path) || (a.reason < b.reason ? -1 : a.reason > b.reason ? 1 : 0)) // An outside-project file the AI lane reviewed is not "outside the dbt project, not reviewed". const aiReviewedSet = new Set(aiReviewedOutside) const inputNotReviewed = (input.scope?.notReviewed ?? []).filter((n) => !aiReviewedSet.has(n.path)) const ledger: NotReviewed[] = [ ...inputNotReviewed, ...dropped, ...reviewable // Other/analysis files the AI lane reviewed (`otherFiles`, `pythonFiles`) are covered; a // file in a call that failed, or a lane that errored or timed out, is not. .filter((f) => ((f.kind === "other" && !otherChecked.has(f.path)) || f.kind === "analysis") && !aiReviewed.has(f.path)) .map((f) => ({ path: f.path, reason: "not a dbt model/macro/test/yml/seed file" })), ...reviewable .filter((f) => !touched.has(f.path)) .map((f) => ({ path: f.path, reason: `no checks run for ${f.kind} files at the ${tier} tier` })), ...(manifestMissing && !anyManifest ? modelFiles.map((f) => ({ path: f.path, reason: "no dbt manifest: lineage, config and graph checks skipped" })) : []), ] const seen = new Set() const byPathReason = (a: NotReviewed, b: NotReviewed) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.reason < b.reason ? -1 : a.reason > b.reason ? 1 : 0 const notReviewed = ledger.filter((e) => !seen.has(e.path) && !!seen.add(e.path)).sort(byPathReason) notReviewed.push(...sortedUnverified) const envelope = buildEnvelope({ engineErrors: engineErrors.length ? engineErrors : undefined, internalFailure, ai: aiStatus, policy: input.policy, findings: findings.map(publicEvidence), verdictFindings, withheld, withheldDecides, tier, mode: input.mode, rubric: input.rubric, engine: { core: input.coreVersion, model: input.modelVersion, cliVersion: input.cliVersion }, manifestHash: input.manifestHash, staleManifest: input.staleManifest, generatedAt: input.generatedAt, degraded, scope: input.scope || notReviewed.length || disabledModels.length ? { ...input.scope, disabledModels: disabledModels.length ? disabledModels.sort() : undefined, ...(aiReviewedOutside.length ? { aiReviewedOutside } : {}), unverified: sortedUnverified.length ? sortedUnverified : undefined, notReviewed, } : undefined, // Include tierReasons whenever `--explain-tier` / `--force-tier` is set, // when a riskTierPathTokens config error was caught above, OR when the // classifier lands on `full` tier — a naturally-full run is a customer- // visible policy call ("why did my YAML-only diff get REQUEST_CHANGES?") // and the reason list is what makes the verdict debuggable without the // customer having to re-run with --explain-tier. `trivial`/`lite` runs // stay silent to avoid noise on approvals. tierReasons: input.explainTier || tierForced || pathTokenConfigError || tier === "full" ? tierReasons : undefined, tierForced: tierForced ? true : undefined, tierClassified: tierForced ? classifiedTier : undefined, }) return signEnvelope(envelope) }