From 43774e5686b0fb2e4730be6aa575d67794b496ef Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 3 Dec 2026 22:44:24 +0530 Subject: [PATCH 01/39] fix(review): follow-ups from the failure-reporting review - Exit 3 is decided by category; the CLI test restores the exit code. - A base that could not be analysed leaves PII undecided, never critical. - An interrupted fetch stops the deepen loop instead of carrying on. - The log label and the disabled-model note say what happened. Co-Authored-By: Claude Fable 5.2 --- docs/docs/usage/dbt-pr-review.md | 22 +++-- .../opencode/src/altimate/review/failure.ts | 25 ++++-- .../opencode/src/altimate/review/format.ts | 2 +- packages/opencode/src/altimate/review/git.ts | 23 ++++- .../src/altimate/review/orchestrate.ts | 46 ++++++---- .../opencode/src/altimate/review/runner.ts | 3 +- .../opencode/src/altimate/review/verdict.ts | 9 +- .../test/altimate/review-ci-honesty.test.ts | 2 +- .../altimate/review-failures-gate.test.ts | 87 +++++++++++++++++-- .../altimate/review-incomplete-run.test.ts | 74 +++++++++++++++- 10 files changed, 242 insertions(+), 51 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 5aa3c43264..8af13f3233 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -473,15 +473,17 @@ rubric: errors can quote connection strings, row values or tokens. It names the engine check that failed (with a count), or the file whose review failed with a fixed sentence for the kind of failure. The message itself is in the - job log, masked, and cut after the first credential it holds (nothing after - it is printed), on a line that starts with `altimate review:`, the kind, + job log, masked, and cut after the first masked value (nothing after it is + printed, and the line ends "(rest withheld after a masked value)"), on a line that starts with `altimate review:`, the kind, and the check or file (for example `altimate review: engine_error check=columnLineage: …`). The envelope records the kind as `category` on `engineErrors` entries (`engine_error`, `internal_error`) and on failed files in `scope.unverified` (`internal_error`, `file_unreadable`); a failed AI lane sets `ai.state` to `error` with a fixed reason and logs `ai_error`. A failed `git fetch` stops the review with a fixed message, and its log line carries - `git_fetch_failed` or `git_fetch_timeout`. A project + `git_fetch_failed` or `git_fetch_timeout`. The one exception is data diff: + its driver message can quote warehouse row values, so its log line carries + only the class of failure (see "Data-diff in CI"). A project reviewed without `dbt compile` (parse-only) therefore never gets APPROVE for a changed Jinja model. A failure on one file marks that file unverified and the rest of the PR is still reviewed, and so does a changed model whose head @@ -507,12 +509,14 @@ rubric: verified)", and is listed as "compared without compiled base SQL". A changed model that the manifest marks disabled (`enabled: false`, or listed only under `disabled`) is not built by dbt, so it has no compiled SQL by design: - that is not counted as a gap and does not hold back approval. Every check - that reads the model's own SQL still runs (the catalog, dbt patterns, PII, - and the engine checks when compiled SQL exists), since "disabled" comes from - the PR's own manifest. The model is listed as "disabled in this manifest: - dbt does not build them, so no compiled SQL is expected; the checks that - read the model's own SQL still ran". The exemption applies only when the + that is not counted as a gap and does not hold back approval. The checks + that read its raw SQL (the catalog and dbt patterns) still run, since + "disabled" comes from the PR's own manifest; the engine checks (PII, + lineage, equivalence) run only when compiled SQL exists for it, which for a + disabled model is usually not the case. The model is listed as "disabled in this manifest: + dbt does not build them, so no compiled SQL is expected; the catalog and + dbt-pattern checks still ran; the PII and engine checks need compiled SQL". + The exemption applies only when the manifest is newer than the model file; with an older manifest the model counts as having no compiled head SQL. A model disabled only in some targets (`enabled: "{{ target.name != 'ci' }}"`) is judged by the manifest you pass. diff --git a/packages/opencode/src/altimate/review/failure.ts b/packages/opencode/src/altimate/review/failure.ts index 1d1deb4905..225dac515d 100644 --- a/packages/opencode/src/altimate/review/failure.ts +++ b/packages/opencode/src/altimate/review/failure.ts @@ -7,9 +7,11 @@ import { errorReason, type FailureCategory } from "./verdict" * error: an engine, git, file system or model message can quote a connection * string, a row value or a token, and no masking pattern catches every shape. * They carry a category from this closed set, structured facts that are not - * free text, and a fixed sentence written here. (One kind of text is not an - * error and is not covered: `tierReasons` can carry the validation message for - * a bad `riskTierPathTokens` value in the base branch's config.) The error + * free text, and a fixed sentence written here. One exception, as on main: + * `tierReasons` can carry the message of the validation error thrown for a bad + * `riskTierPathTokens` value in the base branch's config, and it reaches the + * comment and the envelope. That message is config text, not driver or + * provider output. The error * itself goes to the job log (stderr) through `logDetail`, on a line that * starts with the same category, check and file, so a reader can find it. The * categories are `FailureCategory` in `verdict.ts`. @@ -71,14 +73,14 @@ function knownCode(err: unknown): string | undefined { } const REDACTED = "[REDACTED]" -const WITHHELD = " (rest withheld: the message holds a credential)" +const WITHHELD = " (rest withheld after a masked value)" /** * An error as text for the job log, which is public in a public repository's - * CI. It is masked by `errorReason`, and once a credential is found nothing - * after it is printed: the masker can misjudge where a value ends (a bare - * value followed by a quoted one with spaces), and the rest of a message that - * held a credential is not needed to find the failure. + * CI. It is masked by `errorReason`, and nothing after the first masked value + * is printed: the masker can misjudge where a value ends (a bare value + * followed by a quoted one with spaces), and the rest of the message is not + * needed to find the failure. */ export function logDetail(err: unknown): string { const masked = errorReason(err, 2000) @@ -114,3 +116,10 @@ export function reportFailure(category: FailureCategory, facts: FailureFacts, er process.stderr.write(`altimate review: ${category}${where ? ` ${where}` : ""}: ${detail}\n`) return { category, ...all, message: sentence(category, all) } } + +/** True when some failure is an exception in the review's own code. Decided by + * category, never by which list an entry is in: an engine failure or an + * unreadable file exits as before, whatever collected it. */ +export function hasInternalFailure(entries: ReadonlyArray<{ category?: FailureCategory }>): boolean { + return entries.some((e) => e.category === "internal_error") +} diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 8e405ea19e..81e594a3f9 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -441,7 +441,7 @@ export function coverageNotes(env: VerdictEnvelope, maxChars = Infinity): string const paths = env.scope.disabledModels notes.push( `${paths.length} model(s) disabled in this manifest: dbt does not build them, so no compiled SQL is expected; ` + - "the checks that read the model's own SQL still ran: " + + "the catalog and dbt-pattern checks still ran; the PII and engine checks need compiled SQL: " + `${paths.slice(0, 5).map(codeSpan).join(", ")}${paths.length > 5 ? ` and ${paths.length - 5} more` : ""}.`, ) } diff --git a/packages/opencode/src/altimate/review/git.ts b/packages/opencode/src/altimate/review/git.ts index 43e451805c..4f4a24a762 100644 --- a/packages/opencode/src/altimate/review/git.ts +++ b/packages/opencode/src/altimate/review/git.ts @@ -29,6 +29,15 @@ const STDERR_TAIL = 4096 const FETCH_TIMED_OUT = "git fetch timed out" const timedOut = (e: unknown) => e instanceof Error && e.message.startsWith(FETCH_TIMED_OUT) +/** A fetch stopped by SIGINT or SIGTERM: the run is being cancelled, so no + * caller may retry or carry on with another fetch. */ +export class FetchInterrupted extends Error { + constructor(readonly signal: NodeJS.Signals) { + super(`git fetch interrupted by ${signal}`) + this.name = "FetchInterrupted" + } +} + /** A failed fetch for the "not available locally" error: a category and its * fixed text (`git fetch timed out after N s`, `git fetch failed (exit code * N)`). The detail goes to the job log: git's `fatal:` line (`fatal: … @@ -84,7 +93,7 @@ function gitFetch(args: string[], cwd: string, timeoutMs: number): Promise settle() // Settle now: with another handler keeping this process alive, the // caller must not wait on a child that may never report closing. - reject(new Error(`git fetch interrupted by ${signal}`)) + reject(new FetchInterrupted(signal)) if (process.listenerCount(signal) === 0) process.kill(process.pid, signal) } process.once("exit", onExit) @@ -344,6 +353,7 @@ async function fetchTargetHistory( timeoutMs, ) } catch (e) { + if (e instanceof FetchInterrupted) throw e throw fetchFailure(e) } if (await found()) return true @@ -359,12 +369,16 @@ async function fetchTargetHistory( await deepen(["fetch", "--no-tags", `--deepen=${depth}`, "origin", target]) if (await found()) return true // A head the remote does not serve (a local commit, a fork's head) is not - // fatal: the target's own deepening may still reach the merge-base. A - // timeout is: the remote is stalled, and the next deepen would stall too. + // fatal: git exits non-zero and the target's own deepening may still + // reach the merge-base. Anything else is: a timeout (the remote is + // stalled, and the next deepen would stall too), an interruption, or a + // fetch that could not start. await deepen(["fetch", "--no-tags", `--deepen=${depth}`, "origin", target, headSha]).catch((e) => { - if (timedOut(e)) throw e + if (timedOut(e) || e instanceof FetchInterrupted || typeof (e as { exitCode?: unknown })?.exitCode !== "number") + throw e }) } catch (e) { + if (e instanceof FetchInterrupted) throw e throw fetchFailure(e) } if (await found()) return true @@ -423,6 +437,7 @@ export async function resolveReviewBase(opts: ResolveBaseOptions): Promise fetchTargetHistory(target.branch, head, opts.cwd, find, opts.fetchTimeoutMs).catch((e: Error) => { + if (e instanceof FetchInterrupted) throw e why = ` (${e.message})` return false }) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 6904502efb..3396b408ed 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -48,7 +48,7 @@ import { selectSources, } from "./rule-catalog" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult } from "./ai-review" -import { reportFailure } from "./failure" +import { hasInternalFailure, reportFailure } from "./failure" /** * The deterministic review recipe. @@ -1070,6 +1070,8 @@ async function piiClassifyLane( 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 @@ -1080,6 +1082,9 @@ async function piiClassifyLane( // 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 @@ -1091,6 +1096,7 @@ async function piiClassifyLane( 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 @@ -1118,13 +1124,16 @@ async function piiClassifyLane( // 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 that could not be analysed leaves every column undecided, as in the + // fallback path: a warning that never blocks, whatever the raw base shows. + const baseUnanalysed = baseAbstained || baseUnresolved 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 undecided = baseUnknown && !baseLacks(col) + const undecided = baseUnanalysed || (baseUnknown && !baseLacks(col)) const highConfidence = p.confidence >= 0.9 const severity: Severity = highExposureLayer && highConfidence && !lowRiskClass && !undecided ? "critical" : "warning" out.push( @@ -1135,7 +1144,8 @@ async function piiClassifyLane( body: `This change surfaces a **${p.classification}**-classified column \`${p.column}\` ` + `(confidence ${(p.confidence * 100).toFixed(0)}%). Confirm masking / access policy before merging to a non-restricted schema` + - (p.masking ? `; suggested masking: \`${p.masking}\`.` : "."), + (p.masking ? `; suggested masking: \`${p.masking}\`.` : ".") + + (baseUnanalysed ? PII_UNDECIDED_BASE_UNANALYSED : ""), file: file.path, model, // Without a base, exposure is undecided: `unknown` keeps these warnings @@ -1797,17 +1807,6 @@ export async function runReview(input: OrchestrateInput): Promise { - const diffScopedPii = await piiClassifyLane(currentCtx, input.runner, dialect, (col) => baseLacksOutput(currentCtx.file.path, col)) - 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] let basePii = new Set() let baseAbstained = false if (hasOldSide(currentCtx.file) && currentCtx.engineOldSql) { @@ -1820,6 +1819,23 @@ export async function runReview(input: OrchestrateInput): Promise baseLacksOutput(currentCtx.file.path, col), + baseAbstained, + ) + 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) — @@ -2348,7 +2364,7 @@ export async function runReview(input: OrchestrateInput): Promise 0 || unverified.some((u) => u.category === "internal_error") + const internalFailure = hasInternalFailure([...laneErrors, ...unverified]) const envelope = buildEnvelope({ engineErrors: engineErrors.length ? engineErrors : undefined, diff --git a/packages/opencode/src/altimate/review/runner.ts b/packages/opencode/src/altimate/review/runner.ts index 1fed479bd5..3b6fc716a6 100644 --- a/packages/opencode/src/altimate/review/runner.ts +++ b/packages/opencode/src/altimate/review/runner.ts @@ -131,7 +131,8 @@ function dataDiffSkipped(message: string, warehouse?: string): boolean { /** The class of a `data.diff` failure, a public fact: driver messages can quote * warehouse row values (`invalid input syntax for type integer: ""`), so only the class is shown and the message goes to the job log. */ + * email>"`), so only the class is shown, and the job log too gets only the + * class, never the message (`reportFailure`). */ function dataDiffClass(message: string): "timeout" | "connection" | "query" | "unknown" { return /timed? ?out|timeout|etimedout/i.test(message) ? "timeout" diff --git a/packages/opencode/src/altimate/review/verdict.ts b/packages/opencode/src/altimate/review/verdict.ts index 4c8796cb03..3578fd8bef 100644 --- a/packages/opencode/src/altimate/review/verdict.ts +++ b/packages/opencode/src/altimate/review/verdict.ts @@ -474,7 +474,9 @@ function maskSecretValues(text: string): string { // braced one with spaces (the job-log sink in `failure.ts` withholds // everything after the first masked value for that reason). It also // over-masks: a long absolute file path reads as a blob, and the word after a -// credential key is taken as its value. +// credential key is taken as its value. That limits how useful the job log is: +// long paths are over-masked, so the rest of the line is withheld (a CI +// runner's path to a compiled model loses its file name). /** An error as one bounded line, for the job log only. No reason, comment, * envelope or telemetry field carries its output: those hold a failure @@ -528,8 +530,9 @@ export function errorReason(err: unknown, max = 200): string { } /** True when the run itself broke: an engine call failed, a file's review - * threw or its content could not be read, or a model had no compiled head SQL - * (its engine and PII checks were skipped). Missing findings then mean "not + * threw or its content could not be read, the review's own code threw + * (`internalFailure`), or a model had no compiled head SQL (its engine and PII + * checks were skipped). Missing findings then mean "not * checked", so the run cannot APPROVE. A check that could not parse a model * (`abstained`) is not a broken run: SQL the engine does not support is * common, and blocking every such PR from approval would teach people to diff --git a/packages/opencode/test/altimate/review-ci-honesty.test.ts b/packages/opencode/test/altimate/review-ci-honesty.test.ts index a6dc641367..bca19e3ce5 100644 --- a/packages/opencode/test/altimate/review-ci-honesty.test.ts +++ b/packages/opencode/test/altimate/review-ci-honesty.test.ts @@ -218,7 +218,7 @@ describe("an AI-lane error reaches the comment as fixed text, its message only t const line = logged.find((l) => l.startsWith("altimate review: ai_error check=request:")) expect(line).toContain(marker) expect(line).not.toContain(pass) - expect(line).toContain("(rest withheld: the message holds a credential)") + expect(line).toContain("(rest withheld after a masked value)") expect(line).not.toContain("and more") }) }) diff --git a/packages/opencode/test/altimate/review-failures-gate.test.ts b/packages/opencode/test/altimate/review-failures-gate.test.ts index 34d927de84..85bd0cf766 100644 --- a/packages/opencode/test/altimate/review-failures-gate.test.ts +++ b/packages/opencode/test/altimate/review-failures-gate.test.ts @@ -17,13 +17,14 @@ import * as postModule from "../../src/altimate/review/post-github" import * as freeTierModule from "../../src/altimate/free/client" import * as consentModule from "../../src/altimate/free/consent" import { createDispatcherRunner } from "../../src/altimate/review/runner" -import { logDetail, reportFailure } from "../../src/altimate/review/failure" +import { hasInternalFailure, logDetail, reportFailure } from "../../src/altimate/review/failure" import { resolveHeadRef } from "../../src/altimate/review/git" import { emitReviewRun } from "../../src/altimate/review/telemetry" import { Dispatcher } from "../../src/altimate/native" import { Telemetry } from "../../src/altimate/telemetry" import { NO_DEFAULT_MODEL, runAiReview } from "../../src/altimate/review/ai-review" import { Provider } from "../../src/provider/provider" +import { Config } from "../../src/config/config" import { LLM } from "../../src/session/llm" /** @@ -267,7 +268,7 @@ describe("no error text reaches the comment, the envelope or telemetry; the job }) expect(log).not.toContain(tail) expect(log).not.toContain(first) - expect(log).toContain("(rest withheld: the message holds a credential)") + expect(log).toContain("(rest withheld after a masked value)") expect(logDetail(new Error(message))).not.toContain(tail) } // A message without a credential is logged whole. @@ -278,6 +279,16 @@ describe("no error text reaches the comment, the envelope or telemetry; the job expect(log).toBe(`altimate review: engine_error check=check: ${plain}\n`) }) + test("a long CI path that is over-masked gets the neutral suffix, not a claim of a credential", async () => { + const message = + "ENOENT: no such file or directory, open '/home/runner/work/analytics/analytics/target/compiled/proj/models/staging/stg_orders.sql'" + const { log } = await captured(async () => { + reportFailure("file_unreadable", { path: "models/staging/stg_orders.sql" }, new Error(message)) + }) + expect(log).toContain("ENOENT: no such file or directory, open '/[REDACTED] (rest withheld after a masked value)") + expect(log).not.toContain("credential") + }) + // The production AI lane, with the provider and model stubbed to fail at each stage. describe("the real AI lane", () => { const files = [{ path: "models/a.sql", model: "a", status: "modified" as const, diff: "+select 2 as id", sql: "select 2 as id" }] @@ -343,6 +354,25 @@ describe("no error text reaches the comment, the envelope or telemetry; the job } }) + test("a config that cannot be read is an AI error with fixed text, through the whole review", async () => { + const m = marker() + const spies = [ + spyOn(Config, "get").mockImplementation((async () => { + throw new Error(`config said ${m}`) + }) as any), + spyOn(Dispatcher, "call").mockImplementation((async () => ({ success: true, data: { prompt: "p" } })) as any), + ] + try { + const { env, log, events } = await captured(() => review({}, { aiReview: runAiReview })) + expect(env.ai).toMatchObject({ state: "error", reason: "no usable model. See the job log for details." }) + expect(JSON.stringify(env) + renderSummary(env) + events).not.toContain(m) + expect(log).toContain("altimate review: ai_error check=model:") + expect(log).toContain(m) + } finally { + for (const spy of spies) spy.mockRestore() + } + }) + test("no configured model is a skip with fixed advice, not a logged error", async () => { const getModel = spyOn(Provider, "defaultModel").mockImplementation((async () => { throw new Error("no providers found") @@ -448,18 +478,30 @@ describe("an internal exception fails the job in every mode", () => { }) as any), spyOn(process.stdout, "write").mockImplementation((() => true) as any), ] + // Bun does not clear an exit code assigned `undefined`: reset to 0, and + // restore with `?? 0`, so this test cannot change the run's own exit code. const saved = process.exitCode - process.exitCode = undefined + process.exitCode = 0 try { await (ReviewCommand.handler as any)({ post: true, json: true, cwd: process.cwd() }) - expect(exitCodeWhenPosting).toBeUndefined() + expect(exitCodeWhenPosting).toBe(0) expect(process.exitCode as number | undefined).toBe(EXIT_INTERNAL_FAILURE) } finally { - process.exitCode = saved + process.exitCode = saved ?? 0 for (const spy of spies) spy.mockRestore() } }) + test("an internal failure is decided by category, whatever list holds the entry", () => { + const lane = (category: "engine_error" | "file_unreadable" | "internal_error") => ({ method: "lane", reason: "r", count: 1, category }) + expect(hasInternalFailure([lane("engine_error")])).toBe(false) + expect(hasInternalFailure([lane("file_unreadable")])).toBe(false) + expect(hasInternalFailure([{ category: undefined }])).toBe(false) + expect(hasInternalFailure([lane("engine_error"), lane("internal_error")])).toBe(true) + const failedFile = { path: "models/a.sql", kind: "failed", category: "internal_error" as const } + expect(hasInternalFailure([failedFile])).toBe(true) + }) + test("a side that could not be read keeps the run from approving but exits 0, as before", async () => { for (const mode of ["gate", "comment"] as const) for (const side of ["old", "new"] as const) { @@ -731,7 +773,7 @@ describe("a model the manifest marks disabled", () => { expect(env.findings).toEqual([]) expect(env.verdict).toBe("APPROVE") expect(renderSummary(env)).toContain( - "1 model(s) disabled in this manifest: dbt does not build them, so no compiled SQL is expected; the checks that read the model's own SQL still ran: `models/marts/fct_customers.sql`.", + "1 model(s) disabled in this manifest: dbt does not build them, so no compiled SQL is expected; the catalog and dbt-pattern checks still ran; the PII and engine checks need compiled SQL: `models/marts/fct_customers.sql`.", ) }, 30000) }) @@ -769,6 +811,39 @@ describe("PII abstention", () => { }) }) + test("an unparseable base keeps the precise classifier's PII finding undecided, never critical", async () => { + // The base uses syntax the engine cannot parse, so its lineage resolves no + // column and its PII check abstains; `ssn` already existed in it. + const base = "select ssn from t |> select ssn" + const head = "select ssn from t" + const env = await runReview({ + changedFiles: [{ path: "models/marts/a.sql", status: "modified" as const, diff: `-${base}\n+${head}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["pii_exposure"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: runner({ + async detectPii(sql: string) { + return sql === base ? { columns: [], abstained: true } : { columns: ["ssn"] } + }, + async columnLineage(sql: string) { + return sql === base ? [] : [{ source: "t.ssn", target: "ssn" }] + }, + async classifyPii(columns: string[]) { + return columns.map((column) => ({ column, classification: "SSN", confidence: 0.99 })) + }, + }), + getContent: async (_f, side) => (side === "new" ? head : base), + }) + const pii = env.findings.filter((f) => f.category === "pii_exposure") + const precise = pii.find((f) => f.evidence?.tool === "altimate_core.classify_pii") + expect(precise).toMatchObject({ severity: "warning", confidence: "unknown" }) + expect(precise?.body).toContain( + "The base model could not be analysed, so whether this column is new could not be decided.", + ) + expect(pii.filter((f) => f.severity === "critical")).toEqual([]) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + }) + test("a PII check that could not analyse the model is reported, not treated as clean", async () => { const env = await runReview({ changedFiles: [two[0]], diff --git a/packages/opencode/test/altimate/review-incomplete-run.test.ts b/packages/opencode/test/altimate/review-incomplete-run.test.ts index a62d7a1bfa..3c6f797d76 100644 --- a/packages/opencode/test/altimate/review-incomplete-run.test.ts +++ b/packages/opencode/test/altimate/review-incomplete-run.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, spyOn, test } from "bun:test" -import { chmodSync, writeFileSync } from "node:fs" +import { chmodSync, readFileSync, writeFileSync } from "node:fs" import { execFileSync } from "node:child_process" import path from "node:path" import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" @@ -9,7 +9,7 @@ import { createDispatcherRunner, isParseFailure } from "../../src/altimate/revie import { Dispatcher } from "../../src/altimate/native" import { buildEnvelope, computeIdealVerdict, errorReason, type VerdictEnvelope } from "../../src/altimate/review/verdict" import { coverageNotes, renderSummary, verdictHeadline } from "../../src/altimate/review/format" -import { resolveHeadRef, resolveReviewBase } from "../../src/altimate/review/git" +import { FetchInterrupted, resolveHeadRef, resolveReviewBase } from "../../src/altimate/review/git" import { knownReviewers, TIER_LANES } from "../../src/altimate/review/risk-tier" import { tmpdir } from "../fixture/fixture" @@ -1381,8 +1381,9 @@ describe.skipIf(process.platform === "win32")("network fetches of the target bra process.on("SIGINT", host) const savedPath = process.env.PATH process.env.PATH = `${bin.path}${path.delimiter}${savedPath}` + let pending: Promise<{ result: unknown; log: string }> | undefined try { - const pending = captureLog(() => resolveHeadRef("origin/feature", tmp.path, 60000).catch((e: Error) => e)) + pending = captureLog(() => resolveHeadRef("origin/feature", tmp.path, 60000).catch((e: Error) => e)) for (let i = 0; i < 100 && running() === 0; i++) await new Promise((resolve) => setTimeout(resolve, 50)) expect(running()).toBe(1) process.emit("SIGINT", "SIGINT") @@ -1393,6 +1394,15 @@ describe.skipIf(process.platform === "win32")("network fetches of the target bra expect(running()).toBe(0) expect(process.listenerCount("SIGINT")).toBe(1) } finally { + // A failed assertion must not leave the fetch pending or its sleep running: + // interrupt it (a no-op once it settled), wait for it, then kill leftovers. + process.emit("SIGINT", "SIGINT") + await pending?.catch(() => undefined) + try { + execFileSync("pkill", ["-f", `sleep ${marker}`]) + } catch { + // Nothing left to kill. + } process.env.PATH = savedPath process.removeListener("SIGINT", host) } @@ -1430,6 +1440,64 @@ describe.skipIf(process.platform === "win32")("network fetches of the target bra } }, 20000) + test("SIGINT while deepening the head stops the deepen loop", async () => { + await using origin = await tmpdir({ git: true }) + await using clone = await tmpdir() + await using bin = await tmpdir() + const g = (cwd: string, ...a: string[]) => execFileSync("git", a, { cwd }).toString().trim() + const main = g(origin.path, "rev-parse", "--abbrev-ref", "HEAD") + g(origin.path, "checkout", "-q", "-b", "pr") + for (const n of [1, 2]) { + writeFileSync(path.join(origin.path, `f${n}.sql`), `select ${n}\n`) + g(origin.path, "add", "-A") + g(origin.path, "commit", "-qm", `pr ${n}`) + } + execFileSync("git", ["clone", "-q", "--depth", "1", "--branch", "pr", `file://${origin.path}`, clone.path]) + const realGit = execFileSync("which", ["git"]).toString().trim() + const calls = path.join(bin.path, "fetches.log") + const marker = `26.${process.pid % 1000}${Math.floor(Math.random() * 1000)}` + // Every fetch is logged; the head deepen (last argument: the head's SHA) stalls. + writeFileSync( + path.join(bin.path, "git"), + `#!/bin/sh\nif [ "$1" = fetch ]; then eval last=\\\${$#}; echo "$last" >> "${calls}"; if [ \${#last} -eq 40 ]; then sleep ${marker} & wait; exit 1; fi; fi\nexec "${realGit}" "$@"\n`, + ) + chmodSync(path.join(bin.path, "git"), 0o755) + const running = () => + execFileSync("ps", ["-axo", "command"]).toString().split("\n").filter((l) => l.trim() === `sleep ${marker}`).length + // The host's own handler keeps the process alive, so only the rejection can stop the loop. + const host = () => {} + process.on("SIGINT", host) + const savedPath = process.env.PATH + process.env.PATH = `${bin.path}${path.delimiter}${savedPath}` + let pending: Promise | undefined + try { + pending = resolveReviewBase({ cwd: clone.path, env: { GITHUB_BASE_REF: main }, fetchTimeoutMs: 15000 }).catch( + (e: Error) => e, + ) + for (let i = 0; i < 100 && running() === 0; i++) await new Promise((resolve) => setTimeout(resolve, 50)) + expect(running()).toBe(1) + process.emit("SIGINT", "SIGINT") + const err = await pending + expect(err).toBeInstanceOf(FetchInterrupted) + expect((err as Error).message).toBe("git fetch interrupted by SIGINT") + await new Promise((resolve) => setTimeout(resolve, 300)) + // The interrupted head deepen was the last fetch: no further depth was tried. + const lines = readFileSync(calls, "utf8").trim().split("\n") + expect(lines.at(-1)).toHaveLength(40) + expect(lines.filter((l) => l.length === 40)).toHaveLength(1) + } finally { + process.emit("SIGINT", "SIGINT") + await pending + try { + execFileSync("pkill", ["-f", `sleep ${marker}`]) + } catch { + // Nothing left to kill. + } + process.env.PATH = savedPath + process.removeListener("SIGINT", host) + } + }, 20000) + test("a long fetch error is logged by its fatal line, else its last complete line", async () => { await using tmp = await tmpdir({ git: true }) await using bin = await tmpdir() From a552e53b984fdecb7c5be60c04a79c5c2216f694 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 3 Dec 2026 21:04:01 +0530 Subject: [PATCH 02/39] feat(review): consumers outside dbt, contract vs `SELECT`, engine-aware integer division, empty unit-test fixtures Consumer column lists outside dbt (opt-in): decided by exact identifier or own-line mention, else undecided. Contract column check (opt-in, non-blocking). Output columns only from SQL shapes the parser follows; otherwise the check abstains. Engine-aware integer division and unit-test fixture checks. Co-Authored-By: Claude Fable 5.2 --- docs/docs/usage/dbt-pr-review.md | 63 +- .../altimate/review/adapter-capabilities.ts | 79 ++ .../opencode/src/altimate/review/config.ts | 15 + .../src/altimate/review/consumer-lists.ts | 280 +++++ .../src/altimate/review/dbt-patterns.ts | 11 +- .../opencode/src/altimate/review/format.ts | 2 +- .../src/altimate/review/orchestrate.ts | 283 ++++- .../src/altimate/review/rule-catalog.ts | 304 +++++- packages/opencode/src/altimate/review/run.ts | 33 +- .../opencode/src/altimate/review/runner.ts | 57 +- .../src/altimate/review/unit-tests.ts | 82 ++ .../altimate/review-contracts-dialect.test.ts | 999 ++++++++++++++++++ .../test/altimate/review-runner.test.ts | 84 ++ 13 files changed, 2251 insertions(+), 41 deletions(-) create mode 100644 packages/opencode/src/altimate/review/adapter-capabilities.ts create mode 100644 packages/opencode/src/altimate/review/consumer-lists.ts create mode 100644 packages/opencode/src/altimate/review/unit-tests.ts create mode 100644 packages/opencode/test/altimate/review-contracts-dialect.test.ts diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 8af13f3233..91071cbc63 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -302,6 +302,8 @@ riskTierPathTokens: # OFF by default — see "Risk-tier path tokens" b finops: [preset:finops] # promote any FinOps-named path to `full` tier pii: [ssn, email, phone] # or supply your own case-insensitive tokens allowForceTier: true # set false in gate CI: --force-tier is then rejected +checkContractColumns: false # opt-in: new columns missing from an enforced contract (CI that doesn't run `dbt build`) +consumerColumnLists: [] # OFF by default — see "Consumers outside dbt" below rubric: blockOn: [lineage_breakage, contract_violation, pii_exposure, semantic_change] warningPatternThreshold: 3 @@ -341,6 +343,55 @@ rubric: push and posts its own verdict; an earlier blocking review is not dismissed automatically. +### Consumers outside dbt + +A column removed or renamed can break readers the dbt DAG doesn't show. With a +manifest, the review reports: + +- **Exposures and contracts.** Removing a column from a model that has + `exposures` (dashboards, apps, ML) or an enforced contract names those + consumers and suggests a deprecation period or a new model version. + Downstream dbt models that select the column are reported separately, with + the models named. +- **Contract vs `SELECT` (opt-in).** A new column missing from an enforced + contract fails `dbt build`, so this is off by default. Turn it on with + `checkContractColumns: true` when CI runs only `dbt parse` or `dbt compile`. + A column the PR declares in a changed yml counts as declared even when the + manifest predates the PR. It comments; it never blocks. +- **Explicit column lists (opt-in).** Some projects copy a model's columns + into code outside dbt: an export or reverse-ETL script, a feature list, an + API schema. Name those files and the list's pattern, and when a PR adds or + removes a model's columns, each matching list must follow. + +```yaml +consumerColumnLists: + - files: "exports/**/*.py" # repo-relative glob + pattern: "COLUMNS\\s*=\\s*\\[([^\\]]*)\\]" # first capture group = the list + model: fct_orders # omit: the list's own line must name the model +``` + +Without `model`, a list mirrors the model its own lines name: a dict key or +call argument on the line the list opens on (`"fct_orders": [`, +`load("fct_orders", [...])`), or its identifier when that is exactly the +model's name, optionally with one suffix such as `_COLUMNS` or `_FIELDS` +(`FCT_ORDERS_COLUMNS = [...]`, not `STG_FCT_ORDERS_COLUMNS`). +A model named only on a neighbouring line or elsewhere in the file leaves the +list not fully verified (set `model` to decide it). A list is checked only +when both versions of the model have a complete select list: a `*` over CTEs +whose columns are known (`select * from final`, also with `exclude` / +`replace` / `rename`, plain joins, `where`, `group by`, `qualify`, +`order by`, `limit` and `union [all]`) counts; a `*` over a table or `ref()`, +an unnamed expression, or any other syntax on the way (`pivot`, `unpivot`, +`lateral`, table functions, `(values …)`, other set operators) does not. If the files cannot be listed or a list file cannot be +read, the comment names the lookup (`consumerColumnLists.listFiles` or +`consumerColumnLists.read`) and the run cannot approve; the envelope's +`engineErrors` entry has `category: file_unreadable`, and the git or file +system message is only in the job log. A pattern that is not a valid regex, or +has no capture group, is listed by its entry number (`entry 2: the pattern is +not a valid regular expression`), never quoted; it and a list the base branch +had that the PR's head no longer yields are listed without holding back +approval. + ### What the PR comment shows - **One summary comment**, updated in place on every push, capped at about @@ -477,7 +528,8 @@ rubric: printed, and the line ends "(rest withheld after a masked value)"), on a line that starts with `altimate review:`, the kind, and the check or file (for example `altimate review: engine_error check=columnLineage: …`). The envelope records the kind as `category` on - `engineErrors` entries (`engine_error`, `internal_error`) and on failed files + `engineErrors` entries (`engine_error`, `internal_error`, and + `file_unreadable` for a consumer column list lookup) and on failed files in `scope.unverified` (`internal_error`, `file_unreadable`); a failed AI lane sets `ai.state` to `error` with a fixed reason and logs `ai_error`. A failed `git fetch` stops the review with a fixed message, and its log line carries @@ -651,6 +703,15 @@ The deterministic rules group into four families: cartesian (`JOIN` without a condition), `NOT IN (… NULL)`, sum-of-a-ratio, non-portable dialect functions, integer-multiplication overflow, PK-aware join fan-out, timezone-in-hash-key. +- **Engine-dependent rules read an adapter table.** Where behavior differs by + engine, a rule checks the project's adapter (from the manifest or `dialect`) + instead of assuming one. Example: `int / int` (and `count(…) / count(…)`) + truncates on Postgres, Redshift, Trino/Athena and SQL Server, so it is a + correctness finding there. On Snowflake, BigQuery, Databricks and DuckDB it is + only portability advice, shown for packages (`portability: true`). +- **dbt unit tests.** A unit test whose `given` inputs are all `rows: []` is + reported: it either never tests the model's logic, or expects rows the model has nothing to + build from. - **dbt config / Jinja (`DBT0xx`).** A core **minijinja** parser reads `{{ config(...) }}` and the model body: incremental model without an `is_incremental()` guard, `merge`/`delete+insert` without a `unique_key`, diff --git a/packages/opencode/src/altimate/review/adapter-capabilities.ts b/packages/opencode/src/altimate/review/adapter-capabilities.ts new file mode 100644 index 0000000000..cb75636dea --- /dev/null +++ b/packages/opencode/src/altimate/review/adapter-capabilities.ts @@ -0,0 +1,79 @@ +/** + * Per-adapter behavior that review rules depend on. A rule whose correctness + * differs by engine reads this table instead of hard-coding one engine, so it + * fires where the behavior is real and stays silent elsewhere. Every entry + * cites the engine's documentation. An adapter missing from the table gets the + * generic (engine-agnostic) form of each rule only. + * + * Keys are the review's dialect names (see run.ts `ADAPTER_DIALECT`). + */ + +export interface AdapterCapability { + /** `int / int` returns an integer, dropping the fraction (7 / 2 = 3). */ + integerDivisionTruncates: boolean + /** Documentation backing the entries above. */ + sources: string[] +} + +export const ADAPTER_CAPABILITIES: Record = { + postgres: { + integerDivisionTruncates: true, + sources: ["https://www.postgresql.org/docs/current/functions-math.html"], + }, + redshift: { + integerDivisionTruncates: true, + sources: ["https://docs.aws.amazon.com/redshift/latest/dg/r_numeric_computations201.html"], + }, + trino: { + integerDivisionTruncates: true, + sources: ["https://trino.io/docs/current/functions/math.html"], + }, + athena: { + // Athena SQL runs on Trino. + integerDivisionTruncates: true, + sources: ["https://trino.io/docs/current/functions/math.html"], + }, + tsql: { + integerDivisionTruncates: true, + sources: ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/divide-transact-sql"], + }, + fabric: { + integerDivisionTruncates: true, + sources: ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/divide-transact-sql"], + }, + snowflake: { + integerDivisionTruncates: false, + sources: ["https://docs.snowflake.com/en/sql-reference/operators-arithmetic"], + }, + bigquery: { + integerDivisionTruncates: false, + sources: ["https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#arithmetic_operators"], + }, + databricks: { + integerDivisionTruncates: false, + sources: ["https://docs.databricks.com/en/sql/language-manual/functions/slashsign.html"], + }, + duckdb: { + integerDivisionTruncates: false, + sources: ["https://duckdb.org/docs/sql/functions/numeric"], + }, + mysql: { + integerDivisionTruncates: false, + sources: ["https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html"], + }, + oracle: { + integerDivisionTruncates: false, + sources: ["https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Arithmetic-Operators.html"], + }, + clickhouse: { + integerDivisionTruncates: false, + sources: ["https://clickhouse.com/docs/en/sql-reference/functions/arithmetic-functions"], + }, +} + +export function capabilityFor(dialect: string | undefined): AdapterCapability | undefined { + return dialect ? ADAPTER_CAPABILITIES[dialect.toLowerCase()] : undefined +} + +/** Display names of the engines where `int / int` truncates. */ +export const TRUNCATING_DIVISION_ENGINES = "Postgres, Redshift, Trino/Athena and SQL Server" diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 55c5cd7c4d..2dc04c152f 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -35,6 +35,21 @@ export const ReviewConfig = z.object({ * Functions missing on the project's own engine are always reported. */ portability: z.boolean().optional(), + /** + * Opt-in: report a new column missing from an enforced contract. `dbt build` + * already fails on it, so this only helps CI that runs `dbt parse`/`compile` + * without building. + */ + checkContractColumns: z.boolean().default(false), + /** + * Opt-in: explicit column lists outside dbt (loaders, exports) that must + * track a model's columns. `files` is a repo-relative glob, `pattern` a regex + * whose first capture group is the list, `model` the model it mirrors + * (omitted = files that mention the model by name). + */ + consumerColumnLists: z + .array(z.object({ files: z.string(), pattern: z.string(), model: z.string().optional() })) + .default([]), /** Allow `--force-tier` (a debug bypass of the risk classifier). Set false * in gate CI so a run cannot skip checks by forcing a lower tier. */ allowForceTier: z.boolean().default(true), diff --git a/packages/opencode/src/altimate/review/consumer-lists.ts b/packages/opencode/src/altimate/review/consumer-lists.ts new file mode 100644 index 0000000000..e0dd8569a7 --- /dev/null +++ b/packages/opencode/src/altimate/review/consumer-lists.ts @@ -0,0 +1,280 @@ +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { reportFailure } from "./failure" +import type { FailureCategory } from "./verdict" + +/** + * Opt-in: explicit column lists outside dbt (loaders, exports, reverse-ETL + * configs) that must stay in step with a model's columns. A project names the + * files and a regex whose first capture group holds the list in + * `.altimate/review.yml`; the review then reports model columns a list is + * missing, and list entries the model no longer selects. Off unless configured, + * since no such convention is universal. + */ + +export interface ConsumerColumnListConfig { + /** Repository-relative glob of the files holding the lists. */ + files: string + /** Regex whose first capture group is the column list. */ + pattern: string + /** The model the lists mirror; omitted = files that mention the model by name. */ + model?: string +} + +export interface ConsumerColumnList { + path: string + model?: string + columns: string[] + /** File text: a model it names away from the match leaves the list undecided. */ + content: string + /** The match's own lines and one line either side. A model named only + * here, not on the match's own lines, leaves the list undecided. */ + context?: string + /** The match's own lines (whole lines, so a dict key or call before it + * counts) without the captured list: a model named here owns the list. */ + own?: string + /** 1-based line the match starts on. */ + line?: number + /** The identifier the list is assigned to (`ORDERS_COLUMNS = [...]`), when one precedes it. */ + name?: string +} + +const exec = promisify(execFile) +const IDENT = /^[A-Za-z_][A-Za-z0-9_$]*$/ +/** The identifier a match is assigned to: the last `name =` / `name:` before it on its line. */ +const ASSIGNED = /([A-Za-z_][A-Za-z0-9_.$-]*)["']?\s*(?::=|=|:)\s*$/ + +/** One column list per match of `pattern` in `content` (each lowercased and + * de-duplicated, with where it is), so two lists in one file are checked separately. */ +export function findColumnLists( + content: string, + pattern: RegExp, +): Array<{ columns: string[]; line: number; name?: string; context: string; own: string }> { + const flags = pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g" + const re = new RegExp(pattern.source, flags) + const lines = content.split("\n") + const out: Array<{ columns: string[]; line: number; name?: string; context: string; own: string }> = [] + for (const m of content.matchAll(re)) { + const cols = new Set() + for (const token of (m[1] ?? "").split(/[,\s]+/)) { + const name = token.replace(/^["'`]+|["'`]+$/g, "") + if (IDENT.test(name)) cols.add(name.toLowerCase()) + } + if (!cols.size) continue + const start = m.index ?? 0 + const first = content.slice(0, start).split("\n").length + const last = first + m[0].split("\n").length - 1 + // The text before the capture group: `NAME = [` (the pattern's own prefix, or the line's). + const lead = content.slice(content.lastIndexOf("\n", start - 1) + 1, start) + m[0].slice(0, m[0].indexOf(m[1] ?? "")) + const name = ASSIGNED.exec(lead.replace(/[\s\[({]+$/, ""))?.[1] + const context = lines.slice(Math.max(0, first - 2), last + 1).join("\n") + const group = start + m[0].indexOf(m[1] ?? "") + const lineStart = content.lastIndexOf("\n", start - 1) + 1 + const lineEndAt = content.indexOf("\n", start + m[0].length) + const lineEnd = lineEndAt < 0 ? content.length : lineEndAt + const own = content.slice(lineStart, group) + content.slice(group + (m[1] ?? "").length, lineEnd) + out.push({ columns: [...cols], line: first, name, context, own }) + } + return out +} + +/** The column lists `pattern` matches in `content`. */ +export function extractColumnLists(content: string, pattern: RegExp): string[][] { + return findColumnLists(content, pattern).map((l) => l.columns) +} + +/** Column names from every match of `pattern` in `content` (lowercased, de-duplicated). */ +export function extractColumnList(content: string, pattern: RegExp): string[] { + return [...new Set(extractColumnLists(content, pattern).flat())] +} + +/** Lowercased words of an identifier, split at `_` and at case changes + * (`FctOrdersCols` → fct, orders, cols). */ +const words = (text: string) => + text + .replace(/([a-z0-9])([A-Z])/g, "$1_$2") + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter(Boolean) + +/** The one word an identifier may add after a model's name and still name it. */ +const LIST_SUFFIXES = new Set(["columns", "cols", "column", "fields", "field", "names", "list", "keys", "schema", "select"]) + +/** Whether identifier `name` names `model`: exactly the model's words, plus at + * most one suffix from a closed set (`ORDERS_COLUMNS`, `fctOrdersCols`, + * `FCT_ORDERS`; not `STG_ORDERS_COLUMNS` or `FCT_ORDERS_DAILY_COLUMNS`). */ +export function identifierNamesModel(name: string | undefined, model: string): boolean { + if (!name) return false + const want = words(model) + const have = words(name) + if (!want.length || have.length < want.length || have.length > want.length + 1) return false + if (!want.every((w, j) => have[j] === w)) return false + return have.length === want.length || LIST_SUFFIXES.has(have[want.length]) +} + +/** Whether `text` holds `model` as a whole identifier (`_`, letters and digits + * are word characters, so `stg_orders` does not name `orders`). */ +export function mentionsModel(text: string | undefined, model: string): boolean { + if (!text) return false + return new RegExp(`(? !l.model && (identifierNamesModel(l.name, model) || mentionsModel(l.own, model)) + if (owns(list)) return true + if (sameFile.some((l) => l !== list && l.path === list.path && owns(l))) return false + return mentionsModel(list.context, model) || mentionsModel(list.content, model) ? undefined : false +} + +/** How a list is named in a comment: its identifier, else its line; with the + * line too when another list in `sameFile` has the same identifier. */ +export function listLabel(list: ConsumerColumnList, sameFile: ConsumerColumnList[] = []): string | undefined { + if (!list.name) return list.line ? `line ${list.line}` : undefined + const repeated = sameFile.some((l) => l !== list && l.path === list.path && l.name === list.name) + return repeated && list.line ? `${list.name} (line ${list.line})` : list.name +} + +/** + * Lists the base had that the head no longer yields (the file removed, or + * edited so the pattern stops matching): a PR could otherwise switch a list + * off unnoticed. A base list is kept by, in this order: a list in the same + * file under the same identifier (the same columns first; an edited one is + * checked by the lanes), then a list in the same file with the same columns + * (`load([...])` rewritten as `COLS = [...]`), then one in another file with + * the same columns (a moved file). Each head list is used once. + */ +export function droppedLists(base: ConsumerColumnList[], head: ConsumerColumnList[]): Array<{ path: string; reason: string }> { + const left = [...head] + const key = (l: ConsumerColumnList) => [...l.columns].sort().join(",") + const take = (match: (h: ConsumerColumnList) => boolean) => { + const i = left.findIndex(match) + if (i < 0) return false + left.splice(i, 1) + return true + } + const passes: Array<(l: ConsumerColumnList) => (h: ConsumerColumnList) => boolean> = [ + (l) => (h) => h.path === l.path && h.name === l.name && key(h) === key(l), + (l) => (h) => h.path === l.path && h.name === l.name, + (l) => (h) => h.path === l.path && key(h) === key(l), + (l) => (h) => key(h) === key(l), + ] + let remaining = base + for (const pass of passes) remaining = remaining.filter((l) => !take(pass(l))) + return remaining.map((l) => ({ + path: l.path, + reason: `consumerColumnLists: column list ${listLabel(l, base) ?? "in this file"} is no longer found at the head, so it is not checked`, + })) +} + +/** The configured lists, and what kept some of them from being checked. */ +export interface ConsumerListLoad { + lists: ConsumerColumnList[] + /** Lookups that failed (listing files, reading a list file), one per kind + * with the first reason: the lists they would have found were not checked. + * The reason is a fixed sentence; the error itself is in the job log. */ + errors: Array<{ method: string; reason: string; count: number; category: FailureCategory }> + /** Configured entries whose pattern selects no list (invalid regex, or no + * capture group): a policy mistake to report, never a failed run. The policy + * comes from the base branch, so a failed run could not approve the PR that + * fixes the pattern. */ + invalid: string[] + /** Lists the base had that the head no longer yields, or why that could not + * be checked: listed, never blocking. */ + dropped?: Array<{ path: string; reason: string }> +} + +/** Regular files at `head` (or in the index): a submodule (gitlink, mode + * 160000) is not a file of this repository and cannot be read as one. */ +async function listBlobs(gitRoot: string, head?: string): Promise { + const args = head ? ["ls-tree", "-r", "-z", head] : ["ls-files", "-z", "-s"] + const { stdout } = await exec("git", args, { cwd: gitRoot, maxBuffer: 64 * 1024 * 1024 }) + const out: string[] = [] + for (const entry of stdout.split("\0")) { + const tab = entry.indexOf("\t") + if (tab < 0) continue + // ls-tree: ` \t`; ls-files -s: ` \t`. + const mode = entry.slice(0, entry.indexOf(" ")) + if (mode !== "160000") out.push(entry.slice(tab + 1)) + } + return out +} + +/** + * Read the configured lists at the head (`head` ref, or the working tree). + * Nothing is skipped silently: a failed lookup is returned in `errors`, an + * unusable pattern in `invalid`. Reasons are fixed sentences: a git or file + * system error goes to the job log through `reportFailure`, never into them. + */ +export async function loadConsumerLists(opts: { + configs: ConsumerColumnListConfig[] + gitRoot: string + head?: string + read: (repoRelPath: string) => Promise + /** Which side of the PR is read, for the job log. */ + side?: "head" | "base" +}): Promise { + const lists: ConsumerColumnList[] = [] + const invalid: string[] = [] + const side = opts.side ?? "head" + const failures = new Map() + /** Log the error with its facts; keep a fixed reason (the first per method). */ + const fail = (method: string, reason: string, err: unknown, path?: string) => { + reportFailure("file_unreadable", { check: method, side, ...(path ? { path } : {}) }, err) + const prev = failures.get(method) + failures.set(method, { reason: prev?.reason ?? reason, count: (prev?.count ?? 0) + 1 }) + } + // Every entry lists the same files: run git once. `git ls-tree` rejects + // `:(glob)` pathspec magic, so the glob is matched here, the same way for the + // head ref and the working tree. + let listed: Promise | undefined + const listFiles = () => (listed ??= listBlobs(opts.gitRoot, opts.head)) + // Entries are named by position: a pattern or glob is not quoted in public output. + for (const [i, cfg] of opts.configs.entries()) { + const entry = `entry ${i + 1}` + let re: RegExp + try { + re = new RegExp(cfg.pattern, "g") + } catch { + invalid.push(`${entry}: the pattern is not a valid regular expression`) + continue + } + if (!/\((?!\?)/.test(cfg.pattern.replace(/\\./g, ""))) { + invalid.push(`${entry}: the pattern has no capture group, so it selects no list`) + continue + } + const glob = new Bun.Glob(cfg.files) + let files: string[] + try { + files = (await listFiles()).filter((f) => glob.match(f)) + } catch (e) { + fail("consumerColumnLists.listFiles", "the repository's files could not be listed, so no list was checked; see the job log", e) + continue + } + for (const file of files) { + let content: string | undefined + let readError: unknown + try { + content = await opts.read(file) + } catch (e) { + readError = e + } + if (content === undefined) { + fail("consumerColumnLists.read", `could not read ${file}`, readError, file) + continue + } + for (const l of findColumnLists(content, re)) lists.push({ path: file, model: cfg.model, content, ...l }) + } + } + const errors = [...failures].map(([method, f]) => ({ method, ...f, category: "file_unreadable" as const })) + return { lists, errors, invalid } +} diff --git a/packages/opencode/src/altimate/review/dbt-patterns.ts b/packages/opencode/src/altimate/review/dbt-patterns.ts index 82ffe4ddc7..74ad9146ab 100644 --- a/packages/opencode/src/altimate/review/dbt-patterns.ts +++ b/packages/opencode/src/altimate/review/dbt-patterns.ts @@ -4,7 +4,7 @@ import { Log } from "@/altimate/util/log" import { type Finding, type Severity, type ReviewCategory, makeFinding } from "./finding" import { type ChangedFile, fileKind } from "./diff-filter" import { type Rubric, clampSeverity, exclusionReason } from "./rubric" -import { evaluateCatalog, selectItemColumns, stripLiterals } from "./rule-catalog" +import { evaluateCatalog, selectItemColumns, stripLiterals, type CatalogContext } from "./rule-catalog" /** Local copy to avoid a cycle with orchestrate.ts. */ function modelNameFromPath(p: string): string { @@ -759,7 +759,12 @@ const MODEL_DETECTORS: Detector[] = [ ] /** Run the dbt anti-pattern detectors over a changed MODEL file. */ -export function detectModelPatterns(file: ChangedFile, newSql: string | undefined, rubric: Rubric): Finding[] { +export function detectModelPatterns( + file: ChangedFile, + newSql: string | undefined, + rubric: Rubric, + catalogCtx?: CatalogContext, +): Finding[] { const kind = fileKind(file) if (!isModelSql(kind) || file.status === "deleted" || !newSql) return [] const { added, removed } = splitDiff(file.diff) @@ -778,7 +783,7 @@ export function detectModelPatterns(file: ChangedFile, newSql: string | undefine out.push({ ...f, severity: clampSeverity(f.category, f.severity, f.confidence) }) } // Declarative rule catalog (data-driven checks) complements the programmatic detectors. - out.push(...evaluateCatalog(file, newSql, added, removed, rubric)) + out.push(...evaluateCatalog(file, newSql, added, removed, rubric, catalogCtx)) return out.filter((f) => !exclusionReason(f, rubric)) } diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 81e594a3f9..1929eb891f 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -249,7 +249,7 @@ const BULLET_NAMES_MAX = 200 * than any backtick run inside `text`, so a path like `packages/…/foo`bar`.sql` * cannot terminate the span; a leading or trailing backtick * is padded with a space so it isn't glued to the fence. */ -function codeSpan(raw: string): string { +export function codeSpan(raw: string): string { // A code span cannot hold a blank line: one would end the paragraph and let // the rest of a path render as markdown. const text = raw.replace(/\r\n?|\n/g, " ") diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 3396b408ed..4d9e1ef5e1 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1,4 +1,5 @@ import path from "node:path" +import YAML from "yaml" import { type Finding, type ReviewCategory, @@ -47,8 +48,14 @@ import { selectItems, selectSources, } from "./rule-catalog" +import { listLabel, listMirrorsModel, type ConsumerColumnList, type ConsumerListLoad } from "./consumer-lists" +import { detectUnitTestFixtures } from "./unit-tests" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult } from "./ai-review" import { hasInternalFailure, reportFailure } from "./failure" +import { codeSpan } from "./format" + +/** Where an unusable `consumerColumnLists` entry is reported. */ +const REVIEW_POLICY_PATH = ".altimate/review.yml" /** * The deterministic review recipe. @@ -169,6 +176,18 @@ export interface ReviewRunner { lexicalScan?(addedLines: string[]): Promise> /** Direct downstream models (name + file path) of a model, from the manifest DAG. */ downstreamModels?(model: 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[] } | undefined + > /** 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. */ @@ -254,6 +273,11 @@ export interface OrchestrateInput { scope?: Omit /** Drop the regex catalog's cross-engine portability findings (single known engine). */ suppressPortability?: boolean + /** 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"] } @@ -650,6 +674,213 @@ async function columnBreakageLane( ] } +/** A query's output columns from column lineage (lowercased); empty when unknown or `*`. */ +/** + * 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. */ +function columnDelta(ctx: ModelContext): { added: string[]; removed: string[]; unknown: boolean } { + const none = { added: [], removed: [], unknown: false } + const unknown = { added: [], removed: [], unknown: true } + const { file, engineNewSql, engineOldSql } = ctx + if (!engineNewSql || file.status === "deleted") return none + const current = outputColumns(engineNewSql) + if (!current) return unknown + if (!hasOldSide(file)) return { added: [...current], removed: [], unknown: false } + if (!engineOldSql) return unknown + const before = outputColumns(engineOldSql) + if (!before) return unknown + return { + added: [...current].filter((c) => !before.has(c)), + removed: [...before].filter((c) => !current.has(c)), + unknown: 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(", ") + +/** 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): 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 : [] + if (name === target) { + names(m.columns) + for (const v of versions) names(v?.columns) + continue + } + const v = versions.find((v) => `${name}_v${String(v?.v ?? "").toLowerCase()}` === target) + if (v) { + names(m.columns) + 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 || (!consumers.exposures.length && !consumers.contractEnforced)) return [] + const { added, removed, unknown } = columnDelta(ctx) + if (unknown) { + 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) { + 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", + }), + ) + } + + 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. + const inChangedYml = ymlModelColumns(await opts.changedYmlText(), 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", + }), + ) + } + return out +} + +/** + * 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) + const mirrors = lists.filter((l) => listMirrorsModel(l, model, lists) === true) + const undecided = lists.filter((l) => listMirrorsModel(l, model, lists) === undefined) + if (!mirrors.length && !undecided.length) return [] + const { added, removed, unknown } = columnDelta(ctx) + if (unknown) { + 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) + abstain( + `consumerColumnLists: ${list.path}${listLabel(list, lists) ? ` (${listLabel(list, lists)})` : ""} 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 label = listLabel(list, lists) + // 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 } }, + ruleKey: `lineage_breakage:consumer-list:${list.path}${label ? `:${label}` : ""}`, + }), + ) + } + return out +} + /** * 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 @@ -1551,6 +1782,29 @@ export async function runReview(input: OrchestrateInput): Promise = [] + 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" }) + } + // New content of the PR's changed schema files, read once and only if a lane asks. + let ymlText: Promise | undefined + const changedYmlText = () => + (ymlText ??= Promise.all( + reviewable + .filter((f) => f.kind === "schema_yml" && f.status !== "deleted") + .map((f) => (getContent?.(f.path, "new") ?? Promise.resolve(undefined)).then((t) => t ?? "").catch(() => "")), + )) const all: Finding[][] = [] // Files where the diff-scoped PII classifier completed (looked at the change), @@ -1797,6 +2051,22 @@ export async function runReview(input: OrchestrateInput): Promise 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 @@ -1879,7 +2149,11 @@ export async function runReview(input: OrchestrateInput): Promise detectModelPatterns(ctx.file, ctx.newSql, input.rubric))) + tasks.push( + Promise.resolve().then(() => + detectModelPatterns(ctx.file, ctx.newSql, input.rubric, { dialect, dialectKnown: !!input.dialectKnown }), + ), + ) tasks.push(lexicalLane(ctx.file, input.runner)) } // dbt config/Jinja lint (materialization / incremental / contract) — gate on its @@ -1995,7 +2269,10 @@ export async function runReview(input: OrchestrateInput): Promise + portabilityBody?: string + /** Match `added` outside quoted strings only (e.g. `'2024/01/15'` is not a division). */ + ignoreStrings?: boolean example: RuleExample counter?: RuleExample } @@ -66,6 +77,11 @@ function modelName(p: string): string { return path.basename(p).replace(/\.(sql|py)$/i, "") } +/** Replace quoted string contents so text inside literals can't match. */ +function stripStrings(s: string): string { + return s.replace(/'(?:[^']|'')*'/g, "''").replace(/"(?:[^"\\]|\\.)*"/g, '""') +} + function stripComments(s: string): string { return s .replace(/\/\*[\s\S]*?\*\//g, " ") @@ -107,7 +123,7 @@ export function ruleMatches(rule: Rule, input: RuleInput): boolean { let relevant = false if (rule.added) { const hit = input.added.some((l) => { - const s = stripComments(l) + const s = rule.ignoreStrings ? stripStrings(stripComments(l)) : stripComments(l) return rule.added!.test(s) && !(rule.unless && rule.unless.test(s)) }) if (!hit) return false @@ -1062,9 +1078,21 @@ export interface FinalOutputs { * `ParsedSelects.unmodelled`, `misread` and `unknownSources`): its outputs * may be incomplete. */ unfollowed: boolean + /** The final projection's output names in column order, with a `*` (plain, + * qualified, or with `exclude` / `except` / `replace` / `rename`) expanded + * over CTEs and subqueries whose columns are all known; `undefined` for an + * unnamed column. The whole list is `undefined` when it cannot be told: a + * `*` over a table, a `ref()` or an unknown layout, or a query the parser + * does not model. A source it cannot name (`(values …) m(id, label)`) does + * not matter when the projection names its columns. */ + columns?: Array } -interface ScopeOutputs extends Omit { +interface ScopeOutputs + extends Omit< + FinalOutputs, + "passthrough" | "starRaw" | "prefixes" | "bodies" | "bodyTexts" | "rootText" | "unfollowed" | "unionStar" | "unionBranches" | "columns" + > { /** `*` items, whose columns pass through unnamed (`select * from customers`). */ stars: Array<{ branch: number; qualifier?: string }> /** The output names in column order (`undefined` for an unnamed one), when @@ -1981,7 +2009,57 @@ export function finalOutputs(sql: string): FinalOutputs { const rootText = textOf(rootBody.replace(/;\s*$/, "")) const rootBranches = new Set((byScope.get(ROOT_SCOPE) ?? []).map((i) => i.branch)).size const unionStar = rootBranches > 1 && stars.some((st) => st.branch > 0 || !layout) - return { raw, names, lineage, reads, unmapped, passthrough: stars.length > 0, starRaw, prefixes, bodies, bodyTexts, rootText, unionStar, unionBranches: rootBranches, unfollowed: unmodelled || misread || unknownSources.size > 0 } + // The root's columns in order, from an allow-list of shapes: a scope whose + // `*` is expanded, or that is a UNION, must have the plain shape `plainShape` + // accepts, and each `*` must span only CTEs or subqueries whose own columns + // are known the same way. A modified `*` applies its exclusions and renames. + // Anything else is unknown, and stays unknown through every scope that + // expands it. + const strictMemo = new Map | undefined>() + const strictLayout = (scope: string, seen: Set): Array | undefined => { + if (strictMemo.has(scope)) return strictMemo.get(scope) + strictMemo.set(scope, undefined) // a scope that reads itself has no known layout + const result = strictLayoutOf(scope, seen) + strictMemo.set(scope, result) + return result + } + const strictLayoutOf = (scope: string, seen: Set): Array | undefined => { + const all = byScope.get(scope) ?? [] + const items = all.filter((i) => i.branch === 0).sort((a, b) => a.position - b.position) + if (!items.length) return undefined + const body = scope === ROOT_SCOPE ? rootBody : scopeBody.get(scope) + const expands = all.some((i) => STAR_PREFIX.test(i.text)) + if ((expands || all.some((i) => i.branch > 0)) && (body === undefined || !plainShape(body))) return undefined + const key = `${scope}#0` + const inner = new Set([...seen, scope]) + const out: Array = [] + for (const item of items) { + if (!STAR_PREFIX.test(item.text)) { + if (UNNAMED_COLUMNS.test(item.text)) return undefined + out.push(item.name) + continue + } + const star = starItem(item.text) + if (!star || star.opaque || merged.has(key)) return undefined + const q = star.qualifier + // An unqualified `*` spans every source, so one the parser cannot name + // (`(values …) m(id, label)`) makes its columns unknown. + if (!q && unknownSources.has(key)) return undefined + const srcs = (sources.get(key) ?? []).filter((src) => !q || src.alias === q || src.name === q) + const parts = srcs.map((src) => (isDerived(src, scope, seen) ? strictLayout(src.name, inner) : undefined)) + if (!srcs.length || parts.some((part) => !part)) return undefined + for (const column of parts.flatMap((part) => part!)) { + if (column === undefined) return undefined + out.push(...star.outputs(column)) + } + } + // Two outputs under one name: engines rename or reject them. + const named = out.filter((c): c is string => !!c).map((c) => c.toLowerCase()) + if (new Set(named).size !== named.length) return undefined + return out + } + const rootColumns = () => (unmodelled || misread ? undefined : strictLayout(ROOT_SCOPE, new Set())) + return { raw, names, lineage, reads, unmapped, passthrough: stars.length > 0, starRaw, prefixes, bodies, bodyTexts, rootText, unionStar, unionBranches: rootBranches, unfollowed: unmodelled || misread || unknownSources.size > 0, columns: rootColumns() } } /** A Jinja statement tag that emits no text of its own: control flow and `set`. */ @@ -2109,19 +2187,144 @@ interface StarItem { /** The names `column` leaves the star under: none when it is excluded or * replaced by an expression, its new name when renamed. */ carries: (column: string) => string[] + /** The output column `column` becomes, raw or not: none when excluded, its + * new name when renamed (a `replace` keeps the slot and the name). */ + outputs: (column: string) => string[] } const STAR_ONLY_CALL = new RegExp(String.raw`(? m[0]) + const word = (t: string | undefined) => (t && /^[A-Za-z_]/.test(t) ? t.toLowerCase() : undefined) + const isName = (t: string | undefined) => !!t && (/^["`[]/.test(t) || (!!word(t) && !PLAIN_NOT_ALIAS.has(word(t)!))) + let i = 0 + const at = (k = 0) => word(tokens[i + k]) + const end = () => i >= tokens.length + // `[inner|left|right|full [outer]|cross] join`; any other join word fails. + const join = (): boolean | undefined => { + const w = at() + if (w === "join") return (i += 1), true + if (w === "inner" || w === "cross") return at(1) === "join" ? ((i += 2), true) : false + if (w === "left" || w === "right" || w === "full") { + if (at(1) === "join") return (i += 2), true + if (at(1) === "outer" && at(2) === "join") return (i += 3), true + return false + } + return JOIN_LEAD.has(w ?? "") ? false : undefined + } + const source = (): boolean => { + if (tokens[i] === "()") i++ + else if (isName(tokens[i])) { + i++ + while (tokens[i] === "." && isName(tokens[i + 1])) i += 2 + } else return false + if (at() === "as") { + if (!isName(tokens[i + 1])) return false + i += 2 + } else if (isName(tokens[i])) i++ + // A column list after the alias, or a call (a table function), renames or + // computes columns. + return tokens[i] !== "()" && tokens[i] !== "." + } + const branch = (): boolean => { + if (at() !== "select") return false + i++ + if (at() === "distinct") i++ + while (!end() && at() !== "from") { + if (CLAUSE_WORDS.has(at() ?? "")) return tail() + i++ + } + if (end()) return true + i++ // from + if (!source()) return false + for (;;) { + if (end()) return true + if (tokens[i] === ",") { + i++ + if (!source()) return false + continue + } + const j = join() + if (j === false) return false + if (j === true) { + if (!source()) return false + if (at() === "using") { + if (tokens[i + 1] !== "()") return false + i += 2 + } else if (at() === "on") { + i++ + while (!end() && tokens[i] !== "," && !CLAUSE_WORDS.has(at() ?? "") && !(JOIN_LEAD.has(at() ?? "") && tokens[i + 1] !== "()")) i++ + } + continue + } + return tail() + } + } + // `where`, `group by`, `qualify`, `order by`, `limit`, in any order, then + // the end or `union [all]` and another branch. + const tail = (): boolean => { + for (;;) { + if (end()) return true + const w = at() + if (w === "union") { + i++ + if (at() === "all") i++ + return branch() + } + if (w === "group" || w === "order") { + if (at(1) !== "by") return false + i += 2 + } else if (w === "where" || w === "qualify" || w === "limit") i++ + else return false + while (!end() && !CLAUSE_WORDS.has(at() ?? "")) i++ + } + } + return branch() +} + function starItem(text: string): StarItem | undefined { const head = STAR_HEAD.exec(text) if (!head) { // A positional column (`$2`), a column pattern (`columns('ss.')`) or a name // resolved at run time (`identifier('ssn')`, `identifier($col)`) names nothing. if (/(? [c] } + return { opaque: true, carries: (c) => [c], outputs: (c) => [c] } // A `*` inside the item that is not a multiplication (an operand on both // sides): `object_construct(*)`, `struct(t.*)`, `as struct *`. `count(*)` // reads no column, and neither does a count or a masking call over the @@ -2132,7 +2335,7 @@ function starItem(text: string): StarItem | undefined { const prev = /(\S)\s*$/.exec(t.slice(0, i))?.[1] const next = /^\s*(\S)/.exec(t.slice(i + 1))?.[1] const product = !!prev && /[\w$)"'\x60\]]/.test(prev) && !!next && /[\w$("'\x60.+-]/.test(next) - if (!product) return { opaque: true, carries: (c) => [c] } + if (!product) return { opaque: true, carries: (c) => [c], outputs: (c) => [c] } } return undefined } @@ -2145,7 +2348,7 @@ function starItem(text: string): StarItem | undefined { let rest = text.slice(head[0].length) while (rest.trim()) { const m = /^\s*(exclude|except|replace|rename)\b\s*/i.exec(rest) - if (!m) return { qualifier, opaque: true, carries: (c) => [c] } + if (!m) return { qualifier, opaque: true, carries: (c) => [c], outputs: (c) => [c] } rest = rest.slice(m[0].length) let list: string if (rest.startsWith("(")) { @@ -2155,7 +2358,7 @@ function starItem(text: string): StarItem | undefined { } else { // One bare entry: `exclude ssn`, `rename a as b`. const bare = new RegExp(String.raw`^${SEGMENT}(?:\s+as\s+${SEGMENT})?`, "i").exec(rest) - if (!bare) return { qualifier, opaque: true, carries: (c) => [c] } + if (!bare) return { qualifier, opaque: true, carries: (c) => [c], outputs: (c) => [c] } list = bare[0] rest = rest.slice(bare[0].length) } @@ -2163,14 +2366,14 @@ function starItem(text: string): StarItem | undefined { for (const entry of topLevelItems(list)) { if (!entry.trim()) continue if (kind === "exclude" || kind === "except") { - if (!SEGMENT_ONLY.test(entry.trim())) return { qualifier, opaque: true, carries: (c) => [c] } + if (!SEGMENT_ONLY.test(entry.trim())) return { qualifier, opaque: true, carries: (c) => [c], outputs: (c) => [c] } dropped.add(unquote(entry.trim())) continue } // `expr as name`: a raw column under `name`, or an expression that masks it. const item = describeItem(entry) const { alias } = splitAlias(item.text) - if (!alias) return { qualifier, opaque: true, carries: (c) => [c] } + if (!alias) return { qualifier, opaque: true, carries: (c) => [c], outputs: (c) => [c] } steps.push({ kind: kind as "replace" | "rename", from: item.rawColumn, expr: unmaskedExpr(item.text), to: unquote(alias) }) } } @@ -2188,7 +2391,9 @@ function starItem(text: string): StarItem | undefined { const renamed = (name: string) => steps.find((step) => step.kind === "rename" && step.from === name)?.to ?? name return [...new Set([...names].map(renamed))] } - return { qualifier, carries } + const outputs = (column: string) => + dropped.has(column) ? [] : [steps.find((step) => step.kind === "rename" && step.from === column)?.to ?? column] + return { qualifier, carries, outputs } } const wordIn = (text: string | undefined, word: string, dotted = true) => @@ -2726,6 +2931,22 @@ function capturedColumns(rule: Rule, added: string[]): SelectItemColumn[] { return out } +/** The project's engine, for engine-dependent rules. Omitted = unknown. */ +export interface CatalogContext { + dialect: string + /** False when the dialect is a default guess, not read from config or the manifest. */ + dialectKnown: boolean +} + +/** The body an engine-dependent rule reports for this project, or null to stay silent. */ +function gatedBody(rule: Rule, ctx: CatalogContext | undefined): string | null { + if (!rule.dialectGate || !ctx?.dialectKnown) return rule.body + const cap = capabilityFor(ctx.dialect) + if (!cap) return rule.body + if (cap[rule.dialectGate]) return rule.body + return rule.portabilityBody?.replace("{dialect}", ctx.dialect) ?? null +} + /** Evaluate the catalog against a changed file. */ export function evaluateCatalog( file: ChangedFile, @@ -2733,30 +2954,40 @@ export function evaluateCatalog( added: string[], removed: string[], rubric: Rubric, + ctx?: CatalogContext, ): Finding[] { const input: RuleInput = { file, newSql, added, removed } const model = modelName(file.path) const matched: { rule: Rule; finding: Finding }[] = [] for (const rule of CATALOG) { if (!ruleMatches(rule, input)) continue + const body = gatedBody(rule, ctx) + if (body === null) continue const f = makeFinding({ severity: clampSeverity(rule.category, rule.severity, "high"), category: rule.category, title: `${model}: ${rule.title}`, - body: rule.body, + body, file: file.path, model, confidence: "high", evidence: { tool: "rule-catalog", - result: rule.portability - ? { rule: rule.id, portability: true, worksOn: rule.portability.worksOn } - : rule.capturesColumns - ? (() => { - const items = capturedColumns(rule, added) - return { rule: rule.id, columns: [...new Set(items.map((i) => i.column))], items } - })() - : { rule: rule.id }, + result: + rule.portability || body !== rule.body + ? { + rule: rule.id, + portability: true, + // A dialect-gated body is the portability advice for the + // project's own engine, where the construct works as written. + worksOn: rule.portability?.worksOn ?? (body !== rule.body && ctx ? [ctx.dialect.toLowerCase()] : undefined), + } + : rule.capturesColumns + ? (() => { + const items = capturedColumns(rule, added) + return { rule: rule.id, columns: [...new Set(items.map((i) => i.column))], items } + })() + : { rule: rule.id }, }, ruleKey: `${rule.category}:${rule.id}`, }) @@ -2802,7 +3033,21 @@ const r = ( severity: Severity, title: string, body: string, - match: Pick, + match: Pick< + Rule, + | "added" + | "removed" + | "newSql" + | "absentNewSql" + | "unless" + | "kind" + | "pathGlob" + | "portability" + | "capturesColumns" + | "dialectGate" + | "portabilityBody" + | "ignoreStrings" + >, example: RuleExample, counter?: RuleExample, ): Rule => ({ id, category, severity, title, body, ...match, example, counter }) @@ -4475,10 +4720,21 @@ const MISC: Rule[] = [ "sql_correctness", "suggestion", "integer division truncates", - "`5 / 2` does integer division (=2) on many warehouses; cast a side to numeric for a real ratio.", - { added: /(? = { sqlserver: "tsql", synapse: "tsql", fabric: "fabric", + clickhouse: "clickhouse", } /** Read the dbt manifest's `metadata.adapter_type` and map it to a dialect. */ -async function detectDialect(manifestAbs: string): Promise { +export async function detectDialect(manifestAbs: string): Promise { try { const raw = await readFile(manifestAbs, "utf8") const adapter = String(JSON.parse(raw)?.metadata?.adapter_type ?? "").toLowerCase() @@ -395,6 +397,9 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise // the dbt manifest's `adapter_type` (so a BigQuery/Redshift project isn't // analyzed as the snowflake default — wrong-dialect portability suppression). const detectedDialect = config.dialect ? undefined : await detectDialect(manifestAbs) + // Known = set in config or read from the manifest. An adapter without a + // capability entry (a community adapter) keeps the generic engine-dependent + // advice: the catalog's capability gate finds nothing for it. const dialectKnown = !!config.dialect || !!detectedDialect if (!config.dialect) config.dialect = detectedDialect ?? "snowflake" @@ -471,6 +476,30 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise if (opts.noAi) aiDisabledReason = "disabled by --no-ai" else if (config.ai === false) aiDisabledReason = "disabled by `ai: false` in .altimate/review.yml" + const consumerLists = config.consumerColumnLists.length + ? await loadConsumerLists({ + configs: config.consumerColumnLists, + gitRoot, + // The resolved head SHA, as every other read in this run. + head, + read: (p) => getContent(p, "new"), + }) + : undefined + // The lists at the base too: a PR that removes a list file, or edits it so + // the pattern stops matching, would otherwise switch the check off unnoticed. + if (consumerLists && resolved) { + const atBase = await loadConsumerLists({ + configs: config.consumerColumnLists, + gitRoot, + head: resolved.sha, + read: (p) => showAtRef(gitRoot, resolved.sha, p), + side: "base", + }) + consumerLists.dropped = atBase.errors.length + ? [{ path: ".altimate/review.yml", reason: "consumerColumnLists: the base's lists could not be read, so a list this PR removes would go unnoticed" }] + : droppedLists(atBase.lists, consumerLists.lists) + } + return runReview({ changedFiles, config, @@ -500,6 +529,8 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise staleManifest, layout, suppressPortability: shouldSuppressPortability(config.portability, dialectKnown), + dialectKnown, + consumerLists, policy: { source: policy.source, hash: policy.hash, changedInPr: policy.changedInPr.length ? policy.changedInPr : undefined }, scope: { baseRef: resolved?.ref ?? opts.base, diff --git a/packages/opencode/src/altimate/review/runner.ts b/packages/opencode/src/altimate/review/runner.ts index 3b6fc716a6..901b68becf 100644 --- a/packages/opencode/src/altimate/review/runner.ts +++ b/packages/opencode/src/altimate/review/runner.ts @@ -1,6 +1,7 @@ import { Dispatcher } from "../native" import { EngineCoerce } from "../native/engine-coerce" import { parseManifest } from "../native/dbt/manifest" +import { loadRawManifest } from "../native/dbt/helpers" import type { CheckResult, EquivalenceResult, GradeResult, ImpactResult, ReviewRunner } from "./orchestrate" import { buildReviewSchemaContext, type SchemaContext } from "./schema-context" import { logDetail, reportFailure, type FailureFacts } from "./failure" @@ -296,8 +297,13 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun // Only surface validation errors when a REAL schema was supplied — // in lint-only mode the throwaway `_altimate_lint_` schema makes // every real table "unknown" and would flood the review. + // A manifest-derived schema lists only models documented in yml, so + // "table not found" there means "undocumented", not "missing": drop + // it unless the schema came from a complete catalog.json. hasTables - ? asArray(data.validation?.errors).map((e: any) => ({ ...e, rule: "validate", severity: "error" })) + ? asArray(data.validation?.errors) + .filter((e: any) => opts.schemaContext || e?.kind?.type !== "TableNotFound") + .map((e: any) => ({ ...e, rule: "validate", severity: "error" })) : [], ) .concat( @@ -497,6 +503,38 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun return out }, + async modelConsumers(model: string, file?: string) { + try { + const raw = loadRawManifest(opts.manifestPath) + if (!raw) return undefined + const nodes = Object.entries(raw.nodes ?? {}).filter(([id]) => id.startsWith("model.")) + // By file first: a versioned model (`fct_orders_v2.sql`) is named + // `fct_orders` with `version: 2`. Manifest paths are project-relative, + // the changed file repository-relative. + const byPath = (n: any) => { + const p = typeof n?.original_file_path === "string" ? n.original_file_path.replace(/\\/g, "/") : "" + return !!file && !!p && (file === p || file.endsWith(`/${p}`)) + } + const hit = + nodes.find(([, n]) => byPath(n)) ?? + nodes.find(([, n]) => n?.name === model) ?? + nodes.find(([, n]) => n?.version != null && `${n.name}_v${n.version}` === model) + if (!hit) return undefined + const [uid, node] = hit + const exposures = Object.values(raw.exposures ?? {}) + .filter((e) => Array.isArray(e?.depends_on?.nodes) && e.depends_on.nodes.includes(uid)) + .map((e) => ({ name: String(e.name ?? ""), type: e.type ? String(e.type) : undefined })) + const contractEnforced = node.config?.contract?.enforced === true || node.contract?.enforced === true + const contractColumns = contractEnforced + ? Object.values(node.columns ?? {}).map((c) => String(c?.name ?? "").toLowerCase()).filter(Boolean) + : [] + return { exposures, contractEnforced, contractColumns } + } catch (err) { + fail("modelConsumers", err) + return undefined + } + }, + async isComplex(sql: string, dialect?: string): Promise { // Only a tiering hint: a failure reads as "not complex" and is recorded // nowhere, since no check was skipped and the run must not lose approval. @@ -574,13 +612,8 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun }, async columnLineage(sql: string, dialect?: string): Promise> { - try { - const res = await callCore("altimate_core.column_lineage", { - sql, - schema_path: "", - schema_context: await resolveSchema(), - dialect, - }) + const lineage = async (schema_context: Record | undefined) => { + const res = await callCore("altimate_core.column_lineage", { sql, schema_path: "", schema_context, dialect }) const data = (res.data ?? {}) as Record // Core reports a lineage parse failure in `errors` with success:true: an // empty lineage then means "could not parse", not "no columns". @@ -590,6 +623,14 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun source: String(e.source ?? ""), target: String(e.target ?? ""), })) + } + try { + const schema = await resolveSchema() + const edges = await lineage(schema) + // A partial schema (the manifest only types documented models) makes + // the engine drop columns read from tables it doesn't know, returning + // nothing. Output column names need only the SQL: retry without it. + return edges.length || !schema ? edges : await lineage(undefined) } catch (err) { // The SQL lets a lane tell its own input's parse failure from another's. fail("columnLineage", err, [sql]) diff --git a/packages/opencode/src/altimate/review/unit-tests.ts b/packages/opencode/src/altimate/review/unit-tests.ts new file mode 100644 index 0000000000..8c928ea0f9 --- /dev/null +++ b/packages/opencode/src/altimate/review/unit-tests.ts @@ -0,0 +1,82 @@ +import YAML from "yaml" +import { makeFinding, type Finding } from "./finding" +import type { ChangedFile } from "./diff-filter" +import { codeSpan } from "./format" + +const inlineCode = (x: string) => codeSpan(x.replace(/\s+/g, " ")) + +/** + * dbt unit tests whose fixtures cannot exercise the model. When every `given` + * input has `rows: []`: + * - `expect` with no rows: the model's logic over its inputs is never tested; + * - `expect` with rows: the model has nothing to transform, so the test can + * only pass if the model emits constant rows. + * One empty input is normal (an empty `this` for an `is_incremental` test), so + * the rule needs all of them empty. Only unit tests added or changed in this + * PR are checked; `format: csv`/`sql` fixtures are skipped. + */ + +interface UnitTest { + name?: string + model?: string + given?: Array<{ input?: string; rows?: unknown; format?: string }> + expect?: { rows?: unknown; format?: string } +} + +function unitTestsOf(doc: unknown): Map { + const out = new Map() + const list = (doc as { unit_tests?: unknown })?.unit_tests + if (!Array.isArray(list)) return out + for (const t of list) { + if (t && typeof t === "object" && typeof (t as UnitTest).name === "string") out.set((t as UnitTest).name!, t as UnitTest) + } + return out +} + +const isDict = (f?: string) => f === undefined || f === "dict" + +export function detectUnitTestFixtures(file: ChangedFile, oldContent?: string, newContent?: string): Finding[] { + if (file.status === "deleted" || !newContent) return [] + let newDoc: unknown + let oldDoc: unknown + try { + newDoc = YAML.parse(newContent) + oldDoc = oldContent ? YAML.parse(oldContent) : undefined + } catch { + return [] + } + const before = unitTestsOf(oldDoc) + const out: Finding[] = [] + for (const [name, test] of unitTestsOf(newDoc)) { + const prev = before.get(name) + if (prev && JSON.stringify(prev) === JSON.stringify(test)) continue + const given = Array.isArray(test.given) ? test.given : [] + const allInputsEmpty = given.length > 0 && given.every((g) => isDict(g?.format) && Array.isArray(g?.rows) && g.rows.length === 0) + const expectRows = test.expect?.rows + if (!allInputsEmpty || !isDict(test.expect?.format) || !Array.isArray(expectRows)) continue + const model = test.model ?? "" + const passesAnyway = expectRows.length === 0 + out.push( + makeFinding({ + severity: passesAnyway ? "suggestion" : "warning", + category: "test_coverage", + // Names come from the PR's yml: code spans on one line, so a backtick, + // a line break or `@` in them can neither break the comment nor ping. + title: passesAnyway + ? `${inlineCode(model || name)}: unit test ${inlineCode(name)} doesn't exercise the model` + : `${inlineCode(model || name)}: unit test ${inlineCode(name)} expects rows from empty inputs`, + body: passesAnyway + ? "Every `given` input has `rows: []` and `expect` has no rows, so the model's logic over its inputs is never tested. " + + "Add input rows that exercise the logic under test." + : `Every \`given\` input has \`rows: []\` but \`expect\` has ${expectRows.length} row(s): the model has nothing to transform. ` + + "Add input rows that exercise the changed logic.", + file: file.path, + model: model || undefined, + confidence: "high", + evidence: { tool: "unit-test-fixtures", result: { rule: passesAnyway ? "unit_test_no_input_rows" : "unit_test_empty_inputs", test: name } }, + ruleKey: `test_coverage:unit-test-empty-inputs:${name}`, + }), + ) + } + return out +} diff --git a/packages/opencode/test/altimate/review-contracts-dialect.test.ts b/packages/opencode/test/altimate/review-contracts-dialect.test.ts new file mode 100644 index 0000000000..120d44fe8f --- /dev/null +++ b/packages/opencode/test/altimate/review-contracts-dialect.test.ts @@ -0,0 +1,999 @@ +import { afterEach, describe, test, expect, spyOn } from "bun:test" +import { promises as fs } from "node:fs" +import path from "node:path" +import { tmpdir } from "../fixture/fixture" +import { execFile, execFileSync } from "node:child_process" +import { promisify } from "node:util" +import { evaluateCatalog, finalOutputs } from "../../src/altimate/review/rule-catalog" +import { isCatalogPortability, runReview, ymlModelColumns, type ReviewRunner } from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import { + extractColumnList, + extractColumnLists, + listMirrorsModel, + loadConsumerLists, + findColumnLists, + droppedLists, + listLabel, + identifierNamesModel, + mentionsModel, + type ConsumerColumnList, + type ConsumerListLoad, +} from "../../src/altimate/review/consumer-lists" +import { coverageNotes, renderSummary } from "../../src/altimate/review/format" +import { detectUnitTestFixtures } from "../../src/altimate/review/unit-tests" +import { capabilityFor } from "../../src/altimate/review/adapter-capabilities" +import { createDispatcherRunner } from "../../src/altimate/review/runner" +import { detectDialect, reviewPullRequest } from "../../src/altimate/review/run" +import { Dispatcher } from "../../src/altimate/native" +import * as manifestHelpers from "../../src/altimate/native/dbt/helpers" +import { buildEnvelope } from "../../src/altimate/review/verdict" +import { emitReviewRun } from "../../src/altimate/review/telemetry" +import { Telemetry } from "../../src/altimate/telemetry" + +/** + * Checks that work on any dbt project from the manifest and the diff: + * engine-aware integer division, columns removed under exposures or an + * enforced contract, contract-vs-SELECT, unit-test fixtures that can't test + * anything, and opt-in consumer column lists outside dbt. + */ + +const exec = promisify(execFile) + +describe("integer division follows the adapter", () => { + const file = { path: "models/marts/m.sql", status: "modified" as const } + const run = (line: string, ctx?: { dialect: string; dialectKnown: boolean }) => + evaluateCatalog(file, line, [line], [], DEFAULT_RUBRIC, ctx).filter((f) => f.title.includes("integer division")) + + test("truncating engines get the correctness finding", () => { + for (const dialect of ["trino", "postgres", "redshift", "tsql"]) { + expect(capabilityFor(dialect)?.integerDivisionTruncates).toBe(true) + const [f] = run("select count(*) / count(distinct user_id) as r", { dialect, dialectKnown: true }) + expect(f.body).toContain("returns 3, not 3.5") + expect(isCatalogPortability(f)).toBe(false) + } + }) + + test("non-truncating engines get a portability finding (dropped for single-engine projects)", () => { + for (const dialect of ["snowflake", "bigquery", "databricks", "duckdb"]) { + const [f] = run("select 7 / 2 as r", { dialect, dialectKnown: true }) + expect(f.body).toContain(`returns a decimal on ${dialect}`) + expect(isCatalogPortability(f)).toBe(true) + } + }) + + test("unknown engine keeps the generic finding", () => { + expect(run("select 7 / 2 as r", { dialect: "snowflake", dialectKnown: false })[0].body).toContain("returns 3") + expect(run("select 7 / 2 as r")[0].body).toContain("returns 3") + }) + + test("shapes: count ratio and underscore literals match; casts and decimals don't", () => { + expect(run("select 1_000 / 3 as r")).toHaveLength(1) + expect(run("select count(*) / nullif(count(x), 0) as r")).toHaveLength(1) + expect(run("select count(*) * 1.0 / count(x) as r")).toHaveLength(0) + // Already numeric: a decimal multiplier before the ratio, or a cast on the divisor. + expect(run("select 100.0 * count(*) / nullif(count(x), 0) as pct")).toHaveLength(0) + expect(run("select 1.0 * count(*) / count(x) as r")).toHaveLength(0) + expect(run("select count(*) / count(x)::float as r")).toHaveLength(0) + expect(run("select count(*) / nullif(count(x), 0)::numeric as r")).toHaveLength(0) + expect(run("select 100 * count(*) / count(x) as pct")).toHaveLength(1) + expect(run("select cast(count(*) as double) / count(x) as r")).toHaveLength(0) + expect(run("select 7.0 / 2 as r")).toHaveLength(0) + expect(run("select col1 / 2 as r")).toHaveLength(0) + expect(run("where dt >= '2024/01/15'")).toHaveLength(0) + expect(run("select 'a 1/2 b' as label, 3 / 4 as r")).toHaveLength(1) + }) + + test("end to end: a Snowflake project drops it, a multi-adapter package keeps it", async () => { + const base = { + changedFiles: [{ path: "models/m.sql", status: "added" as const, diff: "+select 7 / 2 as r\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"], dialect: "snowflake" }, + rubric: DEFAULT_RUBRIC, + mode: "comment" as const, + runner: fakeRunner(), + getContent: async () => "select 7 / 2 as r", + dialectKnown: true, + } + const has = (fs: { title: string }[]) => fs.some((f) => f.title.includes("integer division")) + expect(has((await runReview({ ...base, suppressPortability: true })).findings)).toBe(false) + expect(has((await runReview({ ...base, suppressPortability: false })).findings)).toBe(true) + const trino = { ...base, config: { ...base.config, dialect: "trino" } } + expect(has((await runReview({ ...trino, suppressPortability: true })).findings)).toBe(true) + }) +}) + +/** Output columns are read from a simple `select a, b from …`. */ +function fakeRunner(consumers?: Awaited>>): ReviewRunner { + return { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: false } + }, + async detectPii() { + return { columns: [] } + }, + async columnLineage(sql: string) { + const m = /select\s+([\s\S]*?)\s+from/i.exec(sql) + if (!m) return [] + return m[1].split(",").map((c) => ({ source: `"src"."${c.trim()}"`, target: c.trim().split(/\s+as\s+/i).pop()! })) + }, + async modelConsumers() { + return consumers + }, + } as ReviewRunner +} + +const OLD = "select id, email, amount from src" +const NEW = "select id, amount, region from src" +const changed = [{ path: "models/marts/fct.sql", status: "modified" as const, diff: "-select id, email, amount from src\n+select id, amount, region from src\n" }] + +function review(consumers: Parameters[0], extra: Partial[0]> = {}) { + return runReview({ + changedFiles: changed, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["lineage_breakage", "contract_violation"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner: fakeRunner(consumers), + getContent: async (_f, side) => (side === "old" ? OLD : NEW), + getCompiled: async (_f, side) => (side === "old" ? OLD : NEW), + ...extra, + }) +} + +describe("consumers outside the DAG", () => { + test("a removed column on a model with exposures names them", async () => { + const env = await review({ exposures: [{ name: "revenue_dashboard", type: "dashboard" }], contractEnforced: false, contractColumns: [] }) + const f = env.findings.find((x) => x.title.includes("declared consumers")) + expect(f?.body).toContain("`email`") + expect(f?.body).toContain("`revenue_dashboard` (dashboard)") + expect(f?.origin).toBe("engine") + }) + + test("a removed column on a contracted model is flagged; a model with neither is not", async () => { + const contracted = await review({ exposures: [], contractEnforced: true, contractColumns: ["id", "amount", "region"] }) + expect(contracted.findings.find((x) => x.title.includes("declared consumers"))?.body).toContain("enforced contract") + const plain = await review({ exposures: [], contractEnforced: false, contractColumns: [] }) + expect(plain.findings.some((x) => x.title.includes("declared consumers"))).toBe(false) + }) + + const optIn = { config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["lineage_breakage", "contract_violation"], checkContractColumns: true } } + + test("opt-in: a new column missing from the enforced contract is reported, and never blocks", async () => { + const env = await review({ exposures: [], contractEnforced: true, contractColumns: ["id", "email", "amount"] }, optIn) + const f = env.findings.find((x) => x.title.includes("missing from the enforced contract")) + expect(f?.body).toContain("`region`") + expect(f?.origin).toBe("catalog") + // Only an added column (nothing removed), so the contract finding is the only one. + const added = "select id, email, amount, region from src" + const only = await review({ exposures: [], contractEnforced: true, contractColumns: ["id", "email", "amount"] }, { + ...optIn, + mode: "gate", + getContent: async (_f, side) => (side === "old" ? OLD : added), + getCompiled: async (_f, side) => (side === "old" ? OLD : added), + }) + expect(only.findings.map((x) => x.title)).toEqual(["fct: new column(s) missing from the enforced contract"]) + expect(only.idealVerdict).not.toBe("REQUEST_CHANGES") + expect(only.verdict).not.toBe("REQUEST_CHANGES") + }) + + test("off by default (dbt build enforces it), and skipped when the PR declares the column in a changed yml", async () => { + const consumers = { exposures: [], contractEnforced: true, contractColumns: ["id", "email", "amount"] } + const def = await review(consumers) + expect(def.findings.some((x) => x.title.includes("missing from the enforced contract"))).toBe(false) + const yml = await review(consumers, { + ...optIn, + changedFiles: [...changed, { path: "models/marts/_fct.yml", status: "modified", diff: "+ - name: region\n" }], + getContent: async (f, side) => (f.endsWith(".yml") ? "models:\n - name: fct\n columns:\n - name: region\n" : side === "old" ? OLD : NEW), + }) + expect(yml.findings.some((x) => x.title.includes("missing from the enforced contract"))).toBe(false) + }) + + test("a column another model declares in a changed yml does not count for this model", async () => { + const consumers = { exposures: [], contractEnforced: true, contractColumns: ["id", "email", "amount"] } + const other = await review(consumers, { + ...optIn, + changedFiles: [...changed, { path: "models/marts/_other.yml", status: "modified", diff: "+ - name: region\n" }], + getContent: async (f, side) => + f.endsWith(".yml") ? "models:\n - name: dim_region\n columns:\n - name: region\n" : side === "old" ? OLD : NEW, + }) + expect(other.findings.find((x) => x.title.includes("missing from the enforced contract"))?.body).toContain("`region`") + }) + + test("ymlModelColumns reads the model's own entry, including versions", () => { + const yml = + "models:\n - name: fct\n columns:\n - name: id\n versions:\n - v: 2\n columns:\n - name: region\n" + + " - name: other\n columns:\n - name: email\n" + expect([...ymlModelColumns([yml], "fct")].sort()).toEqual(["id", "region"]) + expect([...ymlModelColumns([yml], "fct_v2")].sort()).toEqual(["id", "region"]) + expect(ymlModelColumns([yml, "not: [valid"], "missing").size).toBe(0) + }) + + // Output names come from the projection: the engine's lineage leaves out + // outputs with no source column and columns of tables it has no schema for. + const exposed = { exposures: [{ name: "revenue_dashboard", type: "dashboard" }], contractEnforced: false, contractColumns: [] } + const reviewSql = (o: string, n: string, consumers: Parameters[0] = exposed) => + review(consumers, { + changedFiles: [{ path: "models/marts/fct.sql", status: "modified", diff: `-${o}\n+${n}\n` }], + getContent: async (_f, side) => (side === "old" ? o : n), + getCompiled: async (_f, side) => (side === "old" ? o : n), + // The engine's behaviour: no edge for an output without a source column. + runner: { ...fakeRunner(consumers), columnLineage: async () => [] }, + }) + const removes = (env: Awaited>) => env.findings.filter((x) => x.title.includes("declared consumers")) + + test("columns still selected are not reported removed: count(*), literals, a column from a newly joined table", async () => { + expect(removes(await reviewSql( + "select o.customer_id, count(o.order_id) as order_count from orders o group by 1", + "select o.customer_id, count(*) as order_count from orders o group by 1", + ))).toEqual([]) + expect(removes(await reviewSql( + "select o.order_id, o.status from orders o", + "select o.order_id, 'completed' as status, current_timestamp as loaded_at from orders o", + { exposures: [], contractEnforced: true, contractColumns: ["order_id", "status"] }, + ))).toEqual([]) + expect(removes(await reviewSql( + "select o.order_id, o.status from stg_orders o", + "select o.order_id, s.status from stg_orders o left join order_status_map s on o.status_code = s.code", + ))).toEqual([]) + // A real removal is still reported. + expect(removes(await reviewSql("select o.order_id, o.amount from orders o", "select o.order_id from orders o"))).toHaveLength(1) + }) + + // The dbt shape: CTEs, then `select * from final`. + const jaffle = (finalCols: string) => `with customers as ( + select * from "db"."main"."stg_customers" +), +orders as ( + select * from "db"."main"."stg_orders" +), +customer_orders as ( + select customer_id, min(order_date) as first_order, count(order_id) as number_of_orders + from orders group by customer_id +), +final as ( + select + ${finalCols} + from customers + left join customer_orders on customers.customer_id = customer_orders.customer_id +) +select * from final` + const jaffleCols = "customers.customer_id, customers.first_name, customer_orders.first_order, customer_orders.number_of_orders" + + test("`select * from final` over named CTE columns is a complete list: a removed column is reported", async () => { + const env = await reviewSql(jaffle(jaffleCols), jaffle("customers.customer_id, customers.first_name, customer_orders.first_order")) + expect(removes(env)[0]?.body).toContain("removes `number_of_orders`") + expect(env.scope?.unverified ?? []).toEqual([]) + }) + + test("`* exclude (…)` over a CTE applies the exclusion: a column dropped upstream is reported", async () => { + const env = await reviewSql( + "with f as (select order_id, amount, secret, status from orders) select * exclude (secret) from f", + "with f as (select order_id, amount, secret from orders) select * exclude (secret) from f", + ) + expect(removes(env)[0]?.body).toContain("removes `status`") + expect(removes(env)[0]?.body).not.toContain("secret") + // `rename` gives the new name; `replace` keeps the slot and the name. + const renamed = await reviewSql( + "with f as (select order_id, amount from orders) select * rename (amount as total) from f", + "with f as (select order_id, amount from orders) select * replace (amount * 100 as amount) from f", + ) + expect(removes(renamed)[0]?.body).toContain("removes `total`") + }) + + test("a new contract column on a `select * from final` model is reported when the check is on", async () => { + const consumers = { exposures: [], contractEnforced: true, contractColumns: ["customer_id", "first_name", "first_order", "number_of_orders"] } + const o = jaffle(jaffleCols) + const n = jaffle(`${jaffleCols}, customers.email`) + const env = await review(consumers, { + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["lineage_breakage", "contract_violation"], checkContractColumns: true }, + changedFiles: [{ path: "models/marts/fct.sql", status: "modified", diff: `-x\n+y\n` }], + getContent: async (_f, side) => (side === "old" ? o : n), + getCompiled: async (_f, side) => (side === "old" ? o : n), + }) + expect(env.findings.find((x) => x.title.includes("missing from the enforced contract"))?.body).toContain("`email`") + }) + + test("a source the parser cannot name does not matter when the projection names its columns", async () => { + const env = await reviewSql( + "select o.order_id, m.label from orders o join (values (1, 'a')) m(id, label) on o.k = m.id", + "select o.order_id from orders o join (values (1, 'a')) m(id, label) on o.k = m.id", + ) + expect(removes(env)[0]?.body).toContain("removes `label`") + // A `*` over it cannot be listed. + const star = await reviewSql( + "select o.order_id, m.* from orders o join (values (1, 'a')) m(id, label) on o.k = m.id", + "select o.order_id from orders o join (values (1, 'a')) m(id, label) on o.k = m.id", + ) + expect(removes(star)).toEqual([]) + expect(star.scope?.unverified).toContainEqual(expect.objectContaining({ kind: "abstained" })) + }) + + test("FROM items whose columns the parser does not follow are abstained on, at the root or through a CTE", async () => { + const piv = (vals: string) => + `with f as (select id, status, amount from orders) select * from f pivot (sum(amount) for status in (${vals}))` + const cases: Array<[string, string, Parameters[0]?]> = [ + [piv("'a', 'b'"), piv("'a', 'b', 'c'"), { exposures: [], contractEnforced: true, contractColumns: ["id", "a", "b"] }], + [piv("'a', 'b'"), piv("'a'")], + [ + "with f as (select id, status, amount from orders), p as (select * from f pivot (sum(amount) for status in ('a', 'b')) as p (id, a, b)) select id, a, b from p", + "with f as (select id, status, amount from orders), p as (select * from f pivot (sum(amount) for status in ('a' as a, 'b' as b))) select * from p", + ], + [ + "with f as (select id, status, amount from orders) select id, sum(case when status = 'a' then amount end) as a from f group by id", + "with f as (select id, status, amount from orders) select * from f pivot (sum(amount) for status in ('a' as a))", + ], + [ + "with f as (select id, a, b from orders) select * from f unpivot (val for col in (a, b))", + "with f as (select id, a, b from orders) select * from f unpivot (amount for col in (a, b))", + ], + [ + "with f as (select id, amount from orders) select * from f join (values (1, 'a', 'x')) m(id2, label, extra) on f.id = m.id2", + "with f as (select id, amount from orders) select * from f join (values (1, 'a')) m(id2, label) on f.id = m.id2", + ], + [ + "with f as (select id, amount from orders) select f.*, m.id2, m.label from f join (values (1, 'a')) m(id2, label) on f.id = m.id2", + "with f as (select id, amount from orders), g as (select * from f join (values (1, 'a')) m(id2, label) on f.id = m.id2) select * from g", + ], + [ + "with f as (select id, arr from orders) select * from f lateral view explode(arr) t as tag", + "with f as (select id, arr from orders) select * from f lateral view explode(arr) t as tag_value", + ], + ] + for (const [o, n, consumers] of cases) { + const env = await reviewSql(o, n, consumers ?? exposed) + expect({ n, findings: env.findings.filter((x) => /removed column|missing from the enforced/.test(x.title)).length }).toEqual({ n, findings: 0 }) + expect(env.scope?.unverified).toContainEqual(expect.objectContaining({ path: "models/marts/fct.sql", kind: "abstained" })) + expect(env.idealVerdict).toBe(cleanVerdict) + } + }) + + test("`columns` is an allow-list: other FROM syntax and set operators are unknown", () => { + for (const sql of [ + "with f as (select id from t) select * from f cross join generate_series(1, 3) g(n)", + "with f as (select id, arr from t) select * from f, table(flatten(input => f.arr)) l", + "with f as (select id, amount from t) select * from f match_recognize (partition by id order by amount measures count(*) as c one row per match pattern (a+) define a as amount > 0)", + "with f as (select id, amount from t) select * from f at (offset => -60)", + "with f as (select id, amount from t) select * from f tablesample (10)", + "with a as (select id from t), b as (select name from u) select * from a positional join b", + "with a as (select id from t), b as (select name from u) select * from a natural join b", + "with a as (select id, amount from t), b as (select id, amount from u) select * from a minus select * from b", + "with a as (select id from t), b as (select s, id from u) select * from a union all by name select * from b", + "with f as (select id, id, amount from t) select * from f", + "with f as (select id, amount from t) select *, sum(amount) over w as s from f window w as (partition by id)", + ]) + expect({ sql, columns: finalOutputs(sql).columns }).toEqual({ sql, columns: undefined }) + for (const [sql, cols] of [ + ["with a as (select id, amount from t), b as (select id, name from u) select a.*, b.name from a join b on a.id = b.id", ["id", "amount", "name"]], + ["with f as (select id, amount from t) select * from f where amount > 0 qualify row_number() over (partition by id order by amount) = 1 order by id limit 5", ["id", "amount"]], + ["with a as (select id, amount from t), b as (select customer_id, amount from t) select * from a union all select * from b", ["id", "amount"]], + ["with f as (select id, amount from t) select * from (select * from f) x", ["id", "amount"]], + ["with f as (select id, amount, status from t) select * exclude (status) from f", ["id", "amount"]], + ] as const) + expect(finalOutputs(sql).columns).toEqual([...cols]) + }) + + test("a `*` over an undocumented table or an unnamed expression: abstained, listed, not reported", async () => { + for (const n of [ + "select o.*, c.name from orders o join cust c on o.customer_id = c.id", + "select o.order_id, count(*) from orders o group by 1", + ]) { + const env = await reviewSql("select o.order_id, o.amount, c.name from orders o join cust c on o.customer_id = c.id", n) + expect(removes(env)).toEqual([]) + expect(env.scope?.unverified).toContainEqual(expect.objectContaining({ path: "models/marts/fct.sql", kind: "abstained" })) + expect(env.idealVerdict).toBe(cleanVerdict) + } + }) + + test("names from the manifest and the SQL stay inside code spans", async () => { + const col = ["e", "`", "m @", "y"].join("") + const dash = ["d", "`", " @", "x"].join("") + const env = await reviewSql(`select id, "${col}" from src`, "select id from src", { exposures: [{ name: dash, type: "dashboard" }], contractEnforced: false, contractColumns: [] }) + const body = removes(env)[0]?.body ?? "" + expect(body).toContain("removes ``e`m @y``") + expect(body).toContain("exposure(s) ``d` @x`` (dashboard)") + }) + + test("a versioned model is found by its file, and a removal under its exposure is reported", async () => { + await using tmp = await tmpdir() + const manifestPath = path.join(tmp.path, "manifest.json") + const uid = "model.shop.fct_orders.v2" + await fs.writeFile( + manifestPath, + JSON.stringify({ + metadata: { adapter_type: "snowflake" }, + nodes: { + [uid]: { + resource_type: "model", name: "fct_orders", version: 2, original_file_path: "models/fct_orders_v2.sql", + depends_on: { nodes: [] }, config: { contract: { enforced: true } }, + columns: { order_id: { name: "order_id", data_type: "int" }, amount: { name: "amount", data_type: "int" } }, + }, + }, + sources: {}, + exposures: { "exposure.shop.rev": { name: "revenue_dashboard", type: "dashboard", depends_on: { nodes: [uid] } } }, + }), + ) + const real = createDispatcherRunner({ manifestPath }) + const consumers = await real.modelConsumers!("fct_orders_v2", "dbt/models/fct_orders_v2.sql") + expect(consumers?.exposures.map((e) => e.name)).toEqual(["revenue_dashboard"]) + expect(await real.modelConsumers!("fct_orders_v2")).toEqual(consumers) + const o = "select o.order_id, o.amount from orders o" + const n = "select o.order_id from orders o" + const env = await review(undefined, { + changedFiles: [{ path: "dbt/models/fct_orders_v2.sql", status: "modified", diff: `-${o}\n+${n}\n` }], + getContent: async (_f, side) => (side === "old" ? o : n), + getCompiled: async (_f, side) => (side === "old" ? o : n), + runner: { ...fakeRunner(), modelConsumers: real.modelConsumers }, + }) + expect(env.findings.find((x) => x.title.includes("declared consumers"))?.body).toContain("removes `amount`") + }) + + test("a star select is never guessed at", async () => { + const env = await review( + { exposures: [{ name: "d" }], contractEnforced: false, contractColumns: [] }, + { getCompiled: async (_f, side) => (side === "old" ? "select * from src" : NEW) }, + ) + expect(env.findings.some((x) => x.title.includes("declared consumers"))).toBe(false) + }) +}) + +describe("opt-in consumer column lists", () => { + test("lists are extracted from the capture group; models matched by name", () => { + const py = 'MART_COLUMNS = [\n "id",\n "amount",\n \'email\',\n]\nTABLE = "fct"\n' + expect(extractColumnList(py, /MART_COLUMNS\s*=\s*\[([^\]]*)\]/)).toEqual(["id", "amount", "email"]) + const [found] = findColumnLists(py, /MART_COLUMNS\s*=\s*\[([^\]]*)\]/) + const list = { path: "loaders/fct.py", content: py, ...found } + // `TABLE = "fct"` is a neighbouring line, not the match's own: undecided. + expect(listMirrorsModel(list, "fct")).toBeUndefined() + expect(listMirrorsModel(list, "fct_orders")).toBe(false) + expect(listMirrorsModel({ ...list, model: "other" }, "fct")).toBe(false) + // Where the match is is not known: the file naming the model is not enough. + expect(listMirrorsModel({ path: "loaders/fct.py", columns: ["id"], content: py }, "fct")).toBeUndefined() + }) + + test("two lists in one file are kept apart, so a stale one is not masked", () => { + const py = 'A = [id, amount, region]\nB = [id, amount]\n' + expect(extractColumnLists(py, /= \[([^\]]*)\]/)).toEqual([ + ["id", "amount", "region"], + ["id", "amount"], + ]) + }) + + test("a list missing the new column and keeping the removed one is reported", async () => { + const env = await review(undefined, { + consumerLists: loaded([{ path: "loaders/fct.py", columns: ["id", "email", "amount"], content: "fct", own: "fct" }]), + }) + const f = env.findings.find((x) => x.title.includes("loaders/fct.py")) + expect(f?.body).toContain("lacks the new column(s) `region`") + expect(f?.body).toContain("still lists the removed column(s) `email`") + expect(f?.origin).toBe("catalog") + }) + + test("an up-to-date list, or no lists configured, reports nothing", async () => { + const ok = await review(undefined, { + consumerLists: loaded([{ path: "loaders/fct.py", columns: ["id", "amount", "region"], content: "fct", own: "fct" }]), + }) + expect(ok.findings.some((x) => x.title.includes("loaders/fct.py"))).toBe(false) + }) + + test("lists are read from the head with git; a bad pattern is reported, not fatal", async () => { + await using tmp = await tmpdir() + const root = tmp.path + const g = (...a: string[]) => exec("git", a, { cwd: root }) + await g("init", "-q", "-b", "main") + await fs.mkdir(path.join(root, "loaders"), { recursive: true }) + await fs.writeFile(path.join(root, "loaders", "fct.py"), 'COLS = ["id", "amount"]\n') + await fs.writeFile(path.join(root, "loaders", "other.txt"), 'COLS = ["x"]\n') + await g("add", "-A") + const lists = await loadConsumerLists({ + configs: [ + { files: "loaders/**/*.py", pattern: "COLS\\s*=\\s*\\[([^\\]]*)\\]", model: "fct" }, + { files: "loaders/**", pattern: "([", model: "fct" }, + ], + gitRoot: root, + read: (p) => fs.readFile(path.join(root, p), "utf8"), + }) + expect(lists.lists.map((l) => [l.path, l.columns, l.name, l.line])).toEqual([["loaders/fct.py", ["id", "amount"], "COLS", 1]]) + // One usable entry: the bad one is listed for the author to fix, the run is not failed. + expect(lists.invalid).toHaveLength(1) + expect(lists.invalid).toEqual(["entry 2: the pattern is not a valid regular expression"]) + expect(lists.errors).toEqual([]) + }) + + test("with a head ref the files are listed from that commit (ls-tree takes no glob magic)", async () => { + await using tmp = await tmpdir() + const root = tmp.path + const g = (...a: string[]) => exec("git", a, { cwd: root }) + await g("init", "-q", "-b", "main") + await fs.mkdir(path.join(root, "loaders", "nested"), { recursive: true }) + await fs.writeFile(path.join(root, "loaders", "nested", "fct.py"), 'COLS = ["id", "amount"]\n') + await fs.writeFile(path.join(root, "loaders", "other.txt"), 'COLS = ["x"]\n') + await g("add", "-A") + await g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "init") + // Only in the working tree: must not be listed when reading the head. + await fs.writeFile(path.join(root, "loaders", "untracked.py"), 'COLS = ["y"]\n') + const lists = await loadConsumerLists({ + configs: [{ files: "loaders/**/*.py", pattern: "COLS\\s*=\\s*\\[([^\\]]*)\\]", model: "fct" }], + gitRoot: root, + head: "HEAD", + read: (p) => fs.readFile(path.join(root, p), "utf8"), + }) + expect(lists.lists.map((l) => [l.path, l.columns])).toEqual([["loaders/nested/fct.py", ["id", "amount"]]]) + }) + + test("a submodule under the glob is not read as a file, at the head or in the working tree", async () => { + await using tmp = await tmpdir() + const root = tmp.path + const g = (...a: string[]) => exec("git", a, { cwd: root }) + await g("init", "-q", "-b", "main") + await fs.mkdir(path.join(root, "loaders"), { recursive: true }) + await fs.writeFile(path.join(root, "loaders", "fct.py"), "COLS = [id]\n") + await g("add", "-A") + await g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "init") + // A gitlink (mode 160000) at loaders/vendor_sdk, as `git submodule add` leaves it. + const sha = (await g("rev-parse", "HEAD")).stdout.trim() + await g("update-index", "--add", "--cacheinfo", `160000,${sha},loaders/vendor_sdk`) + await g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "submodule") + const read = async (p: string) => fs.readFile(path.join(root, p), "utf8").catch(() => undefined) + const cfg = [{ files: "loaders/**", pattern: "COLS = \\[([^\\]]*)\\]", model: "fct" }] + for (const head of ["HEAD", undefined]) { + const load = await loadConsumerLists({ configs: cfg, gitRoot: root, head, read }) + expect(load.errors).toEqual([]) + expect(load.lists.map((l) => l.path)).toEqual(["loaders/fct.py"]) + } + }) + + test("a failed file listing or list read is an engine error, so the run cannot approve", async () => { + await using noRepo = await tmpdir() + const cfg = { files: "loaders/**", pattern: "COLS = \\[([^\\]]*)\\]", model: "fct" } + const unlisted = await loadConsumerLists({ configs: [cfg], gitRoot: noRepo.path, read: async () => "" }) + expect(unlisted.errors.map((e) => e.method)).toEqual(["consumerColumnLists.listFiles"]) + + await using tmp = await tmpdir() + const root = tmp.path + await exec("git", ["init", "-q", "-b", "main"], { cwd: root }) + await fs.mkdir(path.join(root, "loaders"), { recursive: true }) + await fs.writeFile(path.join(root, "loaders", "a.py"), "COLS = [id]\n") + await fs.writeFile(path.join(root, "loaders", "b.py"), "COLS = [id]\n") + await exec("git", ["add", "-A"], { cwd: root }) + const unread = await loadConsumerLists({ configs: [cfg], gitRoot: root, read: async () => undefined }) + expect(unread.errors).toEqual([ + { method: "consumerColumnLists.read", reason: "could not read loaders/a.py", count: 2, category: "file_unreadable" }, + ]) + + const env = await review(undefined, { consumerLists: unread }) + expect(env.engineErrors?.find((e) => e.method === "consumerColumnLists.read")?.category).toBe("file_unreadable") + expect(env.idealVerdict).not.toBe("APPROVE") + // A file that could not be read is not a fault in the review: no exit 3. + expect(env.internalFailure).toBeUndefined() + expect(coverageNotes(env).join("\n")).toContain("consumerColumnLists.read") + }) + + test("unusable patterns are listed and never block, even when none is usable", async () => { + const bad = { files: "loaders/**", pattern: "([" } + const noGroup = { files: "loaders/**", pattern: "COLS = \\[.*\\]" } + await using noRepo = await tmpdir() + const none = await loadConsumerLists({ configs: [bad, noGroup], gitRoot: noRepo.path, read: async () => "COLS = [id]" }) + expect(none.invalid).toHaveLength(2) + expect(none.invalid[1]).toContain("no capture group") + // Fixed sentences: neither the pattern nor the regex engine's message is quoted. + expect(none.invalid).toEqual([ + "entry 1: the pattern is not a valid regular expression", + "entry 2: the pattern has no capture group, so it selects no list", + ]) + // The policy comes from the base: failing the run would also fail the PR that fixes the pattern. + expect(none.errors).toEqual([]) + const env = await review(undefined, { consumerLists: none }) + expect(env.engineErrors).toBeUndefined() + expect(env.idealVerdict).toBe(cleanVerdict) + expect(env.scope?.unverified?.filter((u) => u.path === ".altimate/review.yml" && u.kind === "abstained")).toHaveLength(2) + // Not selected by the tier's lanes: nothing to report. + const off = await review(undefined, { consumerLists: none, config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["sql_quality"] } }) + expect(off.scope?.unverified ?? []).toEqual([]) + }) + + test("a secret-shaped pattern is not quoted in the reason", async () => { + const value = ["Zq9", "xxxx", "Lm2Pq8Rt7Vw"].join("") + const secret = ["pass", "word=", value].join("") + await using noRepo = await tmpdir() + const load = await loadConsumerLists({ configs: [{ files: "x/**", pattern: `${secret}([` }], gitRoot: noRepo.path, read: async () => "" }) + expect(load.invalid.join()).not.toContain(value) + const env = await review(undefined, { consumerLists: load }) + expect(coverageNotes(env).join("\n")).not.toContain(value) + }) + + test("a list path with a backtick or @ stays inside a code span", async () => { + const weird = "loaders/we`ird@team.py" + const env = await review(undefined, { + consumerLists: loaded([{ path: weird, columns: ["id", "email", "amount"], content: "fct", own: "fct" }]), + }) + const f = env.findings.find((x) => x.title.includes(weird)) + expect(f?.title).toContain("``loaders/we`ird@team.py``") + expect(f?.body).toContain("The column list ``loaders/we`ird@team.py`` mirrors `fct`") + }) + + test("without `model`, the match's own lines and identifier decide; a neighbouring line leaves it undecided", async () => { + const lists = (content: string, re = /\[([^\]]*)\]/) => + findColumnLists(content, re).map((l) => ({ path: "loaders/export.py", content, ...l })) + const decide = (content: string, model: string) => { + const all = lists(content) + return all.map((l) => listMirrorsModel(l, model, all)) + } + // Adjacent calls: each list belongs to the model named on its own line. + const calls = 'load("fct", ["id", "email", "amount"])\nload("dim_customers", ["customer_id", "name"])\n' + expect(decide(calls, "fct")).toEqual([true, false]) + expect(decide(calls, "dim_customers")).toEqual([false, true]) + // Dict entries, keyed on the line the list opens on. + const dict = 'COLUMNS = {\n "dim_customers": [\n "customer_id",\n ],\n "fct": [\n "id",\n ],\n}\n' + expect(decide(dict, "fct")).toEqual([false, true]) + // An identifier naming the model, on `_` and case boundaries. + expect(decide('fct_orders_columns = ["id"]\nDimCustomersCols = ["customer_id"]\n', "fct_orders")).toEqual([true, false]) + expect(decide('FCT_ORDERS_COLS = ["id"]\n', "fct_orders")).toEqual([true]) + expect(decide('FCT_ORDERS_COLS = ["id"]\n', "orders_daily")).toEqual([false]) + // Named only on the line above, or elsewhere: undecided, never a match. + expect(decide('# Columns of fct\nORDER_COLUMNS = ["id"]\n', "fct")).toEqual([undefined]) + expect(decide('ORDER_COLUMNS = ["id"]\n\n\nload("fct", ORDER_COLUMNS)\n', "fct")).toEqual([undefined]) + + const env = await review(undefined, { consumerLists: loaded(lists(calls)) }) + expect(env.findings.filter((x) => x.title.includes("export.py")).map((x) => x.title)).toEqual([ + "fct: column list `line 1` in `loaders/export.py` is out of step", + ]) + const comment = await review(undefined, { consumerLists: loaded(lists('# Columns of fct\nORDER_COLUMNS = ["id", "email"]\n')) }) + expect(comment.findings.filter((x) => x.title.includes("export.py"))).toEqual([]) + expect(comment.scope?.unverified?.filter((u) => u.reason.includes("ORDER_COLUMNS")).map((u) => u.kind)).toEqual(["abstained"]) + expect(comment.idealVerdict).toBe(cleanVerdict) + }) + + test("an identifier names a model only as its exact words plus one list suffix; own lines only as a whole identifier", async () => { + expect(identifierNamesModel("ORDERS_COLUMNS", "orders")).toBe(true) + expect(identifierNamesModel("fctOrdersCols", "fct_orders")).toBe(true) + expect(identifierNamesModel("FCT_ORDERS", "fct_orders")).toBe(true) + expect(identifierNamesModel("STG_ORDERS_COLUMNS", "orders")).toBe(false) + expect(identifierNamesModel("FCT_ORDERS_DAILY_COLUMNS", "fct_orders")).toBe(false) + expect(identifierNamesModel("CUSTOMERS_ORDERS_JOIN_COLUMNS", "orders")).toBe(false) + expect(identifierNamesModel("WEBHOOK_EVENTS_ALLOWED", "events")).toBe(false) + expect(mentionsModel('load("stg_orders", [', "orders")).toBe(false) + expect(mentionsModel('load("orders", [', "orders")).toBe(true) + const listsOf = (path: string, content: string) => + findColumnLists(content, /\[([^\]]*)\]/).map((l) => ({ path, content, ...l })) + const add = "select id, email, amount, region from src" + const run = (model: string, lists: ConsumerColumnList[]) => + review(undefined, { + changedFiles: [{ path: `models/${model}.sql`, status: "modified", diff: "-x\n+y\n" }], + getContent: async (_f, side) => (side === "old" ? OLD : add), + getCompiled: async (_f, side) => (side === "old" ? OLD : add), + consumerLists: loaded(lists), + }) + const titles = (env: Awaited>) => env.findings.filter((x) => x.title.includes("column list")).map((x) => x.title) + expect(titles(await run("orders", listsOf("loaders/columns.py", 'ORDERS_COLUMNS = ["id", "email", "amount"]\nSTG_ORDERS_COLUMNS = ["id", "email", "amount"]\n')))).toEqual([ + "orders: column list `ORDERS_COLUMNS` in `loaders/columns.py` is out of step", + ]) + expect(titles(await run("fct_orders", listsOf("exports/daily.py", 'FCT_ORDERS_DAILY_COLUMNS = ["id", "email", "amount"]\n')))).toEqual([]) + expect(titles(await run("orders", listsOf("exports/join.py", 'CUSTOMERS_ORDERS_JOIN_COLUMNS = ["id", "email", "amount"]\n')))).toEqual([]) + expect(titles(await run("events", listsOf("app/settings.py", 'WEBHOOK_EVENTS_ALLOWED = ["id", "email", "amount"]\n')))).toEqual([]) + }) + + test("two lists with the same identifier in one file are both reported, told apart by line", async () => { + const content = + "exports:\n - target: s3://bucket/full\n columns:\n - id\n - email\n - target: s3://bucket/lite\n columns:\n - id\n - email\n" + const found = findColumnLists(content, /columns:\s*\n((?:\s*-\s*\w+\n)+)/) + const lists = found.map((l) => ({ path: "exports/fct.yml", model: "fct", content, ...l })) + expect(lists.map((l) => listLabel(l, lists))).toEqual(["columns (line 3)", "columns (line 7)"]) + const env = await review(undefined, { consumerLists: loaded(lists) }) + const hits = env.findings.filter((x) => x.title.includes("exports/fct.yml")) + expect(hits.map((x) => x.title)).toEqual([ + "fct: column list `columns (line 3)` in `exports/fct.yml` is out of step", + "fct: column list `columns (line 7)` in `exports/fct.yml` is out of step", + ]) + expect(new Set(hits.map((x) => x.id)).size).toBe(2) + }) + + test("the multi-list file from the audit: no finding for the other model's list", async () => { + const content = + "# Nightly export of fct_orders and dim_customers to the CRM\n" + + 'ORDERS_COLUMNS = ["order_id", "customer_id", "amount", "discount"]\n' + + 'CUSTOMERS_COLUMNS = ["customer_id", "name", "email"]\n' + const lists = findColumnLists(content, /= \[([^\]]*)\]/).map((l) => ({ path: "loaders/export.py", content, ...l })) + const o = "select o.order_id, o.customer_id, o.amount from orders o" + const n = "select o.order_id, o.customer_id, o.amount, o.discount from orders o" + const env = await review(undefined, { + changedFiles: [{ path: "models/fct_orders.sql", status: "modified", diff: `-${o}\n+${n}\n` }], + getContent: async (_f, side) => (side === "old" ? o : n), + getCompiled: async (_f, side) => (side === "old" ? o : n), + consumerLists: loaded(lists), + }) + expect(env.findings.filter((x) => x.title.includes("export.py"))).toEqual([]) + expect(env.scope?.unverified?.some((u) => u.reason.includes("CUSTOMERS_COLUMNS"))).toBe(true) + }) + + test("dropped lists: counted per identifier; moved files and rewritten calls with the same columns are kept", () => { + const Y = /columns:\s*\n((?:\s*-\s*\w+\n)+)/ + const B = /\[([^\]]*)\]/ + const mk = (path: string, content: string, re: RegExp) => findColumnLists(content, re).map((l) => ({ path, content, ...l })) + const yBase = "exports:\n - model: fct\n columns:\n - order_id\n - amount\n - model: dim\n columns:\n - customer_id\n - name\n" + const yHead = "exports:\n - model: dim\n columns:\n - customer_id\n - name\n" + expect(droppedLists(mk("exports.yml", yBase, Y), mk("exports.yml", yHead, Y))).toEqual([ + { path: "exports.yml", reason: "consumerColumnLists: column list columns (line 3) is no longer found at the head, so it is not checked" }, + ]) + const py = 'ORDER_COLUMNS = ["order_id", "amount"]\n' + expect(droppedLists(mk("loaders/a.py", py, B), mk("loaders/export/a.py", py, B))).toEqual([]) + expect( + droppedLists(mk("l.py", 'load(["order_id", "amount"])\n', B), mk("l.py", 'COLS = ["order_id", "amount"]\nload(COLS)\n', B)), + ).toEqual([]) + // Same file and identifier first: the removed list is the one named. + expect(droppedLists(mk("a.py", 'A = ["x", "y"]\nB = ["x", "y"]\n', B), mk("a.py", 'B = ["x", "y"]\n', B))).toEqual([ + { path: "a.py", reason: "consumerColumnLists: column list A is no longer found at the head, so it is not checked" }, + ]) + // A deleted list file is not kept alive by a lookalike list in another file the head still has. + const fixture = mk("tests/fixtures.py", 'SAMPLE = ["order_id", "amount"]\n', B) + expect(droppedLists([...mk("exports/orders.py", 'ORDERS = ["order_id", "amount"]\n', B), ...fixture], fixture)).toEqual([ + { path: "exports/orders.py", reason: "consumerColumnLists: column list ORDERS is no longer found at the head, so it is not checked" }, + ]) + // An edited list under the same identifier is kept (the lanes check its columns). + expect(droppedLists(mk("l.py", py, B), mk("l.py", 'ORDER_COLUMNS = ["order_id"]\n', B))).toEqual([]) + }) + + test("a list the base had and the head no longer yields is listed, not silently dropped", async () => { + await using tmp = await tmpdir() + const root = tmp.path + const g = (...a: string[]) => exec("git", a, { cwd: root }) + await g("init", "-q", "-b", "main") + await fs.mkdir(path.join(root, "exports")) + await fs.writeFile(path.join(root, "exports", "fct.py"), 'COLUMNS = ["id", "email", "amount"]\n') + await g("add", "-A") + await g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "base") + await fs.writeFile(path.join(root, "exports", "fct.py"), 'COLUMNS = list(["id", "email", "amount"])\n') + await g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qam", "head") + const configs = [{ files: "exports/**/*.py", pattern: "COLUMNS\\s*=\\s*\\[([^\\]]*)\\]", model: "fct" }] + const at = (ref: string) => (p: string) => exec("git", ["show", `${ref}:${p}`], { cwd: root }).then((r) => r.stdout) + const atHead = await loadConsumerLists({ configs, gitRoot: root, head: "HEAD", read: at("HEAD") }) + const atBase = await loadConsumerLists({ configs, gitRoot: root, head: "HEAD~1", read: at("HEAD~1") }) + expect(atHead.lists).toEqual([]) + atHead.dropped = droppedLists(atBase.lists, atHead.lists) + expect(atHead.dropped).toEqual([ + { path: "exports/fct.py", reason: "consumerColumnLists: column list COLUMNS is no longer found at the head, so it is not checked" }, + ]) + const env = await review(undefined, { consumerLists: atHead }) + expect(env.scope?.unverified).toContainEqual({ ...atHead.dropped[0], kind: "abstained" }) + expect(env.idealVerdict).toBe(cleanVerdict) + }) +}) + +/** The verdict `review()` gives with nothing to report. */ +const cleanVerdict = "APPROVE" + +describe("a PR that switches a consumer list off", () => { + let spy: ReturnType | undefined + afterEach(() => { + spy?.mockRestore() + spy = undefined + }) + + test("end to end: the head edits the list so the pattern no longer matches; the run lists it", async () => { + await using tmp = await tmpdir({ git: true }) + const dir = tmp.path + const g = (...a: string[]) => execFileSync("git", a, { cwd: dir }).toString().trim() + const base = g("rev-parse", "--abbrev-ref", "HEAD") + await fs.writeFile(path.join(dir, "dbt_project.yml"), "name: demo\nversion: '1'\nprofile: demo\n") + await fs.mkdir(path.join(dir, "models")) + await fs.mkdir(path.join(dir, "exports")) + await fs.mkdir(path.join(dir, ".altimate")) + await fs.writeFile( + path.join(dir, ".altimate/review.yml"), + 'reviewers: [lineage_breakage]\nconsumerColumnLists:\n - files: "exports/*.py"\n pattern: "COLUMNS = \\\\[([^\\\\]]*)\\\\]"\n model: m\n', + ) + await fs.writeFile(path.join(dir, "models/m.sql"), "select 1 as id\n") + await fs.writeFile(path.join(dir, "exports/m.py"), 'COLUMNS = ["id"]\n') + g("add", "-A") + g("commit", "-qm", "base") + g("checkout", "-q", "-b", "pr") + await fs.writeFile(path.join(dir, "models/m.sql"), "select 2 as id\n") + await fs.writeFile(path.join(dir, "exports/m.py"), 'COLUMNS = list(["id"])\n') + g("add", "-A") + g("commit", "-qm", "pr") + spy = spyOn(Dispatcher, "call").mockImplementation((async () => ({ success: true, data: {} })) as any) + const saved = { ref: process.env.GITHUB_BASE_REF, event: process.env.GITHUB_EVENT_PATH } + process.env.GITHUB_BASE_REF = base + delete process.env.GITHUB_EVENT_PATH + try { + const env = await reviewPullRequest({ cwd: dir, head: "pr", noAi: true }) + expect(env.scope?.unverified).toContainEqual({ + path: "exports/m.py", + reason: "consumerColumnLists: column list COLUMNS is no longer found at the head, so it is not checked", + kind: "abstained", + }) + expect(env.engineErrors).toBeUndefined() + } finally { + if (saved.ref === undefined) delete process.env.GITHUB_BASE_REF + else process.env.GITHUB_BASE_REF = saved.ref + if (saved.event !== undefined) process.env.GITHUB_EVENT_PATH = saved.event + } + }, 60000) +}) + +function loaded(lists: ConsumerColumnList[]): ConsumerListLoad { + return { lists, errors: [], invalid: [] } +} + +describe("unit tests that cannot exercise the model", () => { + const file = { path: "models/marts/_fct.yml", status: "modified" as const } + const yml = (expectRows: string) => `unit_tests: + - name: t1 + model: fct + given: + - input: ref('a') + rows: [] + - input: this + rows: [] + expect: + rows: ${expectRows} +` + test("all inputs empty and nothing expected: cannot fail", () => { + const [f] = detectUnitTestFixtures(file, undefined, yml("[]")) + expect(f.title).toContain("doesn't exercise the model") + expect(f.severity).toBe("suggestion") + }) + + test("a null `given` entry (valid YAML) is skipped, not a crash", () => { + const doc = `unit_tests: + - name: t1 + model: fct + given: [null] + expect: + rows: [] +` + expect(detectUnitTestFixtures(file, undefined, doc)).toEqual([]) + }) + + test("all inputs empty but rows expected", () => { + const [f] = detectUnitTestFixtures(file, undefined, yml("\n - {id: 1}")) + expect(f.title).toContain("expects rows from empty inputs") + }) + + test("an empty `this` next to a populated input is fine; unchanged tests are skipped", () => { + const ok = `unit_tests: + - name: t1 + model: fct + given: + - input: ref('a') + rows: + - {id: 1} + - input: this + rows: [] + expect: + rows: + - {id: 1} +` + expect(detectUnitTestFixtures(file, undefined, ok)).toHaveLength(0) + expect(detectUnitTestFixtures(file, yml("[]"), yml("[]"))).toHaveLength(0) + }) + + test("a test or model name with a backtick, a line break or @ stays inside one code span", () => { + const name = ["t", "`", "\n\n@", "someone ping"].join("") + const model = ["fct @", "team"].join("") + const doc = `unit_tests:\n - name: ${JSON.stringify(name)}\n model: ${JSON.stringify(model)}\n given:\n - input: ref('a')\n rows: []\n expect:\n rows: []\n` + const [f] = detectUnitTestFixtures(file, undefined, doc) + expect(f.title).toBe("`fct @team`: unit test ``t` @someone ping`` doesn't exercise the model") + expect(f.title).not.toContain("\n") + }) +}) + +describe("adapters the dialect map lacks", () => { + const writeManifest = async (dir: string, adapter: string) => { + const p = path.join(dir, `${adapter}.json`) + await fs.writeFile(p, JSON.stringify({ metadata: { adapter_type: adapter }, nodes: {} })) + return p + } + const division = (dialect: string) => + evaluateCatalog({ path: "models/m.sql", status: "modified" }, "select 7 / 2 as r", ["select 7 / 2 as r"], [], DEFAULT_RUBRIC, { + dialect, + dialectKnown: true, + }).find((f) => f.title.includes("integer division")) + + test("clickhouse maps to its dialect and gets its capability", async () => { + await using tmp = await tmpdir() + expect(await detectDialect(await writeManifest(tmp.path, "clickhouse"))).toBe("clickhouse") + expect(capabilityFor("clickhouse")).toBeDefined() + expect(division("clickhouse")?.body).toContain("returns a decimal on clickhouse") + }) + + test("an unmapped adapter is still a known dialect; only the capability gate is skipped", async () => { + await using tmp = await tmpdir() + expect(await detectDialect(await writeManifest(tmp.path, "materialize"))).toBe("materialize") + expect(capabilityFor("materialize")).toBeUndefined() + // The generic advice, as without a capability entry. + expect(division("materialize")?.body).toContain("returns 3, not 3.5") + }) +}) + +describe("no error text from these checks reaches the comment, the envelope or telemetry; the job log has it", () => { + // A unique string per run: if it shows up in public output, error text leaked. + const marker = () => ["leak", "marker", Math.random().toString(36).slice(2, 10)].join("-") + + /** Runs `fn` with stderr and telemetry captured. */ + async function captured(fn: () => Promise) { + const log: string[] = [] + const events: unknown[] = [] + const stderr = spyOn(process.stderr, "write").mockImplementation(((chunk: any) => { + log.push(String(chunk)) + return true + }) as any) + const track = spyOn(Telemetry, "track").mockImplementation(((e: unknown) => { + events.push(e) + }) as any) + try { + const env = await fn() + emitReviewRun({ invocation: "cli", durationMs: 1, sessionID: "", envelope: env }) + return { env, log: log.join(""), events: JSON.stringify(events) } + } finally { + stderr.mockRestore() + track.mockRestore() + } + } + + const cfg = { files: "loaders/**", pattern: "COLS = \\[([^\\]]*)\\]", model: "fct" } + async function repoWithList() { + const tmp = await tmpdir() + await exec("git", ["init", "-q", "-b", "main"], { cwd: tmp.path }) + await fs.mkdir(path.join(tmp.path, "loaders"), { recursive: true }) + await fs.writeFile(path.join(tmp.path, "loaders", "a.py"), "COLS = [id]\n") + await exec("git", ["add", "-A"], { cwd: tmp.path }) + return tmp + } + + const kinds: Record Promise> = { + "listing the list files fails (git)": async (m) => { + await using tmp = await repoWithList() + // git names the ref it cannot resolve in its error. + const load = await loadConsumerLists({ configs: [cfg], gitRoot: tmp.path, head: `refs/heads/${m}`, read: async () => "" }) + expect(load.errors.map((e) => [e.method, e.category])).toEqual([["consumerColumnLists.listFiles", "file_unreadable"]]) + return review(undefined, { consumerLists: load }) + }, + "reading a list file fails": async (m) => { + await using tmp = await repoWithList() + const load = await loadConsumerLists({ + configs: [cfg], + gitRoot: tmp.path, + read: async () => { + throw new Error(`fs said ${m}`) + }, + }) + expect(load.errors.map((e) => [e.method, e.category])).toEqual([["consumerColumnLists.read", "file_unreadable"]]) + return review(undefined, { consumerLists: load }) + }, + "the manifest lookup for exposures and contracts fails": async (m) => { + const spy = spyOn(manifestHelpers, "loadRawManifest").mockImplementation(() => { + throw new Error(`manifest said ${m}`) + }) + try { + const r = createDispatcherRunner({ manifestPath: path.join(path.sep, "nonexistent", "manifest.json") }) + expect(await r.modelConsumers!("fct_orders")).toBeUndefined() + return buildEnvelope({ findings: [], tier: "full", mode: "gate", engineErrors: r.failures!() }) + } finally { + spy.mockRestore() + } + }, + } + for (const [kind, run] of Object.entries(kinds)) + test(kind, async () => { + const m = marker() + const { env, log, events } = await captured(() => run(m)) + expect(env.engineErrors?.length).toBeGreaterThan(0) + expect(env.internalFailure).toBeUndefined() + expect(JSON.stringify(env)).not.toContain(m) + expect(renderSummary(env)).not.toContain(m) + expect(renderSummary(env, { maxChars: Infinity })).not.toContain(m) + expect(events).not.toContain(m) + expect(events.length).toBeGreaterThan(2) + expect(log).toContain(m) + expect(log).toMatch(/altimate review: (file_unreadable|engine_error) check=(consumerColumnLists\.\w+|modelConsumers)\b/) + }) +}) diff --git a/packages/opencode/test/altimate/review-runner.test.ts b/packages/opencode/test/altimate/review-runner.test.ts index 5e94eae3c7..564398cad8 100644 --- a/packages/opencode/test/altimate/review-runner.test.ts +++ b/packages/opencode/test/altimate/review-runner.test.ts @@ -233,3 +233,87 @@ describe("isParseFailure", () => { expect(isParseFailure(m)).toBe(false) }) }) + +describe("column lineage and consumers from the manifest", () => { + function manifest(dir: string) { + const p = path.join(dir, "manifest.json") + writeFileSync( + p, + JSON.stringify({ + metadata: { adapter_type: "duckdb" }, + nodes: { + "model.demo.fct": { + resource_type: "model", + name: "fct", + original_file_path: "models/fct.sql", + config: { materialized: "table", contract: { enforced: true } }, + depends_on: { nodes: [] }, + columns: { id: { name: "id", data_type: "integer" }, amount: { name: "amount", data_type: "double" } }, + }, + }, + sources: {}, + exposures: { + "exposure.demo.dash": { name: "dash", type: "dashboard", depends_on: { nodes: ["model.demo.fct"] } }, + "exposure.demo.other": { name: "other", type: "ml", depends_on: { nodes: ["model.demo.x"] } }, + }, + }), + ) + return p + } + + test("a partial schema that yields no lineage is retried without it", async () => { + await using tmp = await tmpdir() + const calls: unknown[] = [] + dispatcherSpy = spyOn(Dispatcher, "call").mockImplementation((async (_m: string, params: any) => { + calls.push(params.schema_context) + return { data: { column_lineage: params.schema_context ? [] : [{ source: '"stg"."id"', target: "id" }] } } + }) as any) + const runner = createDispatcherRunner({ manifestPath: manifest(tmp.path) }) + expect(await runner.columnLineage!("select id from stg", "duckdb")).toEqual([{ source: '"stg"."id"', target: "id" }]) + expect(calls).toHaveLength(2) + expect(calls[1]).toBeUndefined() + }) + + test("exposures and the enforced contract are read for a model", async () => { + await using tmp = await tmpdir() + const runner = createDispatcherRunner({ manifestPath: manifest(tmp.path) }) + expect(await runner.modelConsumers!("fct")).toEqual({ + exposures: [{ name: "dash", type: "dashboard" }], + contractEnforced: true, + contractColumns: ["id", "amount"], + }) + expect(await runner.modelConsumers!("missing")).toBeUndefined() + }) +}) + +describe("validation against a partial schema", () => { + // The engine's real shape: the error type is under `kind`. + const notFound = { data: { validation: { errors: [{ code: "E001", message: "Table 'stg' not found", kind: { type: "TableNotFound", table: "stg" } }] } } } + + test("manifest-only schema: an undocumented table is not reported as missing", async () => { + await using tmp = await tmpdir() + const manifestPath = path.join(tmp.path, "manifest.json") + writeFileSync( + manifestPath, + JSON.stringify({ + nodes: { + "model.d.fct": { resource_type: "model", name: "fct", depends_on: { nodes: [] }, columns: { id: { name: "id", data_type: "int" } } }, + }, + sources: {}, + }), + ) + dispatcherSpy = spyOn(Dispatcher, "call").mockImplementation((async () => notFound) as any) + const runner = createDispatcherRunner({ manifestPath }) + expect((await runner.check("select id from stg", "duckdb")).issues?.some((i) => i.rule === "validate")).toBe(false) + }) + + test("catalog schema: a missing table is still reported", async () => { + await using tmp = await tmpdir() + dispatcherSpy = spyOn(Dispatcher, "call").mockImplementation((async () => notFound) as any) + const runner = createDispatcherRunner({ + manifestPath: path.join(tmp.path, "none.json"), + schemaContext: { tables: { fct: { columns: [{ name: "id", type: "int" }] } }, version: "1" }, + }) + expect((await runner.check("select id from stg", "duckdb")).issues?.some((i) => i.rule === "validate")).toBe(true) + }) +}) From d69d90262bee6a4b0baf23e847d60188ff776d41 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 3 Dec 2026 23:24:19 +0530 Subject: [PATCH 03/39] fix(review): a base PII pass that abstained no longer hides a column the raw base lacks Only a base whose lineage resolves no column leaves PII undecided for every column. When the base's PII pass abstained, the raw base decides: a column it mentions is undecided (a warning that never blocks), and a column it never mentions is new, so it stays critical on a marts/reporting model. Co-Authored-By: Claude Fable 5.2 --- .../src/altimate/review/orchestrate.ts | 13 ++-- .../altimate/review-failures-gate.test.ts | 62 +++++++++++++++++++ 2 files changed, 70 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 4d9e1ef5e1..10e5b0d51f 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1355,16 +1355,19 @@ async function piiClassifyLane( // 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 that could not be analysed leaves every column undecided, as in the - // fallback path: a warning that never blocks, whatever the raw base shows. - const baseUnanalysed = baseAbstained || baseUnresolved + // 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 undecided = baseUnanalysed || (baseUnknown && !baseLacks(col)) + 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( @@ -1376,7 +1379,7 @@ async function piiClassifyLane( `This change surfaces a **${p.classification}**-classified column \`${p.column}\` ` + `(confidence ${(p.confidence * 100).toFixed(0)}%). Confirm masking / access policy before merging to a non-restricted schema` + (p.masking ? `; suggested masking: \`${p.masking}\`.` : ".") + - (baseUnanalysed ? PII_UNDECIDED_BASE_UNANALYSED : ""), + (unanalysed ? PII_UNDECIDED_BASE_UNANALYSED : ""), file: file.path, model, // Without a base, exposure is undecided: `unknown` keeps these warnings diff --git a/packages/opencode/test/altimate/review-failures-gate.test.ts b/packages/opencode/test/altimate/review-failures-gate.test.ts index 85bd0cf766..f839539590 100644 --- a/packages/opencode/test/altimate/review-failures-gate.test.ts +++ b/packages/opencode/test/altimate/review-failures-gate.test.ts @@ -844,6 +844,68 @@ describe("PII abstention", () => { expect(env.verdict).not.toBe("REQUEST_CHANGES") }) + test("a column the raw base never mentions stays critical, even if the base's PII pass abstained", async () => { + const base = "select id, array_agg(tag ignore nulls) as tags from t group by id" + const head = "select id, ssn from t" + const env = await runReview({ + changedFiles: [{ path: "models/marts/a.sql", status: "modified" as const, diff: `-${base}\n+${head}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["pii_exposure"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: runner({ + async detectPii(sql: string) { + return sql === base ? { columns: [], abstained: true } : { columns: ["ssn"] } + }, + async columnLineage(sql: string) { + return sql === base + ? [{ source: "t.id", target: "id" }] + : [ + { source: "t.id", target: "id" }, + { source: "t.ssn", target: "ssn" }, + ] + }, + async classifyPii(columns: string[]) { + return columns.filter((c) => c === "ssn").map((column) => ({ column, classification: "SSN", confidence: 0.99 })) + }, + }), + getContent: async (_f, side) => (side === "new" ? head : base), + }) + const precise = env.findings.find((f) => f.category === "pii_exposure" && f.evidence?.tool === "altimate_core.classify_pii") + expect(precise).toMatchObject({ severity: "critical", confidence: "high" }) + expect(precise?.body).not.toContain("could not be analysed") + expect(env.verdict).toBe("REQUEST_CHANGES") + }) + + test("a base with partial lineage and an abstained PII pass leaves a column the raw base has undecided", async () => { + // Lineage resolves only `id` in the base; `email` already existed there. + const base = "select id, any_value(email) as email, array_agg(tag ignore nulls) as tags from customers group by id" + const head = "select id, email, tags from customers_dedup" + const env = await runReview({ + changedFiles: [{ path: "models/marts/dim_customers.sql", status: "modified" as const, diff: `-${base}\n+${head}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["pii_exposure"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: runner({ + async detectPii(sql: string) { + return sql === base ? { columns: [], abstained: true } : { columns: ["email"] } + }, + async columnLineage(sql: string) { + return sql === base + ? [{ source: "customers.id", target: "id" }] + : ["id", "email", "tags"].map((c) => ({ source: `customers_dedup.${c}`, target: c })) + }, + async classifyPii(columns: string[]) { + return columns.filter((c) => c === "email").map((column) => ({ column, classification: "Email", confidence: 0.99 })) + }, + }), + getContent: async (_f, side) => (side === "new" ? head : base), + }) + const pii = env.findings.filter((f) => f.category === "pii_exposure") + expect(pii.filter((f) => f.severity === "critical")).toEqual([]) + expect(pii.find((f) => f.evidence?.tool === "altimate_core.classify_pii")).toMatchObject({ severity: "warning", confidence: "unknown" }) + expect(env.verdict).toBe("COMMENT") + }) + test("a PII check that could not analyse the model is reported, not treated as clean", async () => { const env = await runReview({ changedFiles: [two[0]], From a3159a46e5227eaf29db06ddd99d7bfd4ec75be3 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 3 Dec 2026 23:33:14 +0530 Subject: [PATCH 04/39] fix(review): consumer and contract checks: base failures, package nodes, list identity - base list read failures hold back approval - manifest nodes: by path, then name; ties abstain - version include/exclude, `defined_in` - named groups, `./` and directory globs; empty lists only when named as lists - stable list ids; unnamed lists by their own lines - integer casts keep a count ratio integral - unit tests keyed by model and name Co-Authored-By: Claude Fable 5.2 --- docs/docs/usage/dbt-pr-review.md | 7 +- .../src/altimate/review/consumer-lists.ts | 78 +++-- .../src/altimate/review/orchestrate.ts | 88 ++++-- .../src/altimate/review/rule-catalog.ts | 10 +- packages/opencode/src/altimate/review/run.ts | 3 + .../opencode/src/altimate/review/runner.ts | 41 ++- .../src/altimate/review/unit-tests.ts | 17 +- .../altimate/review-contracts-dialect.test.ts | 287 +++++++++++++++++- .../test/altimate/review-runner.test.ts | 1 + 9 files changed, 467 insertions(+), 65 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 91071cbc63..31c373157b 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -365,8 +365,8 @@ manifest, the review reports: ```yaml consumerColumnLists: - - files: "exports/**/*.py" # repo-relative glob - pattern: "COLUMNS\\s*=\\s*\\[([^\\]]*)\\]" # first capture group = the list + - files: "exports/**/*.py" # repo-relative glob, a file or a directory + pattern: "COLUMNS\\s*=\\s*\\[([^\\]]*)\\]" # first capture group (plain or named) = the list model: fct_orders # omit: the list's own line must name the model ``` @@ -390,7 +390,8 @@ system message is only in the job log. A pattern that is not a valid regex, or has no capture group, is listed by its entry number (`entry 2: the pattern is not a valid regular expression`), never quoted; it and a list the base branch had that the PR's head no longer yields are listed without holding back -approval. +approval. An entry whose `files` glob matches no file is listed as not fully +verified on every run until the entry is fixed or removed. ### What the PR comment shows diff --git a/packages/opencode/src/altimate/review/consumer-lists.ts b/packages/opencode/src/altimate/review/consumer-lists.ts index e0dd8569a7..07f33c60d0 100644 --- a/packages/opencode/src/altimate/review/consumer-lists.ts +++ b/packages/opencode/src/altimate/review/consumer-lists.ts @@ -1,4 +1,6 @@ import { execFile } from "node:child_process" +import { existsSync } from "node:fs" +import path from "node:path" import { promisify } from "node:util" import { reportFailure } from "./failure" import type { FailureCategory } from "./verdict" @@ -49,8 +51,11 @@ const ASSIGNED = /([A-Za-z_][A-Za-z0-9_.$-]*)["']?\s*(?::=|=|:)\s*$/ export function findColumnLists( content: string, pattern: RegExp, + /** The config entry names the model: an empty list there is a list. */ + opts: { model?: string } = {}, ): Array<{ columns: string[]; line: number; name?: string; context: string; own: string }> { - const flags = pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g" + // `d` gives the capture's own offsets: an empty capture cannot be found by text. + const flags = [...new Set(pattern.flags + "gd")].join("") const re = new RegExp(pattern.source, flags) const lines = content.split("\n") const out: Array<{ columns: string[]; line: number; name?: string; context: string; own: string }> = [] @@ -60,19 +65,27 @@ export function findColumnLists( const name = token.replace(/^["'`]+|["'`]+$/g, "") if (IDENT.test(name)) cols.add(name.toLowerCase()) } - if (!cols.size) continue + // A capture that holds something other than column names is skipped. + if (!cols.size && (m[1] === undefined || m[1].replace(/[\s,]/g, "") !== "")) continue const start = m.index ?? 0 + // A match that ends with a line break (a YAML list form) ends on the line + // before it: the next line is not the list's own. + const matched = m[0].replace(/\r?\n+$/, "") const first = content.slice(0, start).split("\n").length - const last = first + m[0].split("\n").length - 1 + const last = first + matched.split("\n").length - 1 // The text before the capture group: `NAME = [` (the pattern's own prefix, or the line's). - const lead = content.slice(content.lastIndexOf("\n", start - 1) + 1, start) + m[0].slice(0, m[0].indexOf(m[1] ?? "")) + const group = m.indices?.[1]?.[0] ?? start + m[0].indexOf(m[1] ?? "") + const lead = content.slice(content.lastIndexOf("\n", start - 1) + 1, group) const name = ASSIGNED.exec(lead.replace(/[\s\[({]+$/, ""))?.[1] + // An empty list (`[]`) is a column list only when the entry names its model + // or its identifier says so (`ORDERS_COLUMNS = []`); a broad pattern also + // matches empty arrays that hold no columns (`orders = []`). + if (!cols.size && !opts.model && !(name && LIST_SUFFIXES.has(words(name).at(-1) ?? ""))) continue const context = lines.slice(Math.max(0, first - 2), last + 1).join("\n") - const group = start + m[0].indexOf(m[1] ?? "") const lineStart = content.lastIndexOf("\n", start - 1) + 1 - const lineEndAt = content.indexOf("\n", start + m[0].length) + const lineEndAt = content.indexOf("\n", start + matched.length) const lineEnd = lineEndAt < 0 ? content.length : lineEndAt - const own = content.slice(lineStart, group) + content.slice(group + (m[1] ?? "").length, lineEnd) + const own = content.slice(lineStart, group) + content.slice(Math.min(group + (m[1] ?? "").length, lineEnd), lineEnd) out.push({ columns: [...cols], line: first, name, context, own }) } return out @@ -83,11 +96,6 @@ export function extractColumnLists(content: string, pattern: RegExp): string[][] return findColumnLists(content, pattern).map((l) => l.columns) } -/** Column names from every match of `pattern` in `content` (lowercased, de-duplicated). */ -export function extractColumnList(content: string, pattern: RegExp): string[] { - return [...new Set(extractColumnLists(content, pattern).flat())] -} - /** Lowercased words of an identifier, split at `_` and at case changes * (`FctOrdersCols` → fct, orders, cols). */ const words = (text: string) => @@ -144,6 +152,16 @@ export function listLabel(list: ConsumerColumnList, sameFile: ConsumerColumnList return repeated && list.line ? `${list.name} (line ${list.line})` : list.name } +/** A stable id for a list within its file, for a finding's fingerprint: its + * identifier, with its position among same-named lists in the file when the + * identifier repeats or is missing. No line number, so an edit above it does + * not change the id. */ +export function listKey(list: ConsumerColumnList, sameFile: ConsumerColumnList[] = []): string { + const peers = sameFile.filter((l) => l.path === list.path && l.name === list.name) + const at = peers.indexOf(list) + return peers.length > 1 || !list.name ? `${list.name ?? ""}#${at < 0 ? 0 : at}` : list.name +} + /** * Lists the base had that the head no longer yields (the file removed, or * edited so the pattern stops matching): a PR could otherwise switch a list @@ -162,9 +180,13 @@ export function droppedLists(base: ConsumerColumnList[], head: ConsumerColumnLis left.splice(i, 1) return true } + // An unnamed list (`load("orders", [...])`) is known by the text of its own + // lines around the list, never by its file alone. + const same = (l: ConsumerColumnList, h: ConsumerColumnList) => + h.path === l.path && (l.name ? h.name === l.name : !h.name && h.own !== undefined && h.own === l.own) const passes: Array<(l: ConsumerColumnList) => (h: ConsumerColumnList) => boolean> = [ - (l) => (h) => h.path === l.path && h.name === l.name && key(h) === key(l), - (l) => (h) => h.path === l.path && h.name === l.name, + (l) => (h) => same(l, h) && key(h) === key(l), + (l) => (h) => same(l, h), (l) => (h) => h.path === l.path && key(h) === key(l), (l) => (h) => key(h) === key(l), ] @@ -193,6 +215,15 @@ export interface ConsumerListLoad { dropped?: Array<{ path: string; reason: string }> } +/** A configured glob as git's pathspec read it: a leading `./` is dropped, and + * a value with no glob characters names a file or a directory. */ +function globMatcher(files: string): (path: string) => boolean { + const spec = files.replace(/^(?:\.\/)+/, "").replace(/\/+$/, "") + if (!/[*?[\]{}]/.test(spec)) return (p) => p === spec || p.startsWith(`${spec}/`) + const glob = new Bun.Glob(spec) + return (p) => glob.match(p) +} + /** Regular files at `head` (or in the index): a submodule (gitlink, mode * 160000) is not a file of this repository and cannot be read as one. */ async function listBlobs(gitRoot: string, head?: string): Promise { @@ -230,8 +261,10 @@ export async function loadConsumerLists(opts: { /** Log the error with its facts; keep a fixed reason (the first per method). */ const fail = (method: string, reason: string, err: unknown, path?: string) => { reportFailure("file_unreadable", { check: method, side, ...(path ? { path } : {}) }, err) - const prev = failures.get(method) - failures.set(method, { reason: prev?.reason ?? reason, count: (prev?.count ?? 0) + 1 }) + // The base's failures are their own entries: both sides hold back approval. + const key = side === "base" ? method.replace("consumerColumnLists.", "consumerColumnLists.base.") : method + const prev = failures.get(key) + failures.set(key, { reason: prev?.reason ?? (side === "base" ? `${reason} (base)` : reason), count: (prev?.count ?? 0) + 1 }) } // Every entry lists the same files: run git once. `git ls-tree` rejects // `:(glob)` pathspec magic, so the glob is matched here, the same way for the @@ -248,18 +281,20 @@ export async function loadConsumerLists(opts: { invalid.push(`${entry}: the pattern is not a valid regular expression`) continue } - if (!/\((?!\?)/.test(cfg.pattern.replace(/\\./g, ""))) { + // A plain or named group captures; `(?:`, `(?=`, `(?!`, `(?<=`, `(? glob.match(f)) + files = (await listFiles()).filter(matches) } catch (e) { fail("consumerColumnLists.listFiles", "the repository's files could not be listed, so no list was checked; see the job log", e) continue } + if (!files.length) invalid.push(`${entry}: the files pattern matches no file`) for (const file of files) { let content: string | undefined let readError: unknown @@ -268,11 +303,14 @@ export async function loadConsumerLists(opts: { } catch (e) { readError = e } + // The working tree is listed from the index: a tracked file deleted on + // disk is not at the head, not unreadable. + if (content === undefined && !opts.head && readError === undefined && !existsSync(path.join(opts.gitRoot, file))) continue if (content === undefined) { fail("consumerColumnLists.read", `could not read ${file}`, readError, file) continue } - for (const l of findColumnLists(content, re)) lists.push({ path: file, model: cfg.model, content, ...l }) + for (const l of findColumnLists(content, re, { model: cfg.model })) lists.push({ path: file, model: cfg.model, content, ...l }) } } const errors = [...failures].map(([method, f]) => ({ method, ...f, category: "file_unreadable" as const })) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 10e5b0d51f..03c59ac62a 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -48,7 +48,7 @@ import { selectItems, selectSources, } from "./rule-catalog" -import { listLabel, listMirrorsModel, type ConsumerColumnList, type ConsumerListLoad } from "./consumer-lists" +import { listKey, listLabel, listMirrorsModel, type ConsumerColumnList, type ConsumerListLoad } from "./consumer-lists" import { detectUnitTestFixtures } from "./unit-tests" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult } from "./ai-review" import { hasInternalFailure, reportFailure } from "./failure" @@ -186,7 +186,17 @@ export interface ReviewRunner { /** 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[] } | undefined + | { + 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 > /** Column-lineage edges for a query: source `"table"."col"` → target output column. */ columnLineage?(sql: string, dialect: string): Promise> @@ -674,7 +684,6 @@ async function columnBreakageLane( ] } -/** A query's output columns from column lineage (lowercased); empty when unknown or `*`. */ /** * The model's output column names, read from its final projection (the * select-list parser), with a `*` over CTEs or subqueries whose columns are @@ -692,7 +701,7 @@ function outputColumns(sql: string): Set | undefined { /** 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. */ -function columnDelta(ctx: ModelContext): { added: string[]; removed: string[]; unknown: boolean } { +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 } = ctx @@ -700,7 +709,9 @@ function columnDelta(ctx: ModelContext): { added: string[]; removed: string[]; u const current = outputColumns(engineNewSql) if (!current) return unknown if (!hasOldSide(file)) return { added: [...current], removed: [], unknown: false } - if (!engineOldSql) return unknown + // No base SQL for the engine (not compiled, or unreadable): that gap is + // already recorded for the file, under its own reason. + if (!engineOldSql) return { ...unknown, baseMissing: true } const before = outputColumns(engineOldSql) if (!before) return unknown return { @@ -742,9 +753,24 @@ export function ymlModelColumns(texts: string[], model: string): Set { for (const v of versions) names(v?.columns) continue } - const v = versions.find((v) => `${name}_v${String(v?.v ?? "").toLowerCase()}` === target) + const v = versions.find( + (v) => `${name}_v${String(v?.v ?? "").toLowerCase()}` === target || String(v?.defined_in ?? "").toLowerCase() === target, + ) if (v) { - names(m.columns) + // 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) } } @@ -767,10 +793,14 @@ async function consumerContractLane( 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 || (!consumers.exposures.length && !consumers.contractEnforced)) return [] - const { added, removed, unknown } = columnDelta(ctx) + const { added, removed, unknown, baseMissing } = columnDelta(ctx) if (unknown) { - 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") + if (!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[] = [] @@ -804,7 +834,10 @@ async function consumerContractLane( 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. - const inChangedYml = ymlModelColumns(await opts.changedYmlText(), model) + // Matched by the manifest node's own name and version: a version with + // `defined_in` lives in a file named otherwise. + const key = consumers.name ? (consumers.version ? `${consumers.name}_v${consumers.version}` : consumers.name) : model + const inChangedYml = ymlModelColumns(await opts.changedYmlText(), key) const missing = added.filter((c) => !declared.has(c) && !inChangedYml.has(c)) if (missing.length) out.push( @@ -835,20 +868,31 @@ async function consumerContractLane( function consumerListLane(ctx: ModelContext, lists: ConsumerColumnList[], abstain: (reason: string) => void): Finding[] { if (!lists.length || !hasOldSide(ctx.file)) return [] const model = modelNameFromPath(ctx.file.path) - const mirrors = lists.filter((l) => listMirrorsModel(l, model, lists) === true) - const undecided = lists.filter((l) => listMirrorsModel(l, model, lists) === undefined) + // 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 } = columnDelta(ctx) + const { added, removed, unknown, baseMissing } = columnDelta(ctx) if (unknown) { - 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") + 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) + for (const list of undecided) { + const label = listLabel(list, byPath.get(list.path)) abstain( - `consumerColumnLists: ${list.path}${listLabel(list, lists) ? ` (${listLabel(list, lists)})` : ""} names this model ` + + `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) @@ -858,7 +902,8 @@ function consumerListLane(ctx: ModelContext, lists: ConsumerColumnList[], abstai 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 label = listLabel(list, lists) + 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)}` @@ -874,7 +919,8 @@ function consumerListLane(ctx: ModelContext, lists: ConsumerColumnList[], abstai model, confidence: "high", evidence: { tool: "consumer-column-list", result: { list: list.path, name: list.name, line: list.line, missing, stale } }, - ruleKey: `lineage_breakage:consumer-list:${list.path}${label ? `:${label}` : ""}`, + // No line number: the fingerprint must survive an edit above the list. + ruleKey: `lineage_breakage:consumer-list:${list.path}:${listKey(list, sameFile)}`, }), ) } @@ -2274,7 +2320,11 @@ export async function runReview(input: OrchestrateInput): Promise showAtRef(gitRoot, resolved.sha, p), side: "base", }) + // A failed base read holds back approval like a head one: the comparison + // that would show a list this PR removes did not run. + consumerLists.errors.push(...atBase.errors) consumerLists.dropped = atBase.errors.length ? [{ path: ".altimate/review.yml", reason: "consumerColumnLists: the base's lists could not be read, so a list this PR removes would go unnoticed" }] : droppedLists(atBase.lists, consumerLists.lists) diff --git a/packages/opencode/src/altimate/review/runner.ts b/packages/opencode/src/altimate/review/runner.ts index 901b68becf..b56d14dd65 100644 --- a/packages/opencode/src/altimate/review/runner.ts +++ b/packages/opencode/src/altimate/review/runner.ts @@ -508,18 +508,34 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun const raw = loadRawManifest(opts.manifestPath) if (!raw) return undefined const nodes = Object.entries(raw.nodes ?? {}).filter(([id]) => id.startsWith("model.")) - // By file first: a versioned model (`fct_orders_v2.sql`) is named - // `fct_orders` with `version: 2`. Manifest paths are project-relative, - // the changed file repository-relative. - const byPath = (n: any) => { - const p = typeof n?.original_file_path === "string" ? n.original_file_path.replace(/\\/g, "/") : "" - return !!file && !!p && (file === p || file.endsWith(`/${p}`)) + // By file first, across every package: a versioned model + // (`fct_orders_v2.sql`) is named `fct_orders` with `version: 2`, and a + // file under a local package is that package's model, whatever the + // root project names. Manifest paths are project-relative, the changed + // file repository-relative: an exact path wins over a suffix, and the + // root project's model breaks a tie. Then by name, root project first. + const project = typeof raw.metadata?.project_name === "string" ? raw.metadata.project_name : undefined + const isRoot = (n: any) => !!project && n?.package_name === project + const pathOf = (n: any) => (typeof n?.original_file_path === "string" ? n.original_file_path.replace(/\\/g, "/") : "") + const narrow = (pool: Array<[string, any]>) => { + if (pool.length < 2) return pool + const root = pool.filter(([, n]) => isRoot(n)) + return root.length ? root : pool } - const hit = - nodes.find(([, n]) => byPath(n)) ?? - nodes.find(([, n]) => n?.name === model) ?? - nodes.find(([, n]) => n?.version != null && `${n.name}_v${n.version}` === model) - if (!hit) return undefined + let candidates: Array<[string, any]> = [] + if (file) { + const exact = nodes.filter(([, n]) => pathOf(n) === file) + const suffix = nodes.filter(([, n]) => !!pathOf(n) && file.endsWith(`/${pathOf(n)}`)) + candidates = narrow(exact.length ? exact : suffix) + } + for (const test of [(n: any) => n?.name === model, (n: any) => n?.version != null && `${n.name}_v${n.version}` === model]) { + if (candidates.length) break + candidates = narrow(nodes.filter(([, n]) => test(n))) + } + if (!candidates.length) return undefined + // Several nodes fit equally: which one the file is cannot be told. + if (candidates.length > 1) return { exposures: [], contractEnforced: false, contractColumns: [], ambiguous: true } + const hit = candidates[0] const [uid, node] = hit const exposures = Object.values(raw.exposures ?? {}) .filter((e) => Array.isArray(e?.depends_on?.nodes) && e.depends_on.nodes.includes(uid)) @@ -528,7 +544,8 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun const contractColumns = contractEnforced ? Object.values(node.columns ?? {}).map((c) => String(c?.name ?? "").toLowerCase()).filter(Boolean) : [] - return { exposures, contractEnforced, contractColumns } + const version = node.version != null ? String(node.version) : undefined + return { exposures, contractEnforced, contractColumns, name: String(node.name ?? model), ...(version ? { version } : {}) } } catch (err) { fail("modelConsumers", err) return undefined diff --git a/packages/opencode/src/altimate/review/unit-tests.ts b/packages/opencode/src/altimate/review/unit-tests.ts index 8c928ea0f9..1c303ad428 100644 --- a/packages/opencode/src/altimate/review/unit-tests.ts +++ b/packages/opencode/src/altimate/review/unit-tests.ts @@ -18,7 +18,8 @@ const inlineCode = (x: string) => codeSpan(x.replace(/\s+/g, " ")) interface UnitTest { name?: string - model?: string + /** Any YAML value: read as text. */ + model?: unknown given?: Array<{ input?: string; rows?: unknown; format?: string }> expect?: { rows?: unknown; format?: string } } @@ -28,7 +29,9 @@ function unitTestsOf(doc: unknown): Map { const list = (doc as { unit_tests?: unknown })?.unit_tests if (!Array.isArray(list)) return out for (const t of list) { - if (t && typeof t === "object" && typeof (t as UnitTest).name === "string") out.set((t as UnitTest).name!, t as UnitTest) + // dbt identifies a unit test by its model and its name. + if (t && typeof t === "object" && typeof (t as UnitTest).name === "string") + out.set(`${String((t as UnitTest).model ?? "")}\u0000${(t as UnitTest).name}`, t as UnitTest) } return out } @@ -47,14 +50,16 @@ export function detectUnitTestFixtures(file: ChangedFile, oldContent?: string, n } const before = unitTestsOf(oldDoc) const out: Finding[] = [] - for (const [name, test] of unitTestsOf(newDoc)) { - const prev = before.get(name) + for (const [key, test] of unitTestsOf(newDoc)) { + const name = test.name! + const prev = before.get(key) if (prev && JSON.stringify(prev) === JSON.stringify(test)) continue const given = Array.isArray(test.given) ? test.given : [] const allInputsEmpty = given.length > 0 && given.every((g) => isDict(g?.format) && Array.isArray(g?.rows) && g.rows.length === 0) const expectRows = test.expect?.rows if (!allInputsEmpty || !isDict(test.expect?.format) || !Array.isArray(expectRows)) continue - const model = test.model ?? "" + // YAML may give a number or a boolean: names are text. + const model = test.model == null ? "" : String(test.model) const passesAnyway = expectRows.length === 0 out.push( makeFinding({ @@ -74,7 +79,7 @@ export function detectUnitTestFixtures(file: ChangedFile, oldContent?: string, n model: model || undefined, confidence: "high", evidence: { tool: "unit-test-fixtures", result: { rule: passesAnyway ? "unit_test_no_input_rows" : "unit_test_empty_inputs", test: name } }, - ruleKey: `test_coverage:unit-test-empty-inputs:${name}`, + ruleKey: `test_coverage:unit-test-empty-inputs:${model}:${name}`, }), ) } diff --git a/packages/opencode/test/altimate/review-contracts-dialect.test.ts b/packages/opencode/test/altimate/review-contracts-dialect.test.ts index 120d44fe8f..84bb5dfc69 100644 --- a/packages/opencode/test/altimate/review-contracts-dialect.test.ts +++ b/packages/opencode/test/altimate/review-contracts-dialect.test.ts @@ -9,7 +9,6 @@ import { isCatalogPortability, runReview, ymlModelColumns, type ReviewRunner } f import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" import { - extractColumnList, extractColumnLists, listMirrorsModel, loadConsumerLists, @@ -27,6 +26,7 @@ import { capabilityFor } from "../../src/altimate/review/adapter-capabilities" import { createDispatcherRunner } from "../../src/altimate/review/runner" import { detectDialect, reviewPullRequest } from "../../src/altimate/review/run" import { Dispatcher } from "../../src/altimate/native" +import * as git from "../../src/altimate/review/git" import * as manifestHelpers from "../../src/altimate/native/dbt/helpers" import { buildEnvelope } from "../../src/altimate/review/verdict" import { emitReviewRun } from "../../src/altimate/review/telemetry" @@ -68,6 +68,17 @@ describe("integer division follows the adapter", () => { expect(run("select 7 / 2 as r")[0].body).toContain("returns 3") }) + test("an integer cast on either side of a count ratio still truncates; a numeric cast does not", () => { + for (const line of [ + "select count(*) / count(x)::bigint as r", + "select count(*) / count(x) :: integer as r", + "select count(*)::int / count(x) as r", + ]) + expect({ line, n: run(line).length }).toEqual({ line, n: 1 }) + for (const line of ["select count(*) / count(x)::numeric as r", "select count(*) / count(x)::decimal(10, 2) as r"]) + expect({ line, n: run(line).length }).toEqual({ line, n: 0 }) + }) + test("shapes: count ratio and underscore literals match; casts and decimals don't", () => { expect(run("select 1_000 / 3 as r")).toHaveLength(1) expect(run("select count(*) / nullif(count(x), 0) as r")).toHaveLength(1) @@ -208,6 +219,37 @@ describe("consumers outside the DAG", () => { expect(other.findings.find((x) => x.title.includes("missing from the enforced contract"))?.body).toContain("`region`") }) + test("a version's include/exclude applies to the model's columns, and `defined_in` names the version's file", () => { + const yml = + "models:\n - name: fct\n columns:\n - name: id\n - name: region\n versions:\n" + + " - v: 2\n columns:\n - include: all\n exclude: [region]\n - name: tier\n" + + " - v: 3\n defined_in: fct_current\n" + expect([...ymlModelColumns([yml], "fct_v2")].sort()).toEqual(["id", "tier"]) + expect([...ymlModelColumns([yml], "fct_current")].sort()).toEqual(["id", "region"]) + const only = "models:\n - name: fct\n columns:\n - name: id\n - name: region\n versions:\n - v: 2\n columns:\n - include: [id]\n" + expect([...ymlModelColumns([only], "fct_v2")]).toEqual(["id"]) + }) + + test("the contract check matches a changed yml by the manifest node's name and version, not the file name", async () => { + const consumers = { exposures: [], contractEnforced: true, contractColumns: ["id", "email", "amount"], name: "fct", version: "3" } + const added = "select id, email, amount, region from src" + const env = await review(consumers, { + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["lineage_breakage", "contract_violation"], checkContractColumns: true }, + changedFiles: [ + { path: "models/marts/fct_current.sql", status: "modified", diff: "-x\n+y\n" }, + { path: "models/marts/_fct.yml", status: "modified", diff: "+ - name: region\n" }, + ], + getContent: async (f, side) => + f.endsWith(".yml") + ? "models:\n - name: fct\n versions:\n - v: 3\n defined_in: fct_current\n columns:\n - include: all\n - name: region\n" + : side === "old" + ? OLD + : added, + getCompiled: async (_f, side) => (side === "old" ? OLD : added), + }) + expect(env.findings.some((x) => x.title.includes("missing from the enforced contract"))).toBe(false) + }) + test("ymlModelColumns reads the model's own entry, including versions", () => { const yml = "models:\n - name: fct\n columns:\n - name: id\n versions:\n - v: 2\n columns:\n - name: region\n" + @@ -436,6 +478,79 @@ select * from final` expect(env.findings.find((x) => x.title.includes("declared consumers"))?.body).toContain("removes `amount`") }) + test("a dependency package's model with the same file path is not picked; two equal candidates abstain", async () => { + await using tmp = await tmpdir() + const manifestPath = path.join(tmp.path, "manifest.json") + const node = (pkg: string) => ({ + resource_type: "model", name: "fct", package_name: pkg, original_file_path: "models/fct.sql", depends_on: { nodes: [] }, config: {}, columns: {}, + }) + const write = (metadata: Record) => + fs.writeFile( + manifestPath, + JSON.stringify({ + metadata, + nodes: { "model.vendor_pkg.fct": node("vendor_pkg"), "model.shop.fct": node("shop") }, + sources: {}, + exposures: { "exposure.shop.rev": { name: "revenue_dashboard", type: "dashboard", depends_on: { nodes: ["model.shop.fct"] } } }, + }), + ) + await write({ adapter_type: "duckdb", project_name: "shop" }) + const consumers = await createDispatcherRunner({ manifestPath }).modelConsumers!("fct", "dbt/models/fct.sql") + expect(consumers?.exposures.map((e) => e.name)).toEqual(["revenue_dashboard"]) + expect(consumers?.ambiguous).toBeUndefined() + // Without the project's name both nodes fit: none is picked. + await write({ adapter_type: "duckdb" }) + const real = createDispatcherRunner({ manifestPath }) + expect((await real.modelConsumers!("fct", "dbt/models/fct.sql"))?.ambiguous).toBe(true) + const env = await review(undefined, { runner: { ...fakeRunner(), modelConsumers: real.modelConsumers } }) + expect(env.findings.some((x) => x.title.includes("declared consumers"))).toBe(false) + expect(env.scope?.unverified).toContainEqual({ + path: "models/marts/fct.sql", + reason: "several models in the manifest match this file, so its declared consumers were not checked", + kind: "abstained", + }) + }) + + test("a base without engine SQL is not blamed on the parser: no extra abstention", async () => { + const env = await review(exposed, { getCompiled: async (_f, side) => (side === "old" ? undefined : NEW), getContent: async (_f, side) => (side === "old" ? "select {{ x }} from src" : NEW) }) + expect(env.scope?.unverified?.filter((u) => u.reason.includes("could not be listed")) ?? []).toEqual([]) + expect(env.scope?.unverified).toContainEqual(expect.objectContaining({ kind: "not_compiled", side: "base" })) + }) + + test("a qualified `*` over one side of a `using` join is that side's columns", () => { + expect(finalOutputs("with a as (select id, amount from t), b as (select id, name from u) select a.* from a join b using (id)").columns).toEqual(["id", "amount"]) + expect(finalOutputs("with a as (select id, amount from t), b as (select id, name from u) select * from a join b using (id)").columns).toBeUndefined() + }) + + test("a file is matched by path across packages first: a local package's file is its model; an exact path beats a suffix", async () => { + await using tmp = await tmpdir() + const manifestPath = path.join(tmp.path, "manifest.json") + const node = (pkg: string, name: string, p: string) => ({ resource_type: "model", name, package_name: pkg, original_file_path: p, depends_on: { nodes: [] }, config: {}, columns: {} }) + const exposure = (uid: string) => ({ "exposure.root.d": { name: "dash", type: "dashboard", depends_on: { nodes: [uid] } } }) + await fs.writeFile( + manifestPath, + JSON.stringify({ + metadata: { project_name: "root" }, + nodes: { "model.root.stg_x": node("root", "stg_x", "models/stg_x.sql"), "model.local.stg_x": node("local", "stg_x", "models/staging/stg_x.sql") }, + exposures: exposure("model.local.stg_x"), + }), + ) + const local = await createDispatcherRunner({ manifestPath }).modelConsumers!("stg_x", "packages/local/models/staging/stg_x.sql") + expect(local?.exposures.map((e) => e.name)).toEqual(["dash"]) + await fs.writeFile( + manifestPath, + JSON.stringify({ + metadata: { project_name: "root" }, + nodes: { "model.root.a": node("root", "orders", "models/orders.sql"), "model.root.b": node("root", "orders_x", "x/models/orders.sql") }, + exposures: exposure("model.root.b"), + }), + ) + const exact = await createDispatcherRunner({ manifestPath }).modelConsumers!("orders", "x/models/orders.sql") + expect(exact?.ambiguous).toBeUndefined() + expect(exact?.name).toBe("orders_x") + expect(exact?.exposures.map((e) => e.name)).toEqual(["dash"]) + }) + test("a star select is never guessed at", async () => { const env = await review( { exposures: [{ name: "d" }], contractEnforced: false, contractColumns: [] }, @@ -448,7 +563,7 @@ select * from final` describe("opt-in consumer column lists", () => { test("lists are extracted from the capture group; models matched by name", () => { const py = 'MART_COLUMNS = [\n "id",\n "amount",\n \'email\',\n]\nTABLE = "fct"\n' - expect(extractColumnList(py, /MART_COLUMNS\s*=\s*\[([^\]]*)\]/)).toEqual(["id", "amount", "email"]) + expect(extractColumnLists(py, /MART_COLUMNS\s*=\s*\[([^\]]*)\]/)).toEqual([["id", "amount", "email"]]) const [found] = findColumnLists(py, /MART_COLUMNS\s*=\s*\[([^\]]*)\]/) const list = { path: "loaders/fct.py", content: py, ...found } // `TABLE = "fct"` is a neighbouring line, not the match's own: undecided. @@ -459,6 +574,79 @@ describe("opt-in consumer column lists", () => { expect(listMirrorsModel({ path: "loaders/fct.py", columns: ["id"], content: py }, "fct")).toBeUndefined() }) + test("a named capture group is a capture; an empty list is kept, a capture that is not a list is not", async () => { + expect(findColumnLists('COLUMNS = ["id", "amount"]', /COLUMNS = \[(?[^\]]*)\]/).map((l) => l.columns)).toEqual([["id", "amount"]]) + await using noRepo = await tmpdir() + const load = await loadConsumerLists({ + configs: [ + { files: "x/**", pattern: "COLUMNS = \\[(?[^\\]]*)\\]" }, + { files: "x/**", pattern: "(?<=COLUMNS = )\\[.*\\]" }, + ], + gitRoot: noRepo.path, + read: async () => "", + }) + expect(load.invalid).toEqual(["entry 2: the pattern has no capture group, so it selects no list"]) + expect(findColumnLists("COLUMNS = []\n", /COLUMNS = \[([^\]]*)\]/).map((l) => l.columns)).toEqual([[]]) + expect(findColumnLists("COLUMNS = [1, 2]\n", /COLUMNS = \[([^\]]*)\]/)).toEqual([]) + const env = await review(undefined, { consumerLists: loaded([{ path: "loaders/fct.py", model: "fct", columns: [], content: "COLUMNS = []" }]) }) + expect(env.findings.find((x) => x.title.includes("loaders/fct.py"))?.body).toContain("lacks the new column(s) `region`") + }) + + test("a broad pattern keeps an empty list only when its identifier or the entry says it is a column list", async () => { + const content = 'orders = []\nfor row in fetch("orders", []):\n orders.append(row)\nORDERS_COLUMNS = ["order_id", "amount"]\nOTHER_COLUMNS = []\n' + const found = findColumnLists(content, /\[([^\]]*)\]/) + expect(found.map((l) => l.name)).toEqual(["ORDERS_COLUMNS", "OTHER_COLUMNS"]) + expect(findColumnLists("orders = []\n", /\[([^\]]*)\]/, { model: "orders" }).map((l) => l.columns)).toEqual([[]]) + const o = "select id as order_id, amount from src" + const n = "select id as order_id, amount, status from src" + const env = await review(undefined, { + changedFiles: [{ path: "models/orders.sql", status: "modified", diff: `-${o}\n+${n}\n` }], + getContent: async (_f, side) => (side === "old" ? o : n), + getCompiled: async (_f, side) => (side === "old" ? o : n), + consumerLists: loaded(findColumnLists(content, /\[([^\]]*)\]/).map((l) => ({ path: "loaders/orders.py", content, ...l }))), + }) + expect(env.findings.filter((x) => x.title.includes("column list")).map((x) => x.title)).toEqual([ + "orders: column list `ORDERS_COLUMNS` in `loaders/orders.py` is out of step", + ]) + }) + + test("globs as git read them: `./dir/*.py` and a bare directory match; a pattern matching nothing is listed", async () => { + await using tmp = await tmpdir() + const root = tmp.path + await exec("git", ["init", "-q", "-b", "main"], { cwd: root }) + await fs.mkdir(path.join(root, "loaders"), { recursive: true }) + await fs.writeFile(path.join(root, "loaders", "fct.py"), "COLS = [id]\n") + await fs.writeFile(path.join(root, "loaders", "gone.py"), "COLS = [x]\n") + await exec("git", ["add", "-A"], { cwd: root }) + // Tracked but deleted on disk: not at the head, not a read failure. + await fs.rm(path.join(root, "loaders", "gone.py")) + const read = async (p: string) => fs.readFile(path.join(root, p), "utf8").catch(() => undefined) + const pattern = "COLS = \\[([^\\]]*)\\]" + for (const files of ["./loaders/*.py", "loaders", "loaders/", "loaders/fct.py"]) { + const load = await loadConsumerLists({ configs: [{ files, pattern, model: "fct" }], gitRoot: root, read }) + expect({ files, paths: load.lists.map((l) => l.path), errors: load.errors }).toEqual({ files, paths: ["loaders/fct.py"], errors: [] }) + } + const none = await loadConsumerLists({ configs: [{ files: "exports/*.py", pattern }], gitRoot: root, read }) + expect(none.invalid).toEqual(["entry 1: the files pattern matches no file"]) + }) + + test("a match that ends with a line break does not take the next line as its own", () => { + const content = "exports:\n - columns:\n - id\n - amount\n - model: dim\n columns:\n - customer_id\n" + const [first] = findColumnLists(content, /columns:\s*\n((?:\s*-\s*\w+\n)+)/) + expect(first.own).not.toContain("dim") + expect(listMirrorsModel({ path: "e.yml", content, ...first }, "dim")).toBeUndefined() + }) + + test("the finding id of a list does not change when a line is added above it", async () => { + const at = (content: string) => findColumnLists(content, /\[([^\]]*)\]/).map((l) => ({ path: "loaders/x.py", model: "fct", content, ...l })) + const ids = async (content: string) => + (await review(undefined, { consumerLists: loaded(at(content)) })).findings.filter((x) => x.title.includes("loaders/x.py")).map((x) => x.id) + const body = 'load(["id", "email", "amount"])\nload(["id", "email", "amount"])\n' + const before = await ids(body) + expect(before).toHaveLength(2) + expect(await ids("# a comment\n" + body)).toEqual(before) + }) + test("two lists in one file are kept apart, so a stale one is not masked", () => { const py = 'A = [id, amount, region]\nB = [id, amount]\n' expect(extractColumnLists(py, /= \[([^\]]*)\]/)).toEqual([ @@ -737,6 +925,12 @@ describe("opt-in consumer column lists", () => { expect(droppedLists([...mk("exports/orders.py", 'ORDERS = ["order_id", "amount"]\n', B), ...fixture], fixture)).toEqual([ { path: "exports/orders.py", reason: "consumerColumnLists: column list ORDERS is no longer found at the head, so it is not checked" }, ]) + // Unnamed lists are told apart by their own lines, not by their file. + const calls = (orders: string, customers: string) => + mk("l.py", `load("orders", [${orders}])\nload("customers", [${customers}])\n`, B) + expect(droppedLists(calls('"id", "amount"', '"customer_id", "name"'), mk("l.py", 'load("customers", ["customer_id", "email"])\n', B))).toEqual([ + { path: "l.py", reason: "consumerColumnLists: column list line 1 is no longer found at the head, so it is not checked" }, + ]) // An edited list under the same identifier is kept (the lanes check its columns). expect(droppedLists(mk("l.py", py, B), mk("l.py", 'ORDER_COLUMNS = ["order_id"]\n', B))).toEqual([]) }) @@ -817,6 +1011,54 @@ describe("a PR that switches a consumer list off", () => { if (saved.event !== undefined) process.env.GITHUB_EVENT_PATH = saved.event } }, 60000) + + test("a base list that cannot be read holds back approval like a head one, without an internal failure", async () => { + await using tmp = await tmpdir({ git: true }) + const dir = tmp.path + const g = (...a: string[]) => execFileSync("git", a, { cwd: dir }).toString().trim() + const base = g("rev-parse", "--abbrev-ref", "HEAD") + await fs.writeFile(path.join(dir, "dbt_project.yml"), "name: demo\nversion: '1'\nprofile: demo\n") + await fs.mkdir(path.join(dir, "models")) + await fs.mkdir(path.join(dir, "exports")) + await fs.mkdir(path.join(dir, ".altimate")) + await fs.writeFile( + path.join(dir, ".altimate/review.yml"), + 'reviewers: [lineage_breakage]\nconsumerColumnLists:\n - files: "exports/*.py"\n pattern: "COLUMNS = \\\\[([^\\\\]]*)\\\\]"\n model: m\n', + ) + await fs.writeFile(path.join(dir, "models/m.sql"), "select 1 as id\n") + await fs.writeFile(path.join(dir, "exports/m.py"), 'COLUMNS = ["id"]\n') + g("add", "-A") + g("commit", "-qm", "base") + g("checkout", "-q", "-b", "pr") + await fs.writeFile(path.join(dir, "models/m.sql"), "select 2 as id\n") + g("add", "-A") + g("commit", "-qm", "pr") + spy = spyOn(Dispatcher, "call").mockImplementation((async () => ({ success: true, data: {} })) as any) + // Reading the list file at the base fails; everything else reads as usual. + const real = git.showAtRef + const show = spyOn(git, "showAtRef").mockImplementation((async (cwd: string, ref: string, rel: string) => { + if (rel === "exports/m.py") throw new Error("object file is empty") + return real(cwd, ref, rel) + }) as any) + const saved = { ref: process.env.GITHUB_BASE_REF, event: process.env.GITHUB_EVENT_PATH } + process.env.GITHUB_BASE_REF = base + delete process.env.GITHUB_EVENT_PATH + try { + const env = await reviewPullRequest({ cwd: dir, head: "pr", noAi: true }) + expect(env.engineErrors).toEqual([ + expect.objectContaining({ method: "consumerColumnLists.base.read", category: "file_unreadable", count: 1 }), + ]) + expect(JSON.stringify(env)).not.toContain("object file is empty") + expect(env.verdict).not.toBe("APPROVE") + expect(env.internalFailure).toBeUndefined() + expect(env.scope?.unverified).toContainEqual(expect.objectContaining({ path: ".altimate/review.yml", kind: "abstained" })) + } finally { + show.mockRestore() + if (saved.ref === undefined) delete process.env.GITHUB_BASE_REF + else process.env.GITHUB_BASE_REF = saved.ref + if (saved.event !== undefined) process.env.GITHUB_EVENT_PATH = saved.event + } + }, 60000) }) function loaded(lists: ConsumerColumnList[]): ConsumerListLoad { @@ -876,6 +1118,47 @@ describe("unit tests that cannot exercise the model", () => { expect(detectUnitTestFixtures(file, yml("[]"), yml("[]"))).toHaveLength(0) }) + test("unit tests are keyed by model and name: the same name on two models is two tests", () => { + const doc = (rowsB: string) => `unit_tests: + - name: t1 + model: a + given: + - input: ref('x') + rows: [] + expect: + rows: [] + - name: t1 + model: b + given: + - input: ref('x') + rows: ${rowsB} + expect: + rows: [] +` + const fs1 = detectUnitTestFixtures(file, undefined, doc("[{id: 1}]")) + expect(fs1.map((f) => f.model)).toEqual(["a"]) + // Only b's test changed: a's is unchanged and not reported again. + expect(detectUnitTestFixtures(file, doc("[{id: 1}]"), doc("[]")).map((f) => f.model)).toEqual(["b"]) + }) + + test("a number or boolean `model` is read as text, not a crash", () => { + const doc = "unit_tests:\n - name: t1\n model: 42\n given:\n - input: ref('a')\n rows: []\n expect:\n rows: []\n" + expect(detectUnitTestFixtures(file, undefined, doc).map((f) => f.title)).toEqual(["`42`: unit test `t1` doesn't exercise the model"]) + }) + + test("a modified schema file whose base cannot be read gets no unit-test finding; it is reported as unreadable", async () => { + const env = await runReview({ + changedFiles: [{ path: "models/marts/_fct.yml", status: "modified", diff: "+ - name: t1\n" }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner: fakeRunner(), + getContent: async (_f, side) => (side === "old" ? undefined : yml("[]")), + }) + expect(env.findings.some((f) => f.title.includes("unit test"))).toBe(false) + expect(env.scope?.unverified).toContainEqual(expect.objectContaining({ path: "models/marts/_fct.yml", kind: "failed" })) + }) + test("a test or model name with a backtick, a line break or @ stays inside one code span", () => { const name = ["t", "`", "\n\n@", "someone ping"].join("") const model = ["fct @", "team"].join("") diff --git a/packages/opencode/test/altimate/review-runner.test.ts b/packages/opencode/test/altimate/review-runner.test.ts index 564398cad8..1d84579fc2 100644 --- a/packages/opencode/test/altimate/review-runner.test.ts +++ b/packages/opencode/test/altimate/review-runner.test.ts @@ -281,6 +281,7 @@ describe("column lineage and consumers from the manifest", () => { exposures: [{ name: "dash", type: "dashboard" }], contractEnforced: true, contractColumns: ["id", "amount"], + name: "fct", }) expect(await runner.modelConsumers!("missing")).toBeUndefined() }) From 073c54595eaa779cefb6ea4590542c79ecea3361 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 3 Dec 2026 19:12:15 +0530 Subject: [PATCH 05/39] feat(review): incremental, microbatch and snapshot semantics Rules for `on_schema_change`, history plans, slice filters with a keyed strategy, `partition_by` and snapshot config or query changes. Column rules abstain when a side's columns cannot be listed. Config values are compared canonically. PR text lowers a warning, never removes it, and never touches a blocking rule. Dialect packs run only on their engine. Co-Authored-By: Claude Fable 5.2 --- docs/docs/usage/dbt-pr-review.md | 51 ++ .../altimate/review/adapter-capabilities.ts | 35 +- .../opencode/src/altimate/review/config.ts | 6 + .../src/altimate/review/dbt-patterns.ts | 56 +- .../altimate/review/incremental-semantics.ts | 593 +++++++++++++++ .../src/altimate/review/orchestrate.ts | 92 ++- .../src/altimate/review/rule-catalog.ts | 20 + .../opencode/src/altimate/review/runner.ts | 13 + .../altimate/review-contracts-dialect.test.ts | 32 + .../review-incremental-semantics.test.ts | 690 ++++++++++++++++++ 10 files changed, 1567 insertions(+), 21 deletions(-) create mode 100644 packages/opencode/src/altimate/review/incremental-semantics.ts create mode 100644 packages/opencode/test/altimate/review-incremental-semantics.test.ts diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 31c373157b..1c4d1da087 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -303,6 +303,7 @@ riskTierPathTokens: # OFF by default — see "Risk-tier path tokens" b pii: [ssn, email, phone] # or supply your own case-insensitive tokens allowForceTier: true # set false in gate CI: --force-tier is then rejected checkContractColumns: false # opt-in: new columns missing from an enforced contract (CI that doesn't run `dbt build`) +incrementalSliceVars: [] # opt-in: vars that pick one slice per incremental run (e.g. [tenant]) consumerColumnLists: [] # OFF by default — see "Consumers outside dbt" below rubric: blockOn: [lineage_breakage, contract_violation, pii_exposure, semantic_change] @@ -713,6 +714,56 @@ The deterministic rules group into four families: - **dbt unit tests.** A unit test whose `given` inputs are all `rows: []` is reported: it either never tests the model's logic, or expects rows the model has nothing to build from. +- **Incremental and snapshot semantics.** Config is read from the manifest + (project, yml and inline, as dbt merges them) with the head's inline + `{{ config() }}` on top. Formatting-only edits never count as a change. A + model whose output columns can't be listed (a `*` over a table, an unnamed + expression), or a yml with snapshots that doesn't parse, is listed as not + fully verified instead of checked; that does not prevent approval (the + parser's message is not shown). A changed snapshot file that could not be + read is listed as failed and does prevent approval. A plan + named in the PR text answers the history-plan suggestion. It never removes + the `on_schema_change='fail'` or snapshot query warnings: it lowers them to a + suggestion that asks you to confirm the plan, and not at all for a rule + listed in `blockingRules`. + - an existing incremental model gains a column, or its `is_incremental()` + filter changes, and the PR doesn't say how existing rows are handled + (`--full-refresh`, a backfill, or forward-only) — a suggestion. Under + the default `on_schema_change='ignore'` the new column is not added on + incremental runs at all until a full refresh; + - an inline `partition_by` changes on an incremental model (needs a full + refresh). Only a value the base sets inline is compared; equivalent + spellings (dict key order, `'d'` and `['d']`) are not a change; + - `on_schema_change='fail'` and the change adds or removes columns, so the + first incremental run after merge fails; + - a snapshot's inline `check_cols` or `strategy` changes (a `.sql` + snapshot's `{{ config() }}`, or a dbt 1.9+ yml snapshot's `config`), + which can version every row on the next run. `check_cols` compares as a + set; + - a `check` snapshot's query changes and the PR doesn't say how history is + handled: rows the new query computes differently are versioned on the + next run. A `timestamp` snapshot, or one whose strategy can't be read, + is not reported; + - `row_number()` dedup ordered only by a load timestamp (`loaded_at`, + `ingestion_timestamp`) — a suggestion; loader sync columns such as + `_fivetran_synced` are not flagged. +- **Opt-in: per-slice incremental runs.** For projects that run one slice per + invocation (a tenant or region chosen by a var), list those vars: + `incrementalSliceVars: [tenant]`. A `delete+insert` or `merge` model filtered + by one of them must include the filtered column in `unique_key`, or one + slice's run deletes or overwrites another's rows. A model with a + `unique_key` and no `incremental_strategy` runs the adapter's default, which + merges on the key on Snowflake and BigQuery and deletes and re-inserts on it + on Postgres and Redshift; other adapters are not checked for this case. When + the key is computed (a hash or an expression) or is not a column the model + passes through, it may already cover the slice, so the finding is a + suggestion. +- **Adapter-dependent advice** fires only where the adapter table establishes + the behavior. On Trino, `on_table_exists='replace'` with an enforced contract + runs `create or replace` then `insert`, and `drop` removes the table during + the build, so readers outside dbt can see an empty or missing table (a + suggestion). `unique_key` and strategy changes are covered by the engine's + `DBT011`/`DBT012`. - **dbt config / Jinja (`DBT0xx`).** A core **minijinja** parser reads `{{ config(...) }}` and the model body: incremental model without an `is_incremental()` guard, `merge`/`delete+insert` without a `unique_key`, diff --git a/packages/opencode/src/altimate/review/adapter-capabilities.ts b/packages/opencode/src/altimate/review/adapter-capabilities.ts index cb75636dea..2de51948b5 100644 --- a/packages/opencode/src/altimate/review/adapter-capabilities.ts +++ b/packages/opencode/src/altimate/review/adapter-capabilities.ts @@ -11,6 +11,20 @@ export interface AdapterCapability { /** `int / int` returns an integer, dropping the fraction (7 / 2 = 3). */ integerDivisionTruncates: boolean + /** + * A `table` model with an enforced contract and `on_table_exists='replace'` + * is replaced atomically. False = `create or replace` then `insert` as two + * statements (readers see an empty table), and `on_table_exists='drop'` + * leaves no table during the build. Undefined = not established. + */ + contractTableReplaceAtomic?: boolean + /** + * What an incremental model with a `unique_key` and no + * `incremental_strategy` runs: a strategy that merges or deletes on the key. + * Undefined = another default, or not established (dbt-spark shares the + * `databricks` dialect but defaults to `append`). + */ + keyedDefaultStrategy?: "merge" | "delete+insert" /** Documentation backing the entries above. */ sources: string[] } @@ -18,15 +32,24 @@ export interface AdapterCapability { export const ADAPTER_CAPABILITIES: Record = { postgres: { integerDivisionTruncates: true, - sources: ["https://www.postgresql.org/docs/current/functions-math.html"], + keyedDefaultStrategy: "delete+insert", + sources: ["https://docs.getdbt.com/docs/build/incremental-strategy", "https://www.postgresql.org/docs/current/functions-math.html"], }, redshift: { integerDivisionTruncates: true, - sources: ["https://docs.aws.amazon.com/redshift/latest/dg/r_numeric_computations201.html"], + keyedDefaultStrategy: "delete+insert", + sources: ["https://docs.getdbt.com/docs/build/incremental-strategy", "https://docs.aws.amazon.com/redshift/latest/dg/r_numeric_computations201.html"], }, trino: { integerDivisionTruncates: true, - sources: ["https://trino.io/docs/current/functions/math.html"], + contractTableReplaceAtomic: false, + sources: [ + "https://trino.io/docs/current/functions/math.html", + // create_table_as with an enforced contract: `create or replace table` then `insert`; + // on_table_exists='drop' drops the table before building it. + "https://github.com/starburstdata/dbt-trino/blob/master/dbt/include/trino/macros/adapters.sql", + "https://github.com/starburstdata/dbt-trino/blob/master/dbt/include/trino/macros/materializations/table.sql", + ], }, athena: { // Athena SQL runs on Trino. @@ -43,11 +66,13 @@ export const ADAPTER_CAPABILITIES: Record = { }, snowflake: { integerDivisionTruncates: false, - sources: ["https://docs.snowflake.com/en/sql-reference/operators-arithmetic"], + keyedDefaultStrategy: "merge", + sources: ["https://docs.getdbt.com/docs/build/incremental-strategy", "https://docs.snowflake.com/en/sql-reference/operators-arithmetic"], }, bigquery: { integerDivisionTruncates: false, - sources: ["https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#arithmetic_operators"], + keyedDefaultStrategy: "merge", + sources: ["https://docs.getdbt.com/docs/build/incremental-strategy", "https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#arithmetic_operators"], }, databricks: { integerDivisionTruncates: false, diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 2dc04c152f..55587f9acd 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -50,6 +50,12 @@ export const ReviewConfig = z.object({ consumerColumnLists: z .array(z.object({ files: z.string(), pattern: z.string(), model: z.string().optional() })) .default([]), + /** + * Opt-in: vars that select the slice one incremental run processes (e.g. + * `tenant`, `region`). A `delete+insert`/`merge` model filtered by one of + * them must include the filtered column in `unique_key`. + */ + incrementalSliceVars: z.array(z.string()).default([]), /** Allow `--force-tier` (a debug bypass of the risk classifier). Set false * in gate CI so a run cannot skip checks by forcing a lower tier. */ allowForceTier: z.boolean().default(true), diff --git a/packages/opencode/src/altimate/review/dbt-patterns.ts b/packages/opencode/src/altimate/review/dbt-patterns.ts index 74ad9146ab..52fbf92c20 100644 --- a/packages/opencode/src/altimate/review/dbt-patterns.ts +++ b/packages/opencode/src/altimate/review/dbt-patterns.ts @@ -238,6 +238,41 @@ const detectDedupTie: Detector = (c) => { }) } +// 9b. Dedup ordered ONLY by a load/ingestion timestamp. Rows loaded in one batch +// share that value, so which version survives is arbitrary (SCD2 versions ranked +// by `ingestion_timestamp` alone). A business column (`updated_at`) stays +// silent, and so do loader sync columns (`_fivetran_synced`, `_airbyte_*`): +// ordering by them is the standard staging idiom and ties are rare per key. +const LOAD_TS_RE = + /^(_?(ingest(ion|ed)?|load(ed)?|etl|extract(ed)?|batch)(_at|_ts|_time|_timestamp|_date|_dt)|_?(ingestion|load|etl|batch)_timestamp|_loaded_at)$/i +const detectDedupLoadTimestamp: Detector = (c) => { + for (const line of c.added) { + const s = stripComments(line) + const m = /row_number\s*\(\s*\)\s*over\s*\(([^)]*)\)/i.exec(s) + if (!m) continue + const order = /order\s+by\s+(.+)$/i.exec(m[1])?.[1] + if (!order) continue + const keys = order.split(",").map((k) => k.trim().replace(/\s+(asc|desc)\b.*$/i, "").replace(/\s+nulls\s+(first|last)$/i, "")) + if (keys.length !== 1) continue + const col = keys[0].split(".").pop()!.replace(/["`]/g, "") + if (!LOAD_TS_RE.test(col)) continue + return makeFinding({ + severity: "suggestion", + category: "dedup", + title: `${c.model}: dedup ordered only by load timestamp \`${col}\``, + body: + `\`row_number()\` is ordered only by \`${col}\`. Rows loaded in the same batch share it, so which version survives is ` + + "arbitrary and can change between runs. Order by the source's own change time first and add a unique tie-breaker.", + file: c.file.path, + model: c.model, + confidence: "high", + evidence: { tool: "dbt-patterns", result: { rule: "dedup_load_timestamp_only", line: line.trim() } }, + ruleKey: "dedup:load-timestamp-only", + }) + } + return null +} + // 11. Function/cast wrapped around a column in an added WHERE — defeats partition pruning. const detectPartitionFunction: Detector = (c) => { const hit = c.added.find((l) => { @@ -729,6 +764,7 @@ const MODEL_DETECTORS: Detector[] = [ detectFanout, detectNotIn, detectDedupTie, + detectDedupLoadTimestamp, detectPartitionFunction, detectCountDistinct, detectPiiIntoMart, @@ -841,7 +877,7 @@ function extractTestOccurrences(doc: unknown): Set { if (n === "relationships" && t && typeof t === "object") { const args = (t as Record)[name] // dbt 1.10.5+ nests test args under `arguments:`; earlier versions - // put them at the top level of the test's value map (cubic-review P3). + // put them at the top level of the test's value map. const argsObj = args && typeof args === "object" ? (args as Record) : undefined const nested = @@ -927,8 +963,7 @@ function extractTestOccurrences(doc: unknown): Set { * A `dbt_utils.unique_combination_of_columns` test names N columns as the * declared grain. If any grain column lacks `not_null` coverage, a NULL * grain-key silently passes the uniqueness test — the guardrail is toothless. - * `DBT_GUIDELINES.md` in the corpus repo states this as a hard rule; kilo - * catches it, we didn't. + * `DBT_GUIDELINES.md` in the corpus repo states this as a hard rule. * * Coverage sources (either counts): * - `constraints: [{type: not_null}]` on the column — enforced by the @@ -958,8 +993,7 @@ export interface GrainKeyGap { * miss vector when omitted. Sources declare table-level `columns:` + tests * on their `tables[]` entries, so we descend one level. Seeds are covered * for symmetry with `extractTestOccurrences` — grain-key tests on a seed - * are rare but legal (altimate-harness-bot review, PR #1029 - * dbt-patterns.ts:963). + * are rare but legal. */ function iterateGrainEntities(d: Record): Array<{ name: string; body: Record }> { const out: Array<{ name: string; body: Record }> = [] @@ -977,7 +1011,7 @@ function iterateGrainEntities(d: Record): Array<{ name: string; // `name` + `columns` + `tests`/`data_tests`, matching the model shape. // Qualify with the enclosing source name (`.`) so two // sources with a table of the same name don't conflate in change-scoping - // OR finding fingerprint (cubic-review P2 on PR #1029). + // OR finding fingerprint. const sources = d.sources if (Array.isArray(sources)) { for (const s of sources) { @@ -1003,8 +1037,7 @@ function iterateGrainEntities(d: Record): Array<{ name: string; * scope grain-gap findings to entities whose grain declaration actually * changed between the base and head of the PR — otherwise a housekeeping * edit (adding a description, bumping a meta tag) surfaces every - * pre-existing gap in the file and trains reviewers to suppress the rule - * (altimate-harness-bot review, PR #1029 dbt-patterns.ts:1099). + * pre-existing gap in the file and trains reviewers to suppress the rule. */ function extractGrainDeclarations(doc: unknown): Map> { const out = new Map>() @@ -1299,7 +1332,7 @@ export function detectSchemaYmlPatterns( // Deleting a whole schema.yml removes every test declared in it — arguably // a bigger removal than dropping a single test. Treat the new side as empty // and diff the old document against `{}` so every prior test surfaces as a - // removal (cubic-review P2). Requires `oldContent` from the caller. + // removal. Requires `oldContent` from the caller. const isDeletedFile = file.status === "deleted" // PREFERRED: structural YAML diff when we have both sides' content. @@ -1386,8 +1419,7 @@ export function detectSchemaYmlPatterns( // (`combination_of_columns` set) actually changed between the base // and head of this PR. A housekeeping edit — adding a description, // bumping a meta tag — must not surface pre-existing gaps on - // unrelated entities; that trains reviewers to suppress the rule - // (altimate-harness-bot review, PR #1029 dbt-patterns.ts:1099). + // unrelated entities; that trains reviewers to suppress the rule. // When there's no old side (added file), every entity counts as // changed and every gap surfaces. if (!isDeletedFile && newDoc !== undefined) { @@ -1522,7 +1554,7 @@ export function detectSchemaYmlPatterns( file: file.path, // Surface the extracted attribution on the top-level Finding so // downstream consumers (dedupe, formatting, telemetry) see it — - // not just inside `evidence.result` (cubic-review P3). + // not just inside `evidence.result`. model: r.model || undefined, column: r.column || undefined, confidence: "high", diff --git a/packages/opencode/src/altimate/review/incremental-semantics.ts b/packages/opencode/src/altimate/review/incremental-semantics.ts new file mode 100644 index 0000000000..cfe5876a60 --- /dev/null +++ b/packages/opencode/src/altimate/review/incremental-semantics.ts @@ -0,0 +1,593 @@ +import YAML from "yaml" +import { makeFinding, normalizeRuleId, type Finding } from "./finding" +import type { ChangedFile } from "./diff-filter" +import { capabilityFor } from "./adapter-capabilities" +import { codeSpan } from "./format" + +/** + * dbt incremental, table-replace and snapshot semantics. These rules follow + * dbt-core behavior, which is the same on every adapter; where the outcome + * depends on the adapter (atomic table replace) they read + * the capability table and stay silent for adapters it doesn't cover. + * + * Config comes from the manifest (dbt_project.yml + yml + inline, merged by + * dbt) overlaid by the head's inline `{{ config() }}` (inline wins in dbt, and + * the manifest may predate the PR). Change detection compares the inline + * config of the two sides; an inline value that moved to yml with the same + * value (per the manifest) is not a change. + * + * All findings are advisory (`dbt-semantics` evidence → catalog origin). + */ + +// --------------------------------------------------------------------------- +// Inline config parsing +// --------------------------------------------------------------------------- + +/** Text with `--` and block comments blanked, same length. Quoted strings and + * quoted identifiers are skipped first, so `'x--y'` is not a comment. */ +function blankComments(sql: string): string { + let out = "" + let i = 0 + while (i < sql.length) { + const c = sql[i] + if (c === "'" || c === '"' || c === "`") { + // A doubled quote inside a string is an escaped quote. + let j = i + 1 + while (j < sql.length && !(sql[j] === c && sql[j + 1] !== c)) j += sql[j] === c ? 2 : 1 + out += sql.slice(i, j + 1) + i = j + 1 + } else if (c === "-" && sql[i + 1] === "-") { + const end = sql.indexOf("\n", i) + const stop = end < 0 ? sql.length : end + out += " ".repeat(stop - i) + i = stop + } else if (c === "/" && sql[i + 1] === "*") { + const end = sql.indexOf("*/", i + 2) + const stop = end < 0 ? sql.length : end + 2 + out += sql.slice(i, stop).replace(/[^\n]/g, " ") + i = stop + } else { + out += c + i++ + } + } + return out +} + +/** Jinja comments (`{# … #}`) blanked: a commented-out `config()` sets nothing. */ +const stripJinjaComments = (sql: string) => sql.replace(/\{#[\s\S]*?#\}/g, " ") + +/** Index of the bracket closing the one at `open`, skipping quoted strings. */ +function closing(s: string, open: number): number { + const pairs: Record = { "(": ")", "[": "]", "{": "}" } + const stack: string[] = [] + let quote: string | null = null + for (let i = open; i < s.length; i++) { + const c = s[i] + if (quote) { + if (c === "\\") i++ + else if (c === quote) quote = null + continue + } + if (c === "'" || c === '"') quote = c + else if (pairs[c]) stack.push(pairs[c]) + else if (c === stack.at(-1)) { + stack.pop() + if (!stack.length) return i + } + } + return -1 +} + +/** Split on commas at nesting depth 0, outside quotes. */ +function topLevelSplit(s: string): string[] { + const out: string[] = [] + let depth = 0 + let quote: string | null = null + let start = 0 + for (let i = 0; i < s.length; i++) { + const c = s[i] + if (quote) { + if (c === "\\") i++ + else if (c === quote) quote = null + continue + } + if (c === "'" || c === '"') quote = c + else if ("([{".includes(c)) depth++ + else if (")]}".includes(c)) depth-- + else if (c === "," && depth === 0) { + out.push(s.slice(start, i)) + start = i + 1 + } + } + out.push(s.slice(start)) + return out +} + +/** `key → raw value text` from every `{{ config(...) }}` in the SQL. */ +export function inlineConfig(sql: string | undefined): Record { + const out: Record = {} + if (!sql) return out + sql = stripJinjaComments(sql) + for (const m of sql.matchAll(/\{\{-?\s*config\s*\(/g)) { + const open = m.index! + m[0].length - 1 + const close = closing(sql, open) + if (close < 0) continue + for (const part of topLevelSplit(sql.slice(open + 1, close))) { + const kv = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*([\s\S]*?)\s*$/.exec(part) + if (kv) out[kv[1]] = kv[2] + } + } + return out +} + +const unquote = (v: string) => v.trim().replace(/^['"]|['"]$/g, "") + +/** An inline config value (Jinja/Python literal text) as data, so it compares + * with the manifest's parsed value; unparseable text stays a string. */ +function inlineValue(raw: string): unknown { + // A trailing comma (`['a', 'b',]`) is legal in Jinja and Python, not in JSON. + const t = raw.trim().replace(/,(\s*[\]}])/g, "$1") + try { + return JSON.parse( + t.replace(/'/g, '"').replace(/\bTrue\b/g, "true").replace(/\bFalse\b/g, "false").replace(/\bNone\b/g, "null"), + ) + } catch { + // Not a literal (a `var()` inside, say): compare its text without the + // whitespace outside quotes, in one quote style. + return unquote(t.replace(/('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")|\s+/g, (m, q) => q ?? "").replace(/"/g, "'")) + } +} + +/** Canonical, case-insensitive form of a config value (object keys sorted). */ +function canonValue(v: unknown): string { + // `10` and `'10'` are the same config value. + if (typeof v === "string" && /^-?\d+(\.\d+)?$/.test(v.trim())) return JSON.stringify(Number(v)) + if (v === null || typeof v !== "object") return JSON.stringify(typeof v === "string" ? v.toLowerCase() : v) ?? "null" + if (Array.isArray(v)) return "[" + v.map(canonValue).join(",") + "]" + const o = v as Record + return "{" + Object.keys(o).filter((k) => o[k] !== undefined && o[k] !== null).sort().map((k) => `${JSON.stringify(k)}:${canonValue(o[k])}`).join(",") + "}" +} + +/** Keys whose list value is a set: `check_cols=['a','b']` equals `['b','a']`. */ +const SET_KEYS = new Set(["check_cols"]) + +/** + * Canonical form of a config value for change detection: dict key order and + * case ignored, a scalar equal to its one-element list (`'d'` = `['d']`), and + * the set-valued keys compared as sets. + */ +function canonConfig(key: string, v: unknown): string { + const list = Array.isArray(v) && v.length === 1 ? v[0] : v + if (Array.isArray(list) && SET_KEYS.has(key)) return "[" + list.map(canonValue).sort().join(",") + "]" + return canonValue(list) +} + +/** + * Whether the effective value of `key` changed between the two sides' inline + * config. An inline value removed while the (head) manifest carries the same + * value moved to yml or `dbt_project.yml`: unchanged. A value only the new side + * sets inline can't be compared without the base's effective config, so it is + * not reported. + */ +function inlineConfigChanged( + key: string, + before: Record, + after: Record, + manifest?: Record, +): boolean { + const o = before[key] + const n = after[key] + if (o === undefined) return false + if (n !== undefined) return canonConfig(key, inlineValue(o)) !== canonConfig(key, inlineValue(n)) + const m = manifest?.[key] + return m === undefined || m === null || canonConfig(key, inlineValue(o)) !== canonConfig(key, m) +} + +function asList(v: unknown): string[] | undefined { + if (v === undefined || v === null) return undefined + if (Array.isArray(v)) return v.map((x) => String(x).toLowerCase()) + const s = String(v).trim() + if (s.startsWith("[")) return [...s.matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1].toLowerCase()) + return [unquote(s).toLowerCase()] +} + +export interface ModelSemantics { + materialized?: string + strategy?: string + uniqueKey?: string[] + onSchemaChange?: string + contractEnforced?: boolean + onTableExists?: string +} + +/** Effective config: manifest `config` overlaid by the inline `{{ config() }}`. */ +export function modelSemantics(inline: Record, manifest?: Record): ModelSemantics { + const m = manifest ?? {} + const str = (k: string) => (inline[k] !== undefined ? unquote(inline[k]).toLowerCase() : typeof m[k] === "string" ? (m[k] as string).toLowerCase() : undefined) + const contractInline = inline.contract !== undefined ? /['"]?enforced['"]?\s*:\s*true/i.test(inline.contract) : undefined + const contractManifest = (m.contract as { enforced?: boolean } | undefined)?.enforced + return { + materialized: str("materialized"), + strategy: str("incremental_strategy"), + uniqueKey: asList(inline.unique_key ?? m.unique_key), + onSchemaChange: str("on_schema_change"), + contractEnforced: contractInline ?? contractManifest, + onTableExists: str("on_table_exists"), + } +} + +/** The SQL with config blocks, comments and whitespace removed: what the model computes. */ +export function modelBody(sql: string): string { + let s = blankComments(stripJinjaComments(sql)) + for (;;) { + const m = /\{\{-?\s*config\s*\(/.exec(s) + if (!m) break + const close = closing(s, m.index + m[0].length - 1) + const end = close < 0 ? -1 : s.indexOf("}}", close) + if (end < 0) break + s = s.slice(0, m.index) + s.slice(end + 2) + } + // Lowercase everything but string literals: `'paid'` → `'PAID'` is a change. + return s + .replace(/\s+/g, " ") + .trim() + .split(/('(?:[^']|'')*')/) + .map((part, k) => (k % 2 ? part : part.toLowerCase())) + .join("") +} + +/** The body as a token stream, so formatting (spaces, line breaks, case) never counts as a change. */ +export function bodyTokens(sql: string): string { + return (modelBody(sql).match(/[a-z0-9_$]+|'(?:[^']|'')*'|[^\s\w]/gi) ?? []).join(" ") +} + +/** The `{% if is_incremental() %}` block(s): what each incremental run picks up. */ +export function incrementalFilter(sql: string): string { + const blocks = [...sql.matchAll(/\{%-?\s*if\s+is_incremental\(\)\s*-?%\}([\s\S]*?)\{%-?\s*endif\s*-?%\}/gi)].map((m) => m[1]) + return blocks.map((b) => bodyTokens(b)).join(" | ") +} + +/** + * Columns compared to one of the named vars: the slice one run processes. Only + * vars the project lists (`incrementalSliceVars`) count, so a filter like + * `currency = '{{ var("reporting_currency") }}'` is not mistaken for a slice. + */ +export function varScopedColumns(sql: string, sliceVars: string[]): string[] { + if (!sliceVars.length) return [] + const names = new Set(sliceVars.map((v) => v.toLowerCase())) + const out = new Set() + const re = /(?:\b[A-Za-z_][\w]*\.)?\b([A-Za-z_][\w]*)\s*(?:=|\bin\b)\s*\(?\s*['"]?\{\{\s*var\s*\(\s*['"]([^'"]+)['"]/gi + for (const m of modelBody(sql).matchAll(re)) if (names.has(m[2].toLowerCase())) out.add(m[1].toLowerCase()) + return [...out] +} + +/** + * PR text that mentions a plan. The text is not parsed ("No backfill needed" + * mentions one too), so a match never removes a warning: it lowers it to a + * suggestion that asks to confirm the plan, unless the project blocks on the + * rule. The history-plan suggestion asks for a plan, so a named one answers it. + */ +const PLAN_RE = /full[- _]?refresh|backfill|forward[- ]only|rebuild|re-?run (the )?history|history (is|stays|will)/i +const FULL_REFRESH_RE = /full[- _]?refresh/i +const CONFIRM_PLAN = " The PR text mentions a plan for history: confirm it covers this change." + +/** Whether the rubric's `blockingRules` names `rule`: PR text never weakens such a rule. */ +const blocks = (rule: string, blockingRules: string[] = []) => + blockingRules.some((r) => normalizeRuleId(r) === normalizeRuleId(rule)) +const CONFIRM_FULL_REFRESH = " The PR text mentions a full refresh: confirm it is planned for the deploy." + +// --------------------------------------------------------------------------- +// Rules +// --------------------------------------------------------------------------- + +export interface IncrementalInput { + file: ChangedFile + model: string + newSql: string + oldSql?: string + /** The model's `config` from the manifest, when it is there. */ + manifestConfig?: Record + /** Added diff lines (raw). */ + added: string[] + dialect: string + dialectKnown: boolean + /** PR title + description; empty outside a PR run. */ + prText: string + /** Exposures (readers outside dbt) depend on this model. */ + hasExposures: boolean + /** Vars that select the slice one run processes (`incrementalSliceVars`); empty = rule off. */ + sliceVars: string[] + /** Output columns added/removed by the change; `unknown` when either side's + * column list could not be listed, so nothing can be said about columns. */ + columnDelta: () => { added: string[]; removed: string[]; unknown: boolean } + /** The head's output column names (lowercased); undefined when not listed. */ + outputColumns: () => string[] | undefined + /** Lists the model as not fully verified (kind `abstained`). */ + abstain: (reason: string) => void + /** The rubric's `blockingRules`. */ + blockingRules?: string[] +} + +/** A name from the repository (model, column, yml entry) as a code span that a + * backtick, `@`, `#` or a control character inside cannot break out of. */ +const inlineCode = (x: string) => codeSpan(x.replace(/[\u0000-\u001f\u007f\s]+/g, " ").trim()) +const ticks = (xs: string[]) => xs.map(inlineCode).join(", ") +const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/ + +function finding(input: { file: ChangedFile; model: string }, rule: string, severity: Finding["severity"], category: Finding["category"], title: string, body: string): Finding { + // A plain identifier stays bare (the summary drops the `model: ` prefix); + // any other name, such as a yml snapshot's free-text `name`, is a code span. + const plain = IDENT.test(input.model) + return makeFinding({ + severity, + category, + // Backticks become `'`, so no nested fence is left for later rendering to mis-pair. + title: `${plain ? input.model : inlineCode(input.model.replace(/`/g, "'"))}: ${title}`, + body, + file: input.file.path, + model: plain ? input.model : undefined, + confidence: "high", + evidence: { tool: "dbt-semantics", result: { rule } }, + ruleKey: `${category}:${rule}`, + }) +} + +/** The select item that ends at `end` (exclusive): back to a comma, an open + * parenthesis or `select` at the same depth, skipping quoted text. */ +function itemBefore(body: string, end: number): string { + let depth = 0 + let i = end - 1 + for (; i >= 0; i--) { + const c = body[i] + if (c === "'" || c === '"') { + const open = body.lastIndexOf(c, i - 1) + if (open < 0) break + i = open + } else if (c === ")") depth++ + else if (c === "(") { + if (!depth) break + depth-- + } else if (c === "," && !depth) break + else if (!depth && /(^|[^\w$])select$/.test(body.slice(Math.max(0, i - 6), i + 1))) break + } + return body.slice(i + 1, end).trim().replace(/^(distinct|all)\s+/, "") +} + +/** + * Whether the model computes `key` rather than passing a column through: an + * expression entry, or `key` aliased from any select item other than + * `[qualifier.]column` (a concatenation, a `case`, a function, a macro). + */ +function computedKey(sql: string, key: string): boolean { + if (!IDENT.test(key)) return true + const body = modelBody(sql) + const column = /^"?[a-z_][\w$]*"?(\."?[a-z_][\w$]*"?)*$/ + for (const m of body.matchAll(new RegExp(`\\s+as\\s+"?${key}"?(?![\\w$])`, "g"))) + if (!column.test(itemBefore(body, m.index))) return true + // An alias without `as` (`a || b order_sk`): the item ends in the key, at a + // comma, `from` or the end, after something that is not a qualifier dot. + for (const m of body.matchAll(new RegExp(`(?<=[\\w$)'"\\]])\\s+"?${key}"?(?=\\s*(,|\\bfrom\\b|$))`, "g"))) { + const item = itemBefore(body, m.index) + if (item && !/\bas$/.test(item) && !column.test(item)) return true + } + return false +} + +export async function incrementalFindings(input: IncrementalInput): Promise { + const inlineNew = inlineConfig(input.newSql) + const inlineOld = inlineConfig(input.oldSql) + const cfg = modelSemantics(inlineNew, input.manifestConfig) + const isNew = input.file.status === "added" + const addedText = input.added.join("\n") + const out: Finding[] = [] + const cap = input.dialectKnown ? capabilityFor(input.dialect) : undefined + + if (cfg.materialized === "incremental") { + const logicChanged = !isNew && !!input.oldSql && bodyTokens(input.oldSql) !== bodyTokens(input.newSql) + // The column delta, read once; a side whose columns could not be listed + // lists the model as not fully verified instead of guessing. + let delta: ReturnType | undefined + const columns = () => { + if (!delta) { + delta = input.columnDelta() + if (delta.unknown) + input.abstain( + "the model's output columns could not be listed (a `*`, an unnamed expression or SQL the parser does not follow), so the incremental column rules were not checked", + ) + } + return delta.unknown ? { added: [], removed: [] } : delta + } + const onFail = cfg.onSchemaChange === "fail" + + // History diverges from new rows when the incremental filter changes or a + // column is added. Formatting-only edits never count. Under + // `on_schema_change='fail'` column changes have their own finding below, + // so only a filter change is reported here. + if (logicChanged && !PLAN_RE.test(input.prText)) { + const filterChanged = incrementalFilter(input.oldSql!) !== incrementalFilter(input.newSql) + const added = onFail ? [] : columns().added + if (filterChanged || added.length) { + const one = added.length === 1 + const newCols = !added.length + ? "" + : !cfg.onSchemaChange || cfg.onSchemaChange === "ignore" + ? `${ticks(added)} ${one ? "is" : "are"} new: with \`on_schema_change='ignore'\`${cfg.onSchemaChange ? "" : " (the default)"}, ` + + `incremental runs don't add ${one ? "it" : "them"} to the existing table, so ${one ? "it appears" : "they appear"} only after a \`--full-refresh\`.` + : `${ticks(added)} ${one ? "is" : "are"} new: rows built before this change get NULL unless backfilled.` + const why = [ + newCols, + filterChanged ? "The `is_incremental()` filter changed, so what a run picks up differs from what is already loaded." : "", + ].filter(Boolean).join(" ") + out.push( + finding(input, "incremental-history-plan", "suggestion", "materialization", "incremental change without a plan for existing rows", + `${why} Say in the PR how history is handled: \`--full-refresh\` on deploy, a backfill of the affected range, or that the change is forward-only.`), + ) + } + } + + if (!isNew && inlineConfigChanged("partition_by", inlineOld, inlineNew, input.manifestConfig)) + out.push( + finding(input, "incremental-partition-change", "warning", "materialization", "`partition_by` changed on an incremental model", + "Incremental runs don't rebuild the existing table: depending on the adapter, the next incremental run fails or the table keeps its old partitioning. Run `--full-refresh` on deploy."), + ) + + // A full refresh rebuilds the table, so the first run can't fail: PR text + // mentioning one lowers the finding to a suggestion (not a blocking rule). + if (onFail && logicChanged) { + const { added, removed } = columns() + if (added.length || removed.length) { + const what = [added.length ? `adds ${ticks(added)}` : "", removed.length ? `removes ${ticks(removed)}` : ""].filter(Boolean).join(" and ") + const mentioned = FULL_REFRESH_RE.test(input.prText) && !blocks("on-schema-change-fail", input.blockingRules) + out.push( + finding(input, "on-schema-change-fail", mentioned ? "suggestion" : "warning", "materialization", "`on_schema_change='fail'` with changed columns", + `This change ${what}, and \`on_schema_change='fail'\` stops the first incremental run after merge. ` + + "Run `--full-refresh` on deploy, or use `append_new_columns` / `sync_all_columns`." + (mentioned ? CONFIRM_FULL_REFRESH : "")), + ) + } + } + + // A per-slice run (filtered by a var) whose key doesn't contain the slice + // column. No strategy with a `unique_key` runs the adapter's default. + const strategy = cfg.strategy ?? (cfg.uniqueKey?.length ? cap?.keyedDefaultStrategy : undefined) + if ((strategy === "delete+insert" || strategy === "merge") && cfg.uniqueKey?.length && + (isNew || /unique_key|incremental_strategy|var\s*\(/i.test(addedText))) { + const missing = varScopedColumns(input.newSql, input.sliceVars).filter((c) => !cfg.uniqueKey!.includes(c)) + if (missing.length) { + const effect = strategy === "delete+insert" ? "deletes" : "overwrites" + // Only a key made of columns the model passes through is known not to + // cover the slice; a computed or unlisted key (a hash, an expression, a + // column from upstream) may already include it. + const outputs = input.outputColumns() + const plain = !!outputs && cfg.uniqueKey.every((k) => outputs.includes(k) && !computedKey(input.newSql, k)) + out.push( + !plain + ? finding(input, "unique-key-missing-slice-column", "suggestion", "dedup", `\`unique_key\` may not include ${ticks(missing)}`, + `Each run processes the slice selected by ${ticks(missing)} (a \`var()\` filter), and \`unique_key\` is ${ticks(cfg.uniqueKey)}, ` + + `which is not a column the model passes through, so whether it covers ${ticks(missing)} could not be told. If it doesn't, a run for one slice ${effect} ` + + `other slices' rows that share a key; add ${ticks(missing)} to \`unique_key\`.`) + : finding(input, "unique-key-missing-slice-column", "warning", "dedup", `\`unique_key\` doesn't include ${ticks(missing)}`, + `Each run processes the slice selected by ${ticks(missing)} (a \`var()\` filter), but \`unique_key\` is ${ticks(cfg.uniqueKey)}. ` + + `A run for one slice ${effect} other slices' rows that share a key. Add ${ticks(missing)} to \`unique_key\`.`), + ) + } + } + } + + // Non-atomic table rebuild on an adapter that runs create-then-insert or drop-then-create. + const gap = + cfg.materialized === "table" && cap?.contractTableReplaceAtomic === false + ? cfg.onTableExists === "drop" + ? "drops the table and then builds it, so it doesn't exist during each build" + : cfg.onTableExists === "replace" && cfg.contractEnforced + ? "runs `create or replace table` and then `insert` as two statements (enforced contract), so readers see an empty table during each build" + : undefined + : undefined + if (gap && (isNew || /contract|on_table_exists|materialized/i.test(addedText))) + out.push( + finding(input, "non-atomic-table-replace", "suggestion", "materialization", "table is unavailable while it rebuilds", + `On ${input.dialect}, \`on_table_exists='${cfg.onTableExists}'\` ${gap}. ` + + `Readers outside dbt${input.hasExposures ? " (this model has exposures)" : ""} can hit that window; ` + + "`on_table_exists='rename'` swaps the table in at the end."), + ) + + return out +} + +const TRACKING_BODY = + "Changing what an existing snapshot compares can version every row on the next run (a column new to the snapshot compares " + + "NULL with its value), recording history that never happened. Check on a copy first, or start a new snapshot table." + +/** + * Snapshot definitions: a changed `check_cols`/strategy, or a changed SELECT on + * an existing `check` snapshot. A `timestamp` snapshot versions a row only when + * its `updated_at` moves, so a query change there is not reported; neither is + * one whose strategy can't be read. + */ +export function snapshotFindings(input: { + file: ChangedFile + model: string + newSql: string + oldSql?: string + prText: string + /** The snapshot's `config` from the manifest, to tell a move to yml from a change. */ + manifestConfig?: Record + /** The rubric's `blockingRules`. */ + blockingRules?: string[] +}): Finding[] { + if (input.file.status === "added" || !input.oldSql) return [] + const before = inlineConfig(input.oldSql) + const after = inlineConfig(input.newSql) + const out: Finding[] = [] + const changed = ["check_cols", "strategy"].filter((k) => inlineConfigChanged(k, before, after, input.manifestConfig)) + const strategy = (after.strategy !== undefined ? unquote(after.strategy) : String(input.manifestConfig?.strategy ?? "")).toLowerCase() + if (changed.length) + out.push( + finding(input, "snapshot-tracking-change", "warning", "materialization", `snapshot ${changed.map((k) => `\`${k}\``).join(" and ")} changed`, TRACKING_BODY), + ) + else if (strategy === "check" && bodyTokens(input.oldSql) !== bodyTokens(input.newSql)) { + const mentioned = PLAN_RE.test(input.prText) && !blocks("snapshot-logic-no-plan", input.blockingRules) + out.push( + finding(input, "snapshot-logic-no-plan", mentioned ? "suggestion" : "warning", "materialization", + mentioned ? "snapshot query changed: confirm the plan for history" : "snapshot query changed without a plan for history", + "This is a `check` snapshot: rows already captured keep the old query's values, and the next run versions every row whose checked " + + "columns the new query computes differently. Say in the PR how history is handled (backfill, a new snapshot, or accepted as forward-only)." + + (mentioned ? CONFIRM_PLAN : "")), + ) + } + return out +} + +/** Reason recorded when a changed yml with snapshots could not be parsed. */ +const YML_UNPARSED = "the YAML could not be parsed, so its snapshot configs (`check_cols`, `strategy`) were not checked" + +/** + * dbt 1.9+ snapshots defined in yml (`snapshots:` with `config.check_cols`/`strategy`). + * A side that declares `snapshots:` but does not parse is reported through + * `abstain` (not fully verified) instead of read as "nothing changed". + */ +export function snapshotYmlFindings( + file: ChangedFile, + oldContent: string | undefined, + newContent: string | undefined, + abstain: (reason: string) => void = () => {}, +): Finding[] { + if (file.status === "added" || file.status === "deleted" || !oldContent || !newContent) return [] + let unparsed = false + const configs = (text: string) => { + const out = new Map>() + let doc: unknown + try { + doc = YAML.parse(text) + } catch { + if (/^snapshots\s*:/m.test(text)) unparsed = true + return out + } + const list = (doc as { snapshots?: unknown })?.snapshots + if (!Array.isArray(list)) return out + for (const snap of list) + if (snap && typeof snap === "object" && typeof (snap as any).name === "string") + out.set((snap as any).name, ((snap as any).config ?? {}) as Record) + return out + } + const before = configs(oldContent) + const after = configs(newContent) + if (unparsed) { + abstain(YML_UNPARSED) + return [] + } + const out: Finding[] = [] + for (const [name, cfg] of after) { + const prev = before.get(name) + if (!prev) continue + const changed = ["check_cols", "strategy"].filter( + (k) => prev[k] !== undefined && canonConfig(k, prev[k]) !== canonConfig(k, cfg[k]), + ) + if (changed.length) + out.push( + finding({ file, model: name }, "snapshot-tracking-change", "warning", "materialization", + `snapshot ${changed.map((k) => `\`${k}\``).join(" and ")} changed`, TRACKING_BODY), + ) + } + return out +} diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 03c59ac62a..e88744832a 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -50,6 +50,7 @@ import { } from "./rule-catalog" import { listKey, listLabel, listMirrorsModel, type ConsumerColumnList, type ConsumerListLoad } from "./consumer-lists" import { detectUnitTestFixtures } from "./unit-tests" +import { incrementalFindings, snapshotFindings, snapshotYmlFindings } from "./incremental-semantics" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult } from "./ai-review" import { hasInternalFailure, reportFailure } from "./failure" import { codeSpan } from "./format" @@ -198,6 +199,8 @@ export interface ReviewRunner { } | undefined > + /** A model's or snapshot's merged dbt `config` from the manifest (project + yml + inline). */ + modelConfig?(name: string): Promise | undefined> /** 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. */ @@ -927,6 +930,45 @@ function consumerListLane(ctx: ModelContext, lists: ConsumerColumnList[], abstai 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 @@ -1782,14 +1824,13 @@ export async function runReview(input: OrchestrateInput): Promise` (typo - // guard, cubic + harness-bot P2). Catch that here so a single config + // 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 - // (cubic-review P2 on PR #1028 risk-tier.ts:134). + // rather than getting silent auto-approve on billing/PCI/etc. paths. let pathTokenCategoryOf: ((p: string) => string | undefined) | undefined let pathTokenConfigError: string | undefined try { @@ -1846,6 +1887,7 @@ export async function runReview(input: OrchestrateInput): Promise | undefined const changedYmlText = () => @@ -2205,6 +2247,20 @@ export async function runReview(input: OrchestrateInput): Promise 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. @@ -2256,6 +2312,31 @@ export async function runReview(input: OrchestrateInput): Promise f.kind === "snapshot" && f.status !== "deleted" && f.status !== "added") + const sets = await Promise.all( + snapshots.map(async (file) => { + try { + const [oldSql, newSql] = await Promise.all([getContent?.(file.oldPath ?? file.path, "old"), getContent?.(file.path, "new")]) + // A side that could not be read leaves the snapshot not reviewed, not clean. + 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) + } + // 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*$/, "") @@ -2295,7 +2376,7 @@ export async function runReview(input: OrchestrateInput): Promise + unverified.push({ path: file.path, reason, kind: "abstained" }), + ), ] } catch (err) { // One malformed schema file degrades that file only. diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 497b62ffdd..9e57d07656 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -2950,6 +2950,22 @@ function gatedBody(rule: Rule, ctx: CatalogContext | undefined): string | null { return rule.portabilityBody?.replace("{dialect}", ctx.dialect) ?? null } +const PACK_ENGINE: Record = { + BigQuery: "bigquery", + Snowflake: "snowflake", + Redshift: "redshift", + Databricks: "databricks", + // Spark SQL runs on the Databricks/Spark adapters (the `spark` adapter maps to `databricks`). + Spark: "databricks", + "Spark/Databricks": "databricks", +} + +/** The engine a dialect-pack rule is about (from its `Engine:` title prefix), if any. */ +export function ruleEngine(rule: Rule): string | undefined { + const m = /^(BigQuery|Snowflake|Redshift|Databricks|Spark\/Databricks|Spark):/.exec(rule.title) + return m ? PACK_ENGINE[m[1]] : undefined +} + /** Evaluate the catalog against a changed file. */ export function evaluateCatalog( file: ChangedFile, @@ -2963,6 +2979,10 @@ export function evaluateCatalog( const model = modelName(file.path) const matched: { rule: Rule; finding: Finding }[] = [] for (const rule of CATALOG) { + // A dialect pack (BigQuery partition filters, Snowflake VARIANT…) only + // applies to its own engine once the project's engine is known. + const engine = ruleEngine(rule) + if (engine && ctx?.dialectKnown && ctx.dialect.toLowerCase().replace(/^spark$/, "databricks") !== engine) continue if (!ruleMatches(rule, input)) continue const body = gatedBody(rule, ctx) if (body === null) continue diff --git a/packages/opencode/src/altimate/review/runner.ts b/packages/opencode/src/altimate/review/runner.ts index b56d14dd65..23f10fbc95 100644 --- a/packages/opencode/src/altimate/review/runner.ts +++ b/packages/opencode/src/altimate/review/runner.ts @@ -552,6 +552,19 @@ export function createDispatcherRunner(opts: DispatcherRunnerOptions): ReviewRun } }, + async modelConfig(name: string) { + try { + const raw = loadRawManifest(opts.manifestPath) + const hit = Object.entries(raw?.nodes ?? {}).find( + ([id, n]) => (id.startsWith("model.") || id.startsWith("snapshot.")) && n?.name === name, + ) + return hit?.[1]?.config as Record | undefined + } catch (err) { + fail("modelConfig", err) + return undefined + } + }, + async isComplex(sql: string, dialect?: string): Promise { // Only a tiering hint: a failure reads as "not complex" and is recorded // nowhere, since no check was skipped and the run must not lose approval. diff --git a/packages/opencode/test/altimate/review-contracts-dialect.test.ts b/packages/opencode/test/altimate/review-contracts-dialect.test.ts index 84bb5dfc69..a333b9bc8c 100644 --- a/packages/opencode/test/altimate/review-contracts-dialect.test.ts +++ b/packages/opencode/test/altimate/review-contracts-dialect.test.ts @@ -1280,3 +1280,35 @@ describe("no error text from these checks reaches the comment, the envelope or t expect(log).toMatch(/altimate review: (file_unreadable|engine_error) check=(consumerColumnLists\.\w+|modelConsumers)\b/) }) }) + +describe("dialect packs apply to their own engine", () => { + const file = { path: "models/marts/fct_orders.sql", status: "added" as const } + const sql = "select count(distinct user_id) from `proj`.`ds`.`events_fct`" + const packs = (ctx?: { dialect: string; dialectKnown: boolean }) => + evaluateCatalog(file, sql, [sql], [], DEFAULT_RUBRIC, ctx) + .map((f) => f.title) + .filter((t) => /: (BigQuery|Snowflake|Redshift|Databricks):/.test(t)) + + test("a DuckDB or Snowflake project gets no BigQuery advice", () => { + expect(packs({ dialect: "duckdb", dialectKnown: true })).toEqual([]) + expect(packs({ dialect: "snowflake", dialectKnown: true })).toEqual([]) + }) + + test("a BigQuery project, or an unknown engine, keeps it", () => { + expect(packs({ dialect: "bigquery", dialectKnown: true }).length).toBeGreaterThan(0) + expect(packs({ dialect: "snowflake", dialectKnown: false }).length).toBeGreaterThan(0) + expect(packs().length).toBeGreaterThan(0) + }) + test("Spark rules fire only on Databricks/Spark once the engine is known", () => { + const line = "select to_date(order_date), explode(items) from t" + const spark = (ctx?: { dialect: string; dialectKnown: boolean }) => + evaluateCatalog(file, line, [line], [], DEFAULT_RUBRIC, ctx) + .map((f) => f.title) + .filter((t) => /: Spark(\/Databricks)?:/.test(t)) + expect(spark({ dialect: "snowflake", dialectKnown: true })).toEqual([]) + expect(spark({ dialect: "postgres", dialectKnown: true })).toEqual([]) + expect(spark({ dialect: "databricks", dialectKnown: true })).toHaveLength(2) + expect(spark({ dialect: "spark", dialectKnown: true })).toHaveLength(2) + expect(spark()).toHaveLength(2) + }) +}) diff --git a/packages/opencode/test/altimate/review-incremental-semantics.test.ts b/packages/opencode/test/altimate/review-incremental-semantics.test.ts new file mode 100644 index 0000000000..0c462300ee --- /dev/null +++ b/packages/opencode/test/altimate/review-incremental-semantics.test.ts @@ -0,0 +1,690 @@ +import { describe, test, expect, spyOn } from "bun:test" +import path from "node:path" +import { + incrementalFindings, + inlineConfig, + modelBody, + modelSemantics, + snapshotFindings, + snapshotYmlFindings, + varScopedColumns, + type IncrementalInput, +} from "../../src/altimate/review/incremental-semantics" +import { detectModelPatterns } from "../../src/altimate/review/dbt-patterns" +import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import { renderSummary } from "../../src/altimate/review/format" +import { buildEnvelope } from "../../src/altimate/review/verdict" +import { createDispatcherRunner } from "../../src/altimate/review/runner" +import { emitReviewRun } from "../../src/altimate/review/telemetry" +import { Telemetry } from "../../src/altimate/telemetry" +import * as manifestHelpers from "../../src/altimate/native/dbt/helpers" + +/** + * dbt incremental / microbatch / snapshot semantics. Generic rules are checked + * on two adapters; adapter-dependent rules fire only where the capability + * table says the behavior is real. + */ + +const INC = (body: string, cfg = "materialized='incremental', incremental_strategy='merge', unique_key='id'") => + `{{ config(${cfg}) }}\n${body}\n{% if is_incremental() %} where ts > (select max(ts) from {{ this }}) {% endif %}\n` + +function input(over: Partial): IncrementalInput { + return { + file: { path: "models/marts/fct.sql", status: "modified" }, + model: "fct", + newSql: INC("select id, ts from src"), + oldSql: INC("select id, ts from src"), + added: [], + dialect: "snowflake", + dialectKnown: true, + prText: "", + hasExposures: false, + sliceVars: [], + columnDelta: () => ({ added: [], removed: [], unknown: false }), + outputColumns: () => undefined, + abstain: () => {}, + ...over, + } +} +/** Markdown text outside inline code spans (CommonMark: a run of N backticks + * closes on the next run of exactly N). */ +function outsideSpans(md: string): string { + let out = "" + let i = 0 + while (i < md.length) { + if (md[i] !== "`") { + out += md[i++] + continue + } + let j = i + while (md[j] === "`") j++ + const close = new RegExp(`(?) => + (await incrementalFindings(input(over))).map((f) => (f.evidence?.result as { rule: string }).rule) + +describe("config parsing", () => { + test("inline config keeps nested values whole", () => { + const c = inlineConfig("{{ config(materialized='incremental', unique_key=['a', 'b'], contract={'enforced': true}, partition_by={'field': 'd', 'granularity': 'day'}) }}") + expect(c.unique_key).toBe("['a', 'b']") + expect(c.partition_by).toBe("{'field': 'd', 'granularity': 'day'}") + expect(modelSemantics(c).uniqueKey).toEqual(["a", "b"]) + expect(modelSemantics(c).contractEnforced).toBe(true) + }) + + test("manifest config fills what the inline config doesn't set; inline wins", () => { + const s = modelSemantics(inlineConfig("{{ config(on_schema_change='fail') }}"), { + materialized: "incremental", + on_schema_change: "ignore", + unique_key: "id", + }) + expect(s).toMatchObject({ materialized: "incremental", onSchemaChange: "fail", uniqueKey: ["id"] }) + }) + + test("the model body keeps string literals: `--` inside one and its case both count", () => { + expect(modelBody("select 'a--b' as x, y from t")).toContain("y from t") + expect(modelBody("select * from t where s = 'paid'")).not.toBe(modelBody("select * from t where s = 'PAID'")) + expect(modelBody("SELECT * FROM t")).toBe(modelBody("select * from t")) + }) + + test("the model body ignores config, comments and whitespace", () => { + expect(modelBody("{{ config(a='b') }}\nselect 1 -- x\n")).toBe(modelBody("{# doc #}{{ config(a='c') }} select 1")) + }) + + test("a config() inside a Jinja comment sets nothing", () => { + const sql = "{{ config(materialized='incremental', on_schema_change='fail') }}\n{# was: {{ config(materialized='table') }} #}\nselect 1" + expect(modelSemantics(inlineConfig(sql)).materialized).toBe("incremental") + }) + + test("only columns compared to a listed slice var count", () => { + const sql = "select * from t where t.tenant_id = '{{ var(\"tenant\") }}' and currency = '{{ var('reporting_currency') }}'" + expect(varScopedColumns(sql, ["tenant"])).toEqual(["tenant_id"]) + expect(varScopedColumns(sql, [])).toEqual([]) + }) +}) + +describe("incremental change without a plan for existing rows", () => { + const delta = (added: string[]) => () => ({ added, removed: [], unknown: false }) + for (const dialect of ["snowflake", "trino"]) { + test(`a new column fires on ${dialect}; PR text naming a plan answers it`, async () => { + const changed = { dialect, newSql: INC("select id, ts, kind from src"), columnDelta: delta(["kind"]) } + const [f] = await incrementalFindings(input(changed)) + expect(f.body).toContain("`kind` is new: with `on_schema_change='ignore'` (the default), incremental runs don't add it") + expect(f.severity).toBe("suggestion") + for (const prText of ["Needs a --full-refresh on deploy", "No backfill needed."]) + expect(await rules({ ...changed, prText })).not.toContain("incremental-history-plan") + }) + } + + test("with `append_new_columns` the new column is added, and old rows get NULL", async () => { + const cfg = "materialized='incremental', unique_key='id', on_schema_change='append_new_columns'" + const [f] = await incrementalFindings( + input({ oldSql: INC("select id, ts from src", cfg), newSql: INC("select id, ts, kind from src", cfg), columnDelta: delta(["kind"]) }), + ) + expect(f.body).toContain("`kind` is new: rows built before this change get NULL unless backfilled") + }) + + test("column names are code spans: a newline, `@` or backtick inside can't break out", async () => { + const [f] = await incrementalFindings(input({ newSql: INC("select id, ts, x from src"), columnDelta: delta(["x\n\n@acme/data-eng ## `y"]) })) + expect(f.body).not.toContain("\n") + expect(f.body).toContain("``x @acme/data-eng ## `y`` is new") + }) + + test("a changed is_incremental() filter fires", async () => { + const oldSql = "{{ config(materialized='incremental', unique_key='id') }} select id, ts from src {% if is_incremental() %} where ts > (select max(ts) from {{ this }}) {% endif %}" + const newSql = oldSql.replace("where ts >", "where ts >=") + expect(await rules({ oldSql, newSql })).toContain("incremental-history-plan") + }) + + test("formatting-only edits, expression edits without new columns, config-only and new models don't fire", async () => { + expect(await rules({ newSql: INC("SELECT id ,\n ts\nFROM src") })).toHaveLength(0) + expect(await rules({ newSql: INC("select id, ts + 1 as ts from src") })).toHaveLength(0) + expect(await rules({ newSql: INC("select id, ts from src", "materialized='incremental', incremental_strategy='merge', unique_key='id', tags=['x']") })).toHaveLength(0) + expect(await rules({ file: { path: "models/marts/fct.sql", status: "added" }, oldSql: undefined, newSql: INC("select 2"), columnDelta: delta(["x"]) })).toHaveLength(0) + }) + + test("partition_by change needs a full refresh", async () => { + const cfg = (g: string) => `materialized='incremental', unique_key='id', partition_by={'field': 'd', 'granularity': '${g}'}` + expect(await rules({ oldSql: INC("select 1", cfg("day")), newSql: INC("select 1", cfg("month")) })).toContain("incremental-partition-change") + }) + + test("equivalent partition_by spellings are not a change", async () => { + const cfg = (p: string) => `materialized='incremental', unique_key='id', partition_by=${p}` + const same = async (a: string, b: string) => rules({ oldSql: INC("select 1", cfg(a)), newSql: INC("select 1", cfg(b)) }) + expect(await same("{'field': 'order_date', 'data_type': 'date'}", "{'data_type': 'date', 'field': 'order_date'}")).toEqual([]) + expect(await same("'order_date'", "['order_date']")).toEqual([]) + expect(await same("{'field': 'd', 'data_type': 'date'}", "{\n 'field': 'd',\n 'data_type': 'date',\n}")).toEqual([]) + expect(await same("['a', 'b']", "['a', 'b',]")).toEqual([]) + expect(await same("{'field': var('pfield'), 'data_type': 'date'}", "{'field': var('pfield'),'data_type': 'date'}")).toEqual([]) + const range = (i: string, end = "100") => `{'field': 'id', 'data_type': 'int64', 'range': {'start': 0, 'end': ${end}, 'interval': ${i}}}` + expect(await same(range("10"), range("'10'"))).toEqual([]) + // Real changes are still reported. + expect(await same(range("10"), range("10", "1000"))).toContain("incremental-partition-change") + expect(await same("{'field': 'd', 'granularity': 'day'}", "{'field': 'd', 'granularity': 'month'}")).toContain("incremental-partition-change") + expect(await same("['a', 'b']", "['b', 'a']")).toContain("incremental-partition-change") + }) + + test("partition_by moved from inline config to yml with the same value is not a change", async () => { + const withPart = "materialized='incremental', unique_key='id', partition_by={'field': 'd', 'granularity': 'day'}" + const without = "materialized='incremental', unique_key='id'" + const moved = { field: "d", granularity: "day" } + expect( + await rules({ oldSql: INC("select 1", withPart), newSql: INC("select 1", without), manifestConfig: { materialized: "incremental", partition_by: moved } }), + ).not.toContain("incremental-partition-change") + // Removed inline and not in yml either: the partitioning really changed. + expect( + await rules({ oldSql: INC("select 1", withPart), newSql: INC("select 1", without), manifestConfig: { materialized: "incremental" } }), + ).toContain("incremental-partition-change") + }) +}) + +describe("on_schema_change='fail'", () => { + const cfg = "materialized='incremental', unique_key='id', on_schema_change='fail'" + test("a changed column set fails the first incremental run", async () => { + const out = await incrementalFindings( + input({ oldSql: INC("select id from s", cfg), newSql: INC("select id, kind from s", cfg), columnDelta: () => ({ added: ["kind"], removed: [], unknown: false }) }), + ) + expect(out.map((f) => f.body).join()).toContain("adds `kind`") + }) + test("it replaces, not repeats, the history-plan finding", async () => { + const out = await rules({ oldSql: INC("select id from s", cfg), newSql: INC("select id, kind from s", cfg), columnDelta: () => ({ added: ["kind"], removed: [], unknown: false }) }) + expect(out).toEqual(["on-schema-change-fail"]) + }) + test("PR text mentioning a full refresh lowers it to a suggestion, never removes it", async () => { + const changed = { oldSql: INC("select id from s", cfg), newSql: INC("select id, kind from s", cfg), columnDelta: () => ({ added: ["kind"], removed: [], unknown: false }) } + for (const prText of [ + "Deploy with --full-refresh", + "Adds discount. No full refresh needed.", + "Do not full-refresh this model.", + "Please avoid --full-refresh; the table is 2TB.", + "## Checklist\n- [ ] full refresh required?", + ]) { + const out = await incrementalFindings(input({ ...changed, prText })) + expect(out.map((f) => [(f.evidence?.result as { rule: string }).rule, f.severity])).toEqual([["on-schema-change-fail", "suggestion"]]) + expect(out[0].body).toContain("The PR text mentions a full refresh: confirm it is planned for the deploy.") + } + const [plain] = await incrementalFindings(input(changed)) + expect(plain.severity).toBe("warning") + }) + test("a rule the project blocks on is never lowered by PR text", async () => { + const changed = { oldSql: INC("select id from s", cfg), newSql: INC("select id, kind from s", cfg), columnDelta: () => ({ added: ["kind"], removed: [], unknown: false }) } + const [f] = await incrementalFindings(input({ ...changed, prText: "No full refresh needed.", blockingRules: ["on_schema_change_fail"] })) + expect(f.severity).toBe("warning") + expect(f.body).not.toContain("confirm it is planned") + }) + test("unknown columns are listed as not fully verified, not reported", async () => { + const reasons: string[] = [] + const out = await rules({ + oldSql: INC("select id from s", cfg), + newSql: INC("select * from s", cfg), + columnDelta: () => ({ added: [], removed: [], unknown: true }), + abstain: (r) => reasons.push(r), + }) + expect(out).toEqual([]) + expect(reasons).toHaveLength(1) + }) + test("an unchanged column set is fine", async () => { + expect(await rules({ oldSql: INC("select id from s", cfg), newSql: INC("select id from s", cfg) })).not.toContain("on-schema-change-fail") + }) + test("a filter-only change is still reported as needing a history plan", async () => { + const oldSql = `{{ config(${cfg}) }} select id from s {% if is_incremental() %} where ts > (select max(ts) from {{ this }}) {% endif %}` + const newSql = oldSql.replace("where ts >", "where ts >=") + expect(await rules({ oldSql, newSql })).toEqual(["incremental-history-plan"]) + }) +}) + +describe("per-slice runs whose unique_key lacks the slice column", () => { + const sql = (key: string, strategy = "delete+insert") => + `{{ config(materialized='incremental', incremental_strategy='${strategy}', unique_key=${key}) }}\nselect event_id, tenant_id from src where tenant_id = '{{ var("tenant") }}'` + for (const dialect of ["snowflake", "postgres"]) { + test(`fires on ${dialect} for delete+insert and merge`, async () => { + const isNew = { file: { path: "models/marts/fct.sql", status: "added" as const }, oldSql: undefined, dialect, sliceVars: ["tenant"] } + const [di] = await incrementalFindings(input({ ...isNew, newSql: sql("'event_id'") })) + expect(di.body).toContain("deletes other slices' rows") + const [mg] = await incrementalFindings(input({ ...isNew, newSql: sql("'event_id'", "merge") })) + expect(mg.body).toContain("overwrites other slices' rows") + expect(await rules({ ...isNew, newSql: sql("['event_id', 'tenant_id']") })).toHaveLength(0) + expect(await rules({ ...isNew, sliceVars: [], newSql: sql("'event_id'") })).toHaveLength(0) + }) + } +}) + +describe("per-slice runs: default strategy and computed keys", () => { + const body = "select order_id, order_sk, tenant_id from src where tenant_id = '{{ var(\"tenant\") }}'" + const isNew = { file: { path: "models/marts/fct.sql", status: "added" as const }, oldSql: undefined, sliceVars: ["tenant"] } + const outputs = () => ["order_id", "order_sk", "tenant_id"] + test("no incremental_strategy with a unique_key runs the adapter's keyed default; unknown defaults stay silent", async () => { + const newSql = `{{ config(materialized='incremental', unique_key='order_id') }}\n${body}` + for (const [dialect, effect] of [["snowflake", "overwrites"], ["bigquery", "overwrites"], ["postgres", "deletes"], ["redshift", "deletes"]]) { + const [f] = await incrementalFindings(input({ ...isNew, dialect, newSql, outputColumns: outputs })) + expect(f.severity).toBe("warning") + expect(f.body).toContain(`${effect} other slices' rows`) + } + expect(await rules({ ...isNew, dialect: "databricks", newSql, outputColumns: outputs })).toEqual([]) + expect(await rules({ ...isNew, dialect: "duckdb", newSql, outputColumns: outputs })).toEqual([]) + expect(await rules({ ...isNew, dialectKnown: false, newSql, outputColumns: outputs })).toEqual([]) + }) + test("a computed or unlisted key is only a suggestion", async () => { + const cfg = (key: string) => `{{ config(materialized='incremental', incremental_strategy='delete+insert', unique_key=${key}) }}\n` + const hashed = cfg("'order_sk'") + "select order_id, md5(tenant_id || order_id) as order_sk, tenant_id from src where tenant_id = '{{ var(\"tenant\") }}'" + const sev = async (over: Partial) => (await incrementalFindings(input({ ...isNew, ...over }))).map((f) => f.severity) + expect(await sev({ newSql: hashed, outputColumns: outputs })).toEqual(["suggestion"]) + expect(await sev({ newSql: cfg("'order_sk'") + body, outputColumns: () => ["order_id", "tenant_id"] })).toEqual(["suggestion"]) + expect(await sev({ newSql: cfg("'order_sk'") + body, outputColumns: () => undefined })).toEqual(["suggestion"]) + expect(await sev({ newSql: cfg("\"tenant_id || '-' || order_id\"") + body, outputColumns: outputs })).toEqual(["suggestion"]) + expect(await sev({ newSql: cfg("'order_id'") + body, outputColumns: outputs })).toEqual(["warning"]) + const keyed = (item: string) => cfg("'order_sk'") + `select ${item} as order_sk, o.tenant_id from src o where o.tenant_id = '{{ var("tenant") }}'` + const sk = () => ["order_sk", "tenant_id"] + expect(await sev({ newSql: keyed("o.tenant_id || '-' || o.id"), outputColumns: sk })).toEqual(["suggestion"]) + expect(await sev({ newSql: keyed("case when o.tenant_id is null then o.id else o.tenant_id || o.id end"), outputColumns: sk })).toEqual(["suggestion"]) + expect(await sev({ newSql: keyed("o.id"), outputColumns: sk })).toEqual(["warning"]) + // An alias without `as`. + const bare = (item: string) => keyed(item).replace(" as order_sk", " order_sk") + expect(await sev({ newSql: bare("o.tenant_id || o.id"), outputColumns: sk })).toEqual(["suggestion"]) + expect(await sev({ newSql: bare("o.id"), outputColumns: sk })).toEqual(["warning"]) + }) +}) + +describe("non-atomic table rebuild", () => { + const tbl = (ote: string, contract = true) => + `{{ config(materialized='table', on_table_exists='${ote}'${contract ? ", contract={'enforced': true}" : ""}) }}\nselect 1 as id` + const isNew = { file: { path: "models/marts/fct.sql", status: "added" as const }, oldSql: undefined, dialect: "trino" } + test("trino: replace with an enforced contract, or drop; always a suggestion", async () => { + const [f] = await incrementalFindings(input({ ...isNew, newSql: tbl("replace") })) + expect(f.severity).toBe("suggestion") + expect(f.body).toContain("`create or replace table` and then `insert`") + const [e] = await incrementalFindings(input({ ...isNew, newSql: tbl("replace"), hasExposures: true })) + expect(e.severity).toBe("suggestion") + expect(e.body).toContain("this model has exposures") + expect((await incrementalFindings(input({ ...isNew, newSql: tbl("drop", false) })))[0].body).toContain("doesn't exist during each build") + }) + test("rename, replace without a contract, or another adapter: silent", async () => { + expect(await rules({ ...isNew, newSql: tbl("rename") })).toHaveLength(0) + expect(await rules({ ...isNew, newSql: tbl("replace", false) })).toHaveLength(0) + expect(await rules({ ...isNew, dialect: "snowflake", newSql: tbl("replace") })).toHaveLength(0) + }) +}) + +describe("snapshots", () => { + const snap = (cols: string, body = "select id, status from src") => + `{% snapshot s %}\n{{ config(unique_key='id', strategy='check', check_cols=${cols}) }}\n${body}\n{% endsnapshot %}` + const file = { path: "snapshots/s.sql", status: "modified" as const } + const rule = (f: ReturnType) => f.map((x) => (x.evidence?.result as { rule: string }).rule) + test("a check_cols change can record history that never happened", () => { + expect(rule(snapshotFindings({ file, model: "s", oldSql: snap("['status']"), newSql: snap("['status', 'amount']"), prText: "" }))).toEqual([ + "snapshot-tracking-change", + ]) + }) + test("check_cols moved from inline config to yml with the same value is not a tracking change", () => { + const inline = `{% snapshot s %}\n{{ config(unique_key='id', strategy='check', check_cols=['status']) }}\nselect id, status from src\n{% endsnapshot %}` + const bare = `{% snapshot s %}\n{{ config(unique_key='id') }}\nselect id, status from src\n{% endsnapshot %}` + const moved = snapshotFindings({ file, model: "s", oldSql: inline, newSql: bare, prText: "", manifestConfig: { strategy: "check", check_cols: ["status"] } }) + expect(rule(moved)).toEqual([]) + const changed = snapshotFindings({ file, model: "s", oldSql: inline, newSql: bare, prText: "", manifestConfig: { strategy: "check", check_cols: ["status", "amount"] } }) + expect(rule(changed)).toEqual(["snapshot-tracking-change"]) + }) + + test("equivalent check_cols spellings are not a tracking change", () => { + expect(rule(snapshotFindings({ file, model: "s", oldSql: snap("['status', 'amount']"), newSql: snap("['amount', 'status']"), prText: "" }))).toEqual([]) + expect(rule(snapshotFindings({ file, model: "s", oldSql: snap("['status', 'amount']"), newSql: snap("[\n 'status',\n 'amount',\n]"), prText: "" }))).toEqual([]) + const y = (cols: string) => `snapshots:\n - name: o\n config:\n strategy: check\n check_cols: ${cols}\n` + expect(snapshotYmlFindings({ path: "snapshots/_s.yml", status: "modified" }, y("[status, amount]"), y("[amount, status]"))).toEqual([]) + expect(snapshotYmlFindings({ path: "snapshots/_s.yml", status: "modified" }, y("[status]"), y("status"))).toEqual([]) + }) + + test("a yml with snapshots that does not parse is not fully verified", () => { + const ok = "snapshots:\n - name: o\n config:\n strategy: timestamp\n" + const broken = "snapshots:\n - name: o\n config:\n strategy: check\n check_cols: [a\n" + const reasons: string[] = [] + expect(snapshotYmlFindings({ path: "snapshots/_s.yml", status: "modified" }, ok, broken, (r) => reasons.push(r))).toEqual([]) + expect(reasons).toEqual(["the YAML could not be parsed, so its snapshot configs (`check_cols`, `strategy`) were not checked"]) + }) + + test("yml-defined snapshots (dbt 1.9+) are checked too", () => { + const y = (cols: string) => `snapshots:\n - name: orders_snap\n relation: source('raw', 'orders')\n config:\n unique_key: id\n strategy: check\n check_cols: ${cols}\n` + const yfile = { path: "snapshots/_snapshots.yml", status: "modified" as const } + expect(snapshotYmlFindings(yfile, y("[status]"), y("[status, amount]")).map((f) => f.title)).toEqual(["orders_snap: snapshot `check_cols` changed"]) + expect(snapshotYmlFindings(yfile, y("[status]"), y("[status]"))).toEqual([]) + }) + + test("a query change needs a plan; a new snapshot is fine", () => { + const changed = { file, model: "s", oldSql: snap("['status']"), newSql: snap("['status']", "select id, upper(status) as status from src") } + expect(rule(snapshotFindings({ ...changed, prText: "" }))).toEqual(["snapshot-logic-no-plan"]) + for (const prText of ["we will backfill", "No backfill needed."]) { + const [f] = snapshotFindings({ ...changed, prText }) + expect([(f.evidence?.result as { rule: string }).rule, f.severity]).toEqual(["snapshot-logic-no-plan", "suggestion"]) + expect(f.title).toBe("s: snapshot query changed: confirm the plan for history") + expect(f.body).toContain("confirm it covers this change") + } + const [blocked] = snapshotFindings({ ...changed, prText: "we will backfill", blockingRules: ["snapshot-logic-no-plan"] }) + expect([blocked.severity, blocked.title]).toEqual(["warning", "s: snapshot query changed without a plan for history"]) + expect(rule(snapshotFindings({ ...changed, newSql: snap("['status']", "SELECT id,\n status FROM src"), prText: "" }))).toEqual([]) + expect(snapshotFindings({ ...changed, file: { ...file, status: "added" }, prText: "" })).toEqual([]) + }) + + test("a query change on a timestamp snapshot, or one whose strategy is unknown, is silent", () => { + const ts = (body: string) => `{% snapshot s %}\n{{ config(unique_key='id', strategy='timestamp', updated_at='updated_at') }}\n${body}\n{% endsnapshot %}` + const add = { file, model: "s", prText: "" } + expect(rule(snapshotFindings({ ...add, oldSql: ts("select id, status, updated_at from src"), newSql: ts("select id, status, amount, updated_at from src") }))).toEqual([]) + const bare = (body: string) => `{% snapshot s %}\n${body}\n{% endsnapshot %}` + expect(rule(snapshotFindings({ ...add, oldSql: bare("select id from src"), newSql: bare("select id, amount from src") }))).toEqual([]) + // Strategy from the manifest (yml / dbt_project.yml). + expect( + rule(snapshotFindings({ ...add, oldSql: bare("select id from src"), newSql: bare("select id, amount from src"), manifestConfig: { strategy: "check" } })), + ).toEqual(["snapshot-logic-no-plan"]) + }) +}) + +describe("dedup ordered only by a load timestamp", () => { + const run = (line: string) => + detectModelPatterns({ path: "models/m.sql", status: "added", diff: `+${line}\n` }, line, DEFAULT_RUBRIC).filter( + (f) => (f.evidence?.result as { rule?: string })?.rule === "dedup_load_timestamp_only", + ) + test("load timestamps fire, as a suggestion", () => { + for (const col of ["loaded_at", "ingestion_timestamp", "src.load_ts", "_loaded_at"]) { + const f = run(`select *, row_number() over (partition by id order by ${col} desc) as rn from t`) + expect(f).toHaveLength(1) + expect(f[0].severity).toBe("suggestion") + } + }) + test("loader sync columns (the standard staging idiom) stay silent", () => { + for (const col of ["_fivetran_synced", "_airbyte_extracted_at", "_sdc_batched_at"]) + expect(run(`select *, row_number() over (partition by id order by ${col} desc) as rn from t`)).toHaveLength(0) + }) + test("a business timestamp, a tie-breaker, or no row_number: silent", () => { + expect(run("select *, row_number() over (partition by id order by updated_at desc) as rn from t")).toHaveLength(0) + expect(run("select *, row_number() over (partition by id order by loaded_at desc, seq desc) as rn from t")).toHaveLength(0) + expect(run("select *, rank() over (partition by id order by loaded_at) as rn from t")).toHaveLength(0) + }) +}) + +describe("end to end through the orchestrator", () => { + const runner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: false } + }, + async detectPii() { + return { columns: [] } + }, + async modelConfig() { + return { materialized: "incremental", unique_key: "id" } + }, + async columnLineage(sql: string) { + const m = /select\s+([\s\S]*?)\s+from/i.exec(sql) + return m ? m[1].split(",").map((c) => ({ source: `"src"."${c.trim()}"`, target: c.trim() })) : [] + }, + } as ReviewRunner + + // A jaffle-style model with an exposure and `on_schema_change='fail'`: the + // column sets come from the same parser on both sides. + const EXPLICIT = "with final as (select order_id, amount, 'web' as channel from orders) select order_id, amount, channel from final" + const STAR = "with final as (select order_id, amount, 'web' as channel from orders) select * from final" + const consumed = { + ...runner, + async modelConfig() { + return { materialized: "incremental", unique_key: "order_id", on_schema_change: "fail" } + }, + async modelConsumers() { + return { exposures: [{ name: "dash", type: "dashboard" }], contractEnforced: false, contractColumns: [] } + }, + } as ReviewRunner + const review = (oldSql: string, newSql: string) => + runReview({ + changedFiles: [{ path: "models/marts/fct.sql", status: "modified", diff: `-${oldSql}\n+${newSql}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns", "materialization", "lineage_breakage"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: consumed, + getContent: async (_f, side) => (side === "old" ? oldSql : newSql), + }) + const TITLE: Record = { + removed: "removed column(s) on a model with declared consumers", + fail: "`on_schema_change='fail'` with changed columns", + history: "incremental change without a plan for existing rows", + } + const ruleKeys = (env: Awaited>) => + Object.keys(TITLE).filter((k) => env.findings.some((f) => f.title.endsWith(TITLE[k]))) + + test("an explicit final list refactored to `select * from final` changes no columns", async () => { + const keys = ruleKeys(await review(EXPLICIT, STAR)) + expect(keys).not.toContain("removed") + expect(keys).not.toContain("fail") + }) + + test("`select * from final` refactored to an explicit list adds no columns", async () => { + const keys = ruleKeys(await review(STAR, EXPLICIT)) + expect(keys).not.toContain("history") + expect(keys).not.toContain("fail") + }) + + test("a real removal behind `select * from final` is still reported", async () => { + const env = await review(EXPLICIT, STAR.replace("'web' as channel", "'web' as channel_name").replace(", amount", "")) + const keys = ruleKeys(env) + expect(keys).toContain("removed") + expect(keys).toContain("fail") + expect(env.findings.find((f) => f.title.endsWith(TITLE.fail))!.body).toContain("removes `amount`, `channel`") + }) + + test("a side whose columns can't be listed is not fully verified, and does not block", async () => { + const env = await review(EXPLICIT, "select * from orders") + expect(ruleKeys(env)).not.toContain("fail") + const reasons = env.scope?.unverified?.filter((u) => u.kind === "abstained").map((u) => u.reason) ?? [] + expect(reasons.some((r) => r.includes("incremental column rules were not checked"))).toBe(true) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + }) + + test("a yml snapshot name cannot ping anyone or inject markdown into the summary", async () => { + const y = (strategy: string) => + `snapshots:\n - name: "orders_snap @acme/data-eng\\n\\n# Approved by \`x"\n relation: source('raw', 'orders')\n config:\n unique_key: id\n strategy: ${strategy}\n updated_at: updated_at\n` + const env = await runReview({ + changedFiles: [{ path: "snapshots/_s.yml", status: "modified", diff: "- strategy: timestamp\n+ strategy: check\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner, + getContent: async (_f, side) => y(side === "old" ? "timestamp" : "check"), + }) + expect(env.findings.some((f) => f.title.endsWith("snapshot `strategy` changed"))).toBe(true) + const md = renderSummary(env) + expect(md).toContain("@acme/data-eng") + // Outside code spans: no mention and no injected heading. + expect(outsideSpans(md)).not.toContain("@acme") + expect(md).not.toMatch(/^#+\s*Approved/m) + }) + + test("the same hostile yml snapshot name in three files cannot ping through the grouped bullet", async () => { + const y = (cols: string) => + `snapshots:\n - name: "a\`b\`@ping-me"\n relation: ref('orders')\n config:\n strategy: check\n check_cols: ${cols}\n` + const paths = ["snapshots/s1.yml", "snapshots/s2.yml", "snapshots/s3.yml"] + const env = await runReview({ + changedFiles: paths.map((path) => ({ path, status: "modified" as const, diff: "- check_cols: [status]\n+ check_cols: [status, amount]\n" })), + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner, + getContent: async (_f, side) => y(side === "old" ? "[status]" : "[status, amount]"), + }) + expect(env.findings.filter((f) => f.title.endsWith("snapshot `check_cols` changed"))).toHaveLength(3) + expect(outsideSpans(renderSummary(env))).not.toContain("@") + }) + + test("an incremental model whose materialization is set in yml (manifest) still gets the rule; findings never block", async () => { + const env = await runReview({ + changedFiles: [ + { path: "models/marts/fct.sql", status: "modified", diff: "-select id from src\n+select id, kind from src\n" }, + { path: "snapshots/s.sql", status: "modified", diff: "-check_cols=['a']\n+check_cols=['a', 'b']\n" }, + ], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner, + getContent: async (f, side) => + f.startsWith("snapshots/") + ? `{{ config(strategy='check', unique_key='id', check_cols=${side === "old" ? "['a']" : "['a', 'b']"}) }} select id, a, b from src` + : side === "old" + ? "select id from src" + : "select id, kind from src", + }) + const titles = env.findings.map((f) => f.title) + expect(titles).toContain("fct: incremental change without a plan for existing rows") + expect(titles.some((t) => t.startsWith("s: snapshot `check_cols` changed"))).toBe(true) + expect(env.findings.filter((f) => f.evidence?.tool === "dbt-semantics").every((f) => f.origin === "catalog")).toBe(true) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + }) +}) + +describe("no error text from these checks reaches the comment, the envelope or telemetry; the job log has it", () => { + // A unique string per run: if it shows up in public output, error text leaked. + const marker = () => ["leak", "marker", Math.random().toString(36).slice(2, 10)].join("-") + + /** Runs `fn` with stderr and telemetry captured. */ + async function captured(fn: () => Promise) { + const log: string[] = [] + const events: unknown[] = [] + const stderr = spyOn(process.stderr, "write").mockImplementation(((chunk: any) => { + log.push(String(chunk)) + return true + }) as any) + const track = spyOn(Telemetry, "track").mockImplementation(((e: unknown) => { + events.push(e) + }) as any) + try { + const env = await fn() + emitReviewRun({ invocation: "cli", durationMs: 1, sessionID: "", envelope: env }) + return { env, log: log.join(""), events: JSON.stringify(events) } + } finally { + stderr.mockRestore() + track.mockRestore() + } + } + + const base = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, + } + const snap = (cols: string) => `{% snapshot s %}\n{{ config(unique_key='id', strategy='check', check_cols=${cols}) }}\nselect id from src\n{% endsnapshot %}` + const snapshotReview = (runner: Partial, getContent: (f: string, side: "old" | "new") => Promise) => + runReview({ + changedFiles: [{ path: "snapshots/s.sql", status: "modified", diff: "-check_cols=['a']\n+check_cols=['a', 'b']\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: { ...base, ...runner } as ReviewRunner, + getContent, + }) + + const kinds: Record Promise; category: string }> = { + "the manifest config lookup fails": { + category: "engine_error", + run: async (m) => { + const spy = spyOn(manifestHelpers, "loadRawManifest").mockImplementation(() => { + throw new Error(`manifest said ${m}`) + }) + try { + const r = createDispatcherRunner({ manifestPath: path.join(path.sep, "nonexistent", "manifest.json") }) + expect(await r.modelConfig!("orders_snap")).toBeUndefined() + return buildEnvelope({ findings: [], tier: "full", mode: "gate", engineErrors: r.failures!() }) + } finally { + spy.mockRestore() + } + }, + }, + "a snapshot's review throws": { + category: "internal_error", + run: (m) => + snapshotReview( + { + async modelConfig() { + throw new Error(`config exploded ${m}`) + }, + }, + async (_f, side) => snap(side === "old" ? "['a']" : "['a', 'b']"), + ), + }, + } + for (const [kind, { run, category }] of Object.entries(kinds)) + test(kind, async () => { + const m = marker() + const { env, log, events } = await captured(() => run(m)) + const categories = [...(env.engineErrors ?? []), ...(env.scope?.unverified ?? [])].map((e: any) => e.category) + expect(categories).toContain(category) + expect(JSON.stringify(env)).not.toContain(m) + expect(renderSummary(env)).not.toContain(m) + expect(renderSummary(env, { maxChars: Infinity })).not.toContain(m) + expect(events).not.toContain(m) + expect(events.length).toBeGreaterThan(2) + expect(log).toContain(m) + expect(log).toContain(`altimate review: ${category} `) + }) + + test("a snapshot side that could not be read holds back approval with a fixed sentence", async () => { + const { env, log } = await captured(() => + snapshotReview({}, async (_f, side) => (side === "old" ? snap("['a']") : undefined)), + ) + expect(env.scope?.unverified).toEqual([ + { + path: "snapshots/s.sql", + kind: "failed", + category: "file_unreadable", + reason: "The head version of this file could not be read. See the job log for details.", + }, + ]) + expect(env.verdict).not.toBe("APPROVE") + expect(log).toContain("altimate review: file_unreadable file=snapshots/s.sql side=head") + }) + + test("a yml snapshot the YAML parser rejects is listed with a fixed sentence, never the parser's message", async () => { + const m = marker() + // The parser quotes the offending line in its message. + const broken = `snapshots:\n - name: s\n config: {strategy: check, check_cols: [${m}\n` + const ok = "snapshots:\n - name: s\n config:\n strategy: check\n check_cols: [a]\n" + const { env, events } = await captured(() => + runReview({ + changedFiles: [{ path: "snapshots/_s.yml", status: "modified", diff: `- check_cols: [a]\n+${m}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: base as ReviewRunner, + getContent: async (_f, side) => (side === "old" ? ok : broken), + }), + ) + const reasons = (env.scope?.unverified ?? []).map((u: any) => u.reason) + expect(reasons).toContain("the YAML could not be parsed, so its snapshot configs (`check_cols`, `strategy`) were not checked") + expect(JSON.stringify(env.scope) + JSON.stringify(env.engineErrors ?? null)).not.toContain(m) + expect(events).not.toContain(m) + }) +}) From 0983cb634654623ea2e97595d89731861d8ea85a Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 3 Dec 2026 19:59:08 +0530 Subject: [PATCH 06/39] feat(review): data tests that cannot do their job, parse-only column checks Flags tests that compare a model with itself, new tests that inherit a loosened threshold, loosened thresholds in `dbt_project.yml`, and dedup windows without a tiebreaker. Column rules read raw SQL when nothing is compiled and abstain on Jinja they cannot follow. Optional `dbt_prepare` action step builds head and base artifacts. Summary names are code spans. Co-Authored-By: Claude Fable 5.2 --- docs/docs/usage/dbt-pr-review.md | 46 +- github/review/action.yml | 104 ++++ ...timate-ingestion.yml => dbt-pr-review.yml} | 2 +- .../src/altimate/review/dbt-patterns.ts | 89 +++- .../opencode/src/altimate/review/format.ts | 19 +- .../src/altimate/review/orchestrate.ts | 204 ++++++-- .../src/altimate/review/test-adequacy.ts | 383 +++++++++++++++ .../test/altimate/review-action.test.ts | 203 ++++++++ .../review-incremental-semantics.test.ts | 298 ++++++++++++ .../altimate/review-test-adequacy.test.ts | 448 ++++++++++++++++++ .../skill/release-v0.8.5-adversarial.test.ts | 2 +- 11 files changed, 1737 insertions(+), 61 deletions(-) rename github/review/examples/{altimate-ingestion.yml => dbt-pr-review.yml} (97%) create mode 100644 packages/opencode/src/altimate/review/test-adequacy.ts create mode 100644 packages/opencode/test/altimate/review-action.test.ts create mode 100644 packages/opencode/test/altimate/review-test-adequacy.test.ts diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 1c4d1da087..e7747e60f0 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -218,13 +218,36 @@ jobs: | `target-base/compiled/…` | Compile the base ref into `target-base/` (below) | Equivalence proofs and column-breakage for modified models. | | `target/catalog.json` | `dbt docs generate` | Complete warehouse columns for column-lineage breakage. | -Compiling the base (optional, for equivalence and column-breakage): +The action can build these for you with `dbt_prepare` (off by default): + +```yaml + - uses: AltimateAI/altimate-code/github/review@main + with: + dbt_prepare: compile # none | compile | full + dbt_command: dbt # or "uv run dbt", "poetry run dbt" + dbt_profiles_dir: . # relative to project_dir +``` + +- **`compile`:** runs `dbt compile` on the head, then compiles the PR's merge-base + into `target-base/` in a temporary worktree. This enables equivalence and + column-breakage proofs. dbt needs a profile it can load, and many adapters + connect to the warehouse while compiling. The head is compiled into the + directory of `manifest_path`, and the review reads compiled SQL from there. + When `head` is set to a commit other than the checkout, or `base` or `head` + starts with `-` or `+` or contains `:`, preparation is skipped. +- **`full`:** also runs `dbt docs generate` for `catalog.json` (complete column + types). That needs warehouse credentials in the profile. +- A head or base compile that fails is a warning: the review still runs, and the + affected models are listed as not verified. + +To build them yourself, compile the **merge-base**, not the base branch's tip: ```yaml - name: Compile the base into target-base/ + env: + BASE_REF: ${{ github.base_ref }} run: | - # The review diffs against the merge-base, not the target branch tip. - git worktree add ../base "$(git merge-base "origin/${{ github.base_ref }}" HEAD)" + git worktree add ../base "$(git merge-base "origin/$BASE_REF" HEAD)" (cd ../base && dbt deps && dbt compile --target-path "$GITHUB_WORKSPACE/target-base") ``` @@ -255,7 +278,7 @@ ways, or neither (it self-disables, leaving a deterministic-only review): Always pass keys as repo **secrets**. Warehouse credentials are consumed by the `dbt compile` step (via your `profiles.yml`), **not** by the review step. A complete, copy-paste workflow lives at -[`github/review/examples/altimate-ingestion.yml`](https://github.com/AltimateAI/altimate-code/blob/main/github/review/examples/altimate-ingestion.yml). +[`github/review/examples/dbt-pr-review.yml`](https://github.com/AltimateAI/altimate-code/blob/main/github/review/examples/dbt-pr-review.yml). Re-pushing commits updates the same summary comment in place; fixed findings are dropped on the next run. `--post` targets **GitHub** PRs (it reads `GITHUB_TOKEN` / @@ -714,6 +737,21 @@ The deterministic rules group into four families: - **dbt unit tests.** A unit test whose `given` inputs are all `rows: []` is reported: it either never tests the model's logic, or expects rows the model has nothing to build from. +- **Data tests that can't do their job.** These are checked on tests added or + changed in the PR. A test moved to another yml, migrated to `arguments:`, or + given new `config` is not new. A yml or `dbt_project.yml` that does not parse + is listed as not fully verified (the parser's message is not shown); a changed + `dbt_project.yml` that cannot be read holds back approval like any unreadable + file: + - a test that compares a model with itself (`dbt_utils.equality` or + `equal_rowcount` against its own `ref`, or a `relationships` test pointing + at its own column) passes by construction. A comparison that filters or + groups its two sides differently (`row_condition`, `group_by`, `where`), + or one on a model with several versions, is not reported; + - new tests that inherit `severity: warn` from `dbt_project.yml` report + failures without failing the build, and new tests that inherit an + `error_if` threshold fail it only above that threshold; + - a `dbt_project.yml` change that loosens those thresholds for a whole folder. - **Incremental and snapshot semantics.** Config is read from the manifest (project, yml and inline, as dbt merges them) with the head's inline `{{ config() }}` on top. Formatting-only edits never count as a change. A diff --git a/github/review/action.yml b/github/review/action.yml index 09c4bc1538..22a83502be 100644 --- a/github/review/action.yml +++ b/github/review/action.yml @@ -31,6 +31,17 @@ inputs: description: "Post the verdict to the PR (summary comment + inline review)." required: false default: "true" + dbt_prepare: + description: "Build the dbt artifacts the full review uses before reviewing. `none` (default): you build them in earlier steps. `compile`: `dbt compile` on the head, and on the PR's merge-base into `target-base/` (equivalence and lineage proofs). `full`: also `dbt docs generate` for `catalog.json` (complete column types). `compile` needs a profile dbt can load, and many adapters connect while compiling; `full` needs warehouse credentials. A failed compile is a warning and the review runs without that side's artifacts." + required: false + default: "none" + dbt_command: + description: "How to invoke dbt for `dbt_prepare`, e.g. `dbt`, `uv run dbt`, `poetry run dbt`. Split on whitespace (no shell quoting)." + required: false + default: "dbt" + dbt_profiles_dir: + description: "`--profiles-dir` for `dbt_prepare`, relative to `project_dir`. Empty = dbt's default lookup." + required: false signing_key: description: "Optional HMAC key to sign the verdict envelope (ALTIMATE_REVIEW_SIGNING_KEY)." required: false @@ -167,6 +178,99 @@ runs: echo "Advisory lane: no model/credentials provided — running deterministic-only." fi + # Optional: build the head and base artifacts the full-tier review needs. + # Inputs are passed as ENV, never interpolated into the script. + - name: Prepare dbt artifacts + if: inputs.dbt_prepare != 'none' + shell: bash + env: + IN_PREPARE: ${{ inputs.dbt_prepare }} + IN_DBT: ${{ inputs.dbt_command }} + IN_PROFILES: ${{ inputs.dbt_profiles_dir }} + IN_PROJECT_DIR: ${{ inputs.project_dir }} + IN_MANIFEST: ${{ inputs.manifest_path }} + IN_BASE: ${{ inputs.base }} + IN_HEAD: ${{ inputs.head }} + EVENT_BASE: ${{ github.event.pull_request.base.ref }} + run: | + set -euo pipefail + PROJECT="$(cd "${IN_PROJECT_DIR:-.}" && pwd -P)" + # Only a project inside this checkout is prepared (and cleaned). + WORKSPACE="$(cd "${GITHUB_WORKSPACE:-.}" && pwd -P)" + if ! git -C "$PROJECT" rev-parse --show-toplevel >/dev/null 2>&1 || [[ "$PROJECT/" != "$WORKSPACE/"* ]]; then + echo "::warning::project_dir ($IN_PROJECT_DIR) is not inside the checked-out repository; skipping dbt_prepare." + exit 0 + fi + # A stale target-base/ from an earlier run must not stand in for a base + # compile this run skips or fails, so it goes before any other exit. + rm -rf "$PROJECT/target-base" + # The ref rules `altimate review` applies to --base/--head: a leading `-` + # or `+`, or a `:`, would be read by git as an option or a refspec. + for REF in "${IN_BASE:-}" "${IN_HEAD:-}"; do + if [[ "$REF" == -* || "$REF" == +* || "$REF" == *:* ]]; then + echo "::warning::base and head must be plain git refs (no leading - or +, no :); skipping dbt_prepare." + exit 0 + fi + done + case "$IN_PREPARE" in compile|full) ;; *) echo "::error::dbt_prepare must be none, compile or full (got '$IN_PREPARE')"; exit 1 ;; esac + read -ra DBT <<< "$IN_DBT" + if [[ ${#DBT[@]} -eq 0 ]]; then echo "::error::dbt_command is empty; set it to how dbt is invoked (e.g. dbt)."; exit 1; fi + # Artifacts are built from the checkout: a different `head` would be reviewed + # against another commit's compiled SQL, so skip preparing instead. + if [[ -n "${IN_HEAD:-}" && "$(git rev-parse --verify -q "$IN_HEAD^{commit}" || true)" != "$(git rev-parse HEAD)" ]]; then + echo "::warning::head ($IN_HEAD) is not the checked-out commit; skipping dbt_prepare. Check out the head to build its artifacts." + exit 0 + fi + REL="$(git -C "$PROJECT" rev-parse --show-prefix)" + PROFILES=() + [[ -n "${IN_PROFILES:-}" ]] && PROFILES=(--profiles-dir "$(cd "$PROJECT" && cd "$IN_PROFILES" && pwd)") + build() { # $1 = project dir, $2 = target path + ( cd "$1" || exit 1 + [[ -f packages.yml || -f dependencies.yml ]] && "${DBT[@]}" deps ${PROFILES[@]+"${PROFILES[@]}"} + "${DBT[@]}" compile --target-path "$2" ${PROFILES[@]+"${PROFILES[@]}"} ) + } + # The head goes next to the manifest (`manifest_path`); the review reads + # compiled SQL from that directory's `compiled/` first. + MANIFEST="${IN_MANIFEST:-target/manifest.json}" + [[ "$MANIFEST" == /* ]] || MANIFEST="$PROJECT/$MANIFEST" + TARGET="$(dirname "$MANIFEST")" + echo "Compiling the head…" + if ! build "$PROJECT" "$TARGET"; then + echo "::warning::The head compile failed (dbt may need a warehouse connection to compile); the review runs without compiled artifacts." + exit 0 + fi + if [[ "$IN_PREPARE" == "full" ]]; then + echo "Generating catalog.json…" + ( cd "$PROJECT" && "${DBT[@]}" docs generate --target-path "$TARGET" ${PROFILES[@]+"${PROFILES[@]}"} ) || + echo "::warning::dbt docs generate failed; continuing without catalog.json." + fi + # The base side: the PR's merge-base, compiled into target-base/. + BASE="${IN_BASE:-$EVENT_BASE}" + BASE="${BASE#origin/}" + if [[ -z "$BASE" ]]; then echo "::warning::No base branch known; skipping the base compile."; exit 0; fi + git fetch --no-tags origin "+refs/heads/$BASE:refs/remotes/origin/$BASE" >/dev/null 2>&1 || true + MB="$(git merge-base "origin/$BASE" HEAD 2>/dev/null || git merge-base "$BASE" HEAD 2>/dev/null || true)" + if [[ -z "$MB" && "$(git rev-parse --is-shallow-repository)" == "true" ]]; then + git fetch --no-tags --deepen=1000 origin "+refs/heads/$BASE:refs/remotes/origin/$BASE" "$(git rev-parse HEAD)" >/dev/null 2>&1 || true + MB="$(git merge-base "origin/$BASE" HEAD 2>/dev/null || true)" + fi + if [[ -z "$MB" ]]; then echo "::warning::Could not find the merge-base with $BASE; skipping the base compile."; exit 0; fi + WT="$RUNNER_TEMP/altimate-review-base" + trap 'git worktree remove --force "$WT" >/dev/null 2>&1 || true' EXIT + git worktree add --detach "$WT" "$MB" >/dev/null || { echo "::warning::Could not check out the base; skipping the base compile."; exit 0; } + # A project the PR adds or moves has no base side to compile. + if [[ ! -f "$WT/$REL/dbt_project.yml" ]]; then + echo "::warning::The merge-base has no dbt project at this path; skipping the base compile." + exit 0 + fi + # A profiles.yml generated into the project dir at runtime is untracked, so + # the base worktree lacks it. + if [[ ${#PROFILES[@]} -eq 0 && -f "$PROJECT/profiles.yml" && ! -f "$WT/$REL/profiles.yml" ]]; then + cp "$PROJECT/profiles.yml" "$WT/$REL/profiles.yml" + fi + echo "Compiling the base ($BASE @ ${MB:0:12})…" + build "$WT/$REL" "$PROJECT/target-base" || echo "::warning::The base compile failed; equivalence will be marked unverified." + - name: Run dbt PR review shell: bash # Inputs are passed as ENV (data), never interpolated into the command — diff --git a/github/review/examples/altimate-ingestion.yml b/github/review/examples/dbt-pr-review.yml similarity index 97% rename from github/review/examples/altimate-ingestion.yml rename to github/review/examples/dbt-pr-review.yml index dc52867909..799d424424 100644 --- a/github/review/examples/altimate-ingestion.yml +++ b/github/review/examples/dbt-pr-review.yml @@ -1,4 +1,4 @@ -# Example: drop-in dbt PR review for a dbt repo (e.g. altimate-ingestion). +# Example: drop-in dbt PR review for a dbt repo. # Copy to the target repo as `.github/workflows/dbt-pr-review.yml` and adjust the # dbt adapter + profiles/secrets to match the warehouse. # diff --git a/packages/opencode/src/altimate/review/dbt-patterns.ts b/packages/opencode/src/altimate/review/dbt-patterns.ts index 52fbf92c20..82e17e8cd3 100644 --- a/packages/opencode/src/altimate/review/dbt-patterns.ts +++ b/packages/opencode/src/altimate/review/dbt-patterns.ts @@ -214,15 +214,80 @@ const detectNotIn: Detector = (c) => { }) } +/** Head-side line numbers of the added lines; undefined when the diff has no hunk headers. */ +function addedLineNumbers(diff: string | undefined): Set | undefined { + if (!diff || !/^@@ /m.test(diff)) return undefined + const out = new Set() + let right = 0 + let inHunk = false + for (const line of diff.split("\n")) { + const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line) + if (h) { + right = Number(h[1]) + inHunk = true + continue + } + if (!inHunk || line.startsWith("\\")) continue + if (line.startsWith("+")) out.add(right++) + else if (line.startsWith(" ") || line === "") right++ + else if (!line.startsWith("-")) inHunk = false + } + return out +} + +/** + * `row_number() over (…)` windows in the model, read from the whole file so a + * window split across lines is seen whole. A window counts as part of the + * change when one of the PR's added lines falls inside its line span (by text + * only when the diff carries no hunk headers, and then only for added lines + * that themselves hold window syntax). + */ +function dedupWindows(c: Ctx): Array<{ spec: string; text: string }> { + // Comments blanked with newlines kept, so offsets map to head line numbers. + const sql = c.newSql.replace(/\/\*[\s\S]*?\*\/|--[^\n]*|\{#[\s\S]*?#\}/g, (m) => m.replace(/[^\n]/g, " ")) + const lineAt = (offset: number) => sql.slice(0, offset).split("\n").length + // An added line that is blank once comments are gone (a new `-- note` inside + // an existing window) does not touch the window. + const lines = sql.split("\n") + const hunkLines = addedLineNumbers(c.file.diff) + const addedLines = hunkLines && new Set([...hunkLines].filter((n) => (lines[n - 1] ?? "").trim() !== "")) + // Text fallback (diff without hunk headers): only added lines that are part + // of a window spec can touch one; a bare identifier elsewhere never does. + const squash = (t: string) => t.replace(/\s+/g, " ").trim() + const added = c.added + .map((l) => squash(stripComments(l))) + .filter((l) => l.length >= 3 && /\b(row_number|over|partition\s+by|order\s+by)\b/i.test(l)) + const out: Array<{ spec: string; text: string }> = [] + for (const m of sql.matchAll(/row_number\s*\(\s*\)\s*over\s*\(/gi)) { + const open = m.index! + m[0].length - 1 + let depth = 0 + let close = -1 + for (let i = open; i < sql.length; i++) { + if (sql[i] === "(") depth++ + else if (sql[i] === ")" && --depth === 0) { + close = i + break + } + } + if (close < 0) continue + const text = sql.slice(m.index!, close + 1) + const touched = addedLines + ? [...addedLines].some((n) => n >= lineAt(m.index!) && n <= lineAt(close)) + : added.some((l) => squash(text).includes(l) || l.includes(squash(text))) + if (!touched) continue + out.push({ spec: sql.slice(open + 1, close).replace(/\s+/g, " ").trim(), text: text.replace(/\s+/g, " ") }) + } + return out +} + // 9. Dedup via ROW_NUMBER()/QUALIFY whose ORDER BY has no unique tiebreaker. const detectDedupTie: Detector = (c) => { - const hit = c.added.find((l) => /row_number\s*\(\s*\)\s*over\s*\(/i.test(stripComments(l))) - if (!hit) return null // Only flag dedup with NO ORDER BY — that is unambiguously non-deterministic. // A present ORDER BY (even single-column) is the developer's deterministic // choice and the dbt-recommended pattern; warning "it might not be unique" // on every dedup is noise (false positives on the common, correct case). - if (/order\s+by/i.test(stripComments(hit))) return null + const hit = dedupWindows(c).find((w) => !/order\s+by/i.test(w.spec)) + if (!hit) return null return makeFinding({ severity: "warning", category: "dedup", @@ -233,7 +298,7 @@ const detectDedupTie: Detector = (c) => { file: c.file.path, model: c.model, confidence: "high", - evidence: { tool: "dbt-patterns", result: { rule: "dedup_no_tiebreaker", line: hit.trim() } }, + evidence: { tool: "dbt-patterns", result: { rule: "dedup_no_tiebreaker", line: hit.text } }, ruleKey: "dedup:no-tiebreaker", }) } @@ -246,11 +311,8 @@ const detectDedupTie: Detector = (c) => { const LOAD_TS_RE = /^(_?(ingest(ion|ed)?|load(ed)?|etl|extract(ed)?|batch)(_at|_ts|_time|_timestamp|_date|_dt)|_?(ingestion|load|etl|batch)_timestamp|_loaded_at)$/i const detectDedupLoadTimestamp: Detector = (c) => { - for (const line of c.added) { - const s = stripComments(line) - const m = /row_number\s*\(\s*\)\s*over\s*\(([^)]*)\)/i.exec(s) - if (!m) continue - const order = /order\s+by\s+(.+)$/i.exec(m[1])?.[1] + for (const w of dedupWindows(c)) { + const order = /order\s+by\s+(.+)$/i.exec(w.spec)?.[1] if (!order) continue const keys = order.split(",").map((k) => k.trim().replace(/\s+(asc|desc)\b.*$/i, "").replace(/\s+nulls\s+(first|last)$/i, "")) if (keys.length !== 1) continue @@ -266,7 +328,7 @@ const detectDedupLoadTimestamp: Detector = (c) => { file: c.file.path, model: c.model, confidence: "high", - evidence: { tool: "dbt-patterns", result: { rule: "dedup_load_timestamp_only", line: line.trim() } }, + evidence: { tool: "dbt-patterns", result: { rule: "dedup_load_timestamp_only", line: w.text } }, ruleKey: "dedup:load-timestamp-only", }) } @@ -1145,7 +1207,7 @@ function extractGrainKeyGaps(doc: unknown): GrainKeyGap[] { mm.contract && typeof mm.contract === "object" ? (mm.contract as Record) : undefined const contractEnforced = cfgContract?.enforced === true || topContract?.enforced === true - // Coverage per column, split by mechanism (per codex R20 S1 review): + // Coverage per column, split by mechanism: // - constraint coverage counts ONLY when `contract.enforced == true`. // On non-contracted models, `constraints: [{type: not_null}]` is // documentation-only and not enforced by the database. Requiring @@ -1220,8 +1282,7 @@ function extractGrainKeyGaps(doc: unknown): GrainKeyGap[] { // Find grain declarations in this model's model-level tests / data_tests. // Restrict to `unique_combination_of_columns` and - // `dbt_utils.unique_combination_of_columns` exactly (per codex R20 S1 - // review) — `endsWith` would over-match `not_unique_combination_of_columns` + // `dbt_utils.unique_combination_of_columns` exactly — `endsWith` would over-match `not_unique_combination_of_columns` // and third-party macros that share the suffix. // Supports both dbt shapes: // pre-1.9: `- dbt_utils.unique_combination_of_columns: {combination_of_columns: [...]}` @@ -1405,7 +1466,7 @@ export function detectSchemaYmlPatterns( // don't collapse to one removal (MINOR #4). Strip it for display; // retain the internal `\x02` separator in `testTag` for the ruleKey // — a colon-joined form would collide when either arg contains `:` - // (e.g. `to='a:b'` vs `field='b:c'`, codex R20 review minor). + // (e.g. `to='a:b'` vs `field='b:c'`). // ruleKey is hashed for fingerprinting; control chars survive. const [test, tagPayload] = testField.split("\x01") const testTag = tagPayload ?? "" diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 1929eb891f..ca05e921f4 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -208,10 +208,14 @@ function clip(text: string, max: number): string { return `${cut.replace(/\s+\S*$/, "") || cut}…` } -/** Backticked names blanked, so the same rule on different models/columns +/** A code span of any fence length: the opening run, then text up to the next + * run of exactly that length (as `codeSpan` writes them). */ +const CODE_SPAN = /(? m[1]).filter((v) => !own.has(v)) + // `codeSpan` pads a value that starts or ends with a backtick by one space. + const values = [...`${f.title} ${f.body}`.matchAll(CODE_SPAN)] + .map((m) => (m[1].length > 1 && /^ [\s\S]* $/.test(m[2]) ? m[2].slice(1, -1) : m[2])) + .filter((v) => !own.has(v)) return [...new Set(values)] } @@ -304,7 +311,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou // not stop the shorter names after it from being listed. const listed = takeWhole( names - .map((n) => `\`${n}\``) + .map((n) => codeSpan(n)) .filter((n) => n.length <= BULLET_NAMES_MAX) .slice(0, 8), BULLET_NAMES_MAX, @@ -327,7 +334,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou // the count of the rest. const entries = values .slice(0, 8) - .map(({ f, v }) => `\`${f.model ?? f.file}\`: ${v.map((x) => `\`${x}\``).join(", ") || "—"}`) + .map(({ f, v }) => `${codeSpan(f.model ?? f.file)}: ${v.map((x) => codeSpan(x)).join(", ") || "—"}`) const kept = takeWhole(entries, BULLET_BODY_MAX - body.length, " · ") const rest = values.length - kept.length const detail = hasDetail ? ` ${kept.join(" · ")}${rest ? `${kept.length ? " " : ""}(+${rest} more)` : ""} \n` : "" @@ -343,7 +350,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou for (const f of g) { const loc = f.file + (f.startLine ? `:${f.startLine}` : "") out.push({ - text: `- **${titleOf(f.title)}** \n ${bodyOf(oneLine(f.body))} \n \`${loc}\`${f.degraded ? " · _unverified_" : ""} · ${f.category}`, + text: `- **${titleOf(f.title)}** \n ${bodyOf(oneLine(f.body))} \n ${codeSpan(loc)}${f.degraded ? " · _unverified_" : ""} · ${f.category}`, count: 1, }) } diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index e88744832a..4f45c48516 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -50,6 +50,7 @@ import { } 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, snapshotFindings, snapshotYmlFindings } from "./incremental-semantics" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult } from "./ai-review" import { hasInternalFailure, reportFailure } from "./failure" @@ -703,20 +704,30 @@ function outputColumns(sql: string): Set | undefined { } /** 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. */ + * 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 } = ctx - if (!engineNewSql || file.status === "deleted") return none - const current = outputColumns(engineNewSql) + 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 (!hasOldSide(file)) return { added: [...current], removed: [], unknown: false } - // No base SQL for the engine (not compiled, or unreadable): that gap is - // already recorded for the file, under its own reason. - if (!engineOldSql) return { ...unknown, baseMissing: true } - const before = outputColumns(engineOldSql) - if (!before) 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)), @@ -724,6 +735,93 @@ function columnDelta(ctx: ModelContext): { added: string[]; removed: string[]; u } } +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, " ")) @@ -1858,9 +1956,8 @@ export async function runReview(input: OrchestrateInput): Promise f.kind === "schema_yml") + const abstainOn = (file: { path: string }) => (reason: string) => + unverified.push({ path: file.path, reason, kind: "abstained" }) if (schemaFiles.length) { - const schemaFindingSets = await Promise.all( + // The head's dbt_project.yml (test thresholds inherited by new tests), read once. + const projectYmlPath = `${input.layout?.root ? `${input.layout.root.replace(/\/$/, "")}/` : ""}dbt_project.yml` + const projectYml = await Promise.resolve(getContent?.(projectYmlPath, "new")).catch(() => undefined) + const contents = await Promise.all( schemaFiles.map(async (file) => { try { const oldRef = file.oldPath ?? file.path @@ -2393,31 +2495,63 @@ export async function runReview(input: OrchestrateInput): Promise - unverified.push({ path: file.path, reason, kind: "abstained" }), - ), - ] + return { file, oldContent, newContent } } catch (err) { - // One malformed schema file degrades that file only. - failedFile(file, err) - return [] as Finding[] + return { file, err } } }), ) - for (const findings of schemaFindingSets) all.push(findings) + // 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 }), + // 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) }), + ]) + } 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 + 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 --git a/packages/opencode/src/altimate/review/test-adequacy.ts b/packages/opencode/src/altimate/review/test-adequacy.ts new file mode 100644 index 0000000000..5b676b7363 --- /dev/null +++ b/packages/opencode/src/altimate/review/test-adequacy.ts @@ -0,0 +1,383 @@ +import YAML from "yaml" +import { makeFinding, type Finding } from "./finding" +import type { ChangedFile, DbtProjectLayout } from "./diff-filter" +import { codeSpan } from "./format" + +/** + * Data tests that cannot do their job, found from yml alone (any adapter): + * - a test that compares a model with itself (`dbt_utils.equality` / + * `equal_rowcount` against its own `ref`, or a `relationships` test pointing + * at its own column) passes by construction; + * - tests added in the PR that inherit `severity: warn` from `dbt_project.yml` + * never fail the build, and ones that inherit an `error_if` threshold fail it + * only above that threshold; + * - a PR that loosens those thresholds in `dbt_project.yml` weakens every test + * under that path. + * Only tests added or changed in the PR are checked. Every name and value from + * the repository is printed as a code span. + */ + +interface TestRef { + entity: string + column?: string + test: string + args: Record + /** The model's `versions:` (`v` values), when it is versioned. */ + versions?: string[] +} + +/** A name or value from the repository as a code span that a backtick, `@`, + * `#` or a control character inside cannot break out of. */ +const span = (x: unknown) => codeSpan(String(x).replace(/[\u0000-\u001f\u007f\s]+/g, " ").trim()) +const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/ + +/** Test config keys: they change how a test is run, not which test it is. */ +const CONFIG_KEYS = new Set([ + "config", + "severity", + "error_if", + "warn_if", + "where", + "limit", + "store_failures", + "store_failures_as", + "fail_calc", + "enabled", + "tags", + "meta", + "alias", + "schema", + "database", +]) + +const SELF_COMPARE = new Set([ + "equality", + "equal_rowcount", + "cardinality_equality", + "expect_table_row_count_to_equal_other_table", + "expect_table_aggregation_to_equal_other_table", +]) + +function parse(text?: string): any { + if (!text) return undefined + try { + return YAML.parse(text) + } catch { + return undefined + } +} + +function testsOf(doc: any): TestRef[] { + const out: TestRef[] = [] + const read = (list: unknown, entity: string, column?: string) => { + if (!Array.isArray(list)) return + for (const t of list) { + if (typeof t === "string") out.push({ entity, column, test: t, args: {}, versions }) + else if (t && typeof t === "object") { + const [k] = Object.keys(t) + const args = (t as any)[k] + if (k) out.push({ entity, column, test: k, args: args && typeof args === "object" ? args : {}, versions }) + } + } + } + let versions: string[] | undefined + for (const group of ["models", "snapshots", "seeds"]) { + for (const e of Array.isArray(doc?.[group]) ? doc[group] : []) { + if (typeof e?.name !== "string") continue + versions = Array.isArray(e.versions) ? e.versions.map((v: any) => String(v?.v ?? v)) : undefined + read(e.data_tests ?? e.tests, e.name) + for (const c of Array.isArray(e.columns) ? e.columns : []) + if (typeof c?.name === "string") read(c.data_tests ?? c.tests, e.name, c.name) + } + } + return out +} + +/** JSON with object keys sorted, so key order in the yml does not matter. */ +const stable = (v: unknown): string => + Array.isArray(v) + ? `[${v.map(stable).join(",")}]` + : v && typeof v === "object" + ? `{${Object.keys(v) + .sort() + .map((k) => `${JSON.stringify(k)}:${stable((v as any)[k])}`) + .join(",")}}` + : JSON.stringify(v) + +/** Which test this is: dbt 1.10's `arguments:` read as plain args, and config + * (`config:`, `severity`, `where` …) left out, so a migrated, reformatted or + * reconfigured test keeps its identity. */ +const key = (t: TestRef) => { + const { arguments: nested, ...rest } = t.args ?? {} + const args: Record = { ...(nested && typeof nested === "object" ? nested : {}), ...rest } + for (const k of CONFIG_KEYS) delete args[k] + return `${t.entity}|${t.column ?? ""}|${t.test}|${stable(args)}` +} + +/** Identity keys of every test a yml declares (empty when it does not parse). */ +export function testKeys(text?: string): Set { + return new Set(testsOf(parse(text)).map(key)) +} + +const arg = (t: TestRef, name: string) => t.args?.[name] ?? t.args?.arguments?.[name] +const shortName = (test: string) => test.split(".").pop()!.toLowerCase() +const squashed = (v: unknown) => (v === undefined || v === null ? "" : stable(v).replace(/\s+/g, "").toLowerCase()) + +/** How `v` refers to `entity`: `true` for `ref('entity')`, the pinned version + * for `ref('entity', v=2)`, `false` otherwise. */ +function refTo(v: unknown, entity: string): boolean | string { + if (typeof v !== "string") return false + const name = entity.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + const m = new RegExp(`ref\\(\\s*['"]${name}['"]\\s*(?:,\\s*(?:v|version)\\s*=\\s*['"]?([\\w.]+)['"]?\\s*)?\\)`).exec(v) + return m ? (m[1] ?? true) : false +} + +/** A reference from a test on `t.entity` back to the same relation: an + * unversioned model by plain `ref`; a model with a single version by plain + * `ref` or one pinning that version. A model-level test runs once per version, + * so with several versions any ref compares different relations. */ +function refsSelf(t: TestRef, v: unknown): boolean { + const ref = refTo(v, t.entity) + if (!t.versions) return ref === true + return t.versions.length === 1 && (ref === true || ref === t.versions[0]) +} + +/** A same-model comparison that filters or groups its two sides differently + * (`row_condition` / `compare_row_condition`, `group_by` / `compare_group_by`) + * or filters one side with `where` (dbt wraps only `model` in it) does real work. */ +function sidesDiffer(t: TestRef): boolean { + if (squashed(arg(t, "row_condition")) !== squashed(arg(t, "compare_row_condition"))) return true + if (squashed(arg(t, "group_by")) !== squashed(arg(t, "compare_group_by"))) return true + return arg(t, "where") !== undefined || t.args?.config?.where !== undefined +} + +function finding(file: ChangedFile, model: string | undefined, rule: string, severity: Finding["severity"], title: string, body: string, extra = ""): Finding { + return makeFinding({ + severity, + category: "test_coverage", + title, + body, + file: file.path, + model, + confidence: "high", + evidence: { tool: "test-adequacy", result: { rule } }, + ruleKey: `test_coverage:${rule}${extra}`, + }) +} + +/** + * Failing rows an `error_if` condition tolerates: `!= 0` / `> 0` → 0, `> 10` → 10, + * `>= 10` → 9. Undefined when the condition isn't a simple bound. + */ +function allowedFailures(cond: string | undefined): number | undefined { + const m = cond ? /^(!=|<>|>=|>)\s*(\d+)$/.exec(cond.trim()) : null + if (!m) return undefined + const n = Number(m[2]) + if (m[1] === ">=") return Math.max(0, n - 1) + if (m[1] === ">") return n + return n === 0 ? 0 : undefined +} + +/** `+severity` / `+error_if` / `+warn_if` (with or without `+`) on one config node. */ +function thresholds(node: any): { severity?: string; error_if?: string; warn_if?: string } { + if (!node || typeof node !== "object") return {} + const get = (k: string) => (node[`+${k}`] ?? node[k]) as unknown + const str = (v: unknown) => (typeof v === "string" ? v.trim().toLowerCase() : undefined) + return { severity: str(get("severity")), error_if: str(get("error_if")), warn_if: str(get("warn_if")) } +} + +/** + * Effective test thresholds for a yml under `segments` (folders below the model + * path), walking `data_tests:` (or `tests:`) from the top, through the project + * name, down the folders; deeper levels override. `path` is where the effective + * value was set. dbt matches a top-level key against package names, so any key + * other than the project's own name scopes a package and is not walked. + */ +export function inheritedThresholds(projectYml: any, segments: string[]): { severity?: string; error_if?: string; path: string[] } { + const tree = projectYml?.data_tests ?? projectYml?.tests + if (!tree || typeof tree !== "object") return { path: [] } + const name = projectYml?.name + const chain = typeof name === "string" && name ? [name, ...segments] : [] + const levels: Array<[string[], any]> = [[[], tree]] + let node = tree + for (let i = 0; i < chain.length; i++) { + node = node?.[chain[i]] + if (!node || typeof node !== "object") break + levels.push([chain.slice(0, i + 1), node]) + } + const eff: { severity?: string; error_if?: string } = {} + let path: string[] = [] + for (const [at, n] of levels) { + const t = thresholds(n) + if (t.severity) eff.severity = t.severity + if (t.error_if) eff.error_if = t.error_if + if (t.severity || t.error_if) path = at.length ? at : ["(all tests)"] + } + return { ...eff, path } +} + +/** Folders of a yml below its resource path (e.g. `models/marts/x.yml` → `["marts"]`, `seeds/x.yml` → `[]`). */ +function segmentsOf(file: string, layout?: DbtProjectLayout): string[] { + const root = layout?.root ? layout.root.replace(/\/$/, "") + "/" : "" + const rel = root && file.startsWith(root) ? file.slice(root.length) : file + const parts = rel.split("/").slice(0, -1) + const resourceDirs = layout ? Object.values(layout.dirs).flat() : ["models", "seeds", "snapshots", "tests"] + return resourceDirs.includes(parts[0]) ? parts.slice(1) : parts +} + +export function detectTestAdequacy(input: { + file: ChangedFile + oldContent?: string + newContent?: string + projectYml?: string + layout?: DbtProjectLayout + /** Tests (`testKeys`) in the base versions of every yml in the PR: a test + * moved from another file is not new. */ + baseTests?: Set + /** Lists the file as not fully verified (kind `abstained`). */ + abstain?: (reason: string) => void +}): Finding[] { + const { file } = input + if (file.status === "deleted" || input.newContent === undefined) return [] + let newDoc: any + try { + newDoc = YAML.parse(input.newContent) + } catch { + input.abstain?.("the yml does not parse, so its data tests were not checked") + return [] + } + if (!newDoc) return [] + const before = new Set([...testsOf(parse(input.oldContent)).map(key), ...(input.baseTests ?? [])]) + const added = testsOf(newDoc).filter((t) => !before.has(key(t))) + const out: Finding[] = [] + + for (const t of added) { + const name = shortName(t.test) + // Different expressions on the same model are a valid invariant (e.g. sum of + // line items equals the order total); only the same expression is circular. + const sameExpression = + name !== "expect_table_aggregation_to_equal_other_table" || + String(arg(t, "compare_expression") ?? arg(t, "expression") ?? "").replace(/\s+/g, "").toLowerCase() === + String(arg(t, "expression") ?? "").replace(/\s+/g, "").toLowerCase() + // `cardinality_equality` compares this column with `field` on the other + // model; against itself it is circular only when the field is the same column. + const sameField = + name !== "cardinality_equality" || String(arg(t, "field") ?? "").toLowerCase() === (t.column ?? "").toLowerCase() + const self = + (SELF_COMPARE.has(name) && + sameExpression && + sameField && + !sidesDiffer(t) && + ["compare_model", "to", "compare_to"].some((a) => refsSelf(t, arg(t, a)))) || + (name === "relationships" && + refsSelf(t, arg(t, "to")) && + // A `where` filters only the child side: a subset of a column is still + // contained in the whole column. + String(arg(t, "field") ?? "").toLowerCase() === (t.column ?? "").toLowerCase()) + if (self) { + // A plain identifier stays bare (the summary drops the `model: ` prefix). + const plain = IDENT.test(t.entity) + out.push( + finding(file, plain ? t.entity : undefined, "test-compares-model-with-itself", "warning", + `${plain ? t.entity : span(t.entity)}: ${span(t.test)} compares the model with itself`, + `This test checks ${span(t.entity)}${t.column ? `.${span(t.column)}` : ""} against ${span(`ref('${t.entity}')`)}, so it passes by construction. ` + + "Point it at the independent source of truth it is meant to reconcile against.", `:${key(t)}`), + ) + } + } + + const project = parse(input.projectYml) + if (added.length && !project) + input.abstain?.("`dbt_project.yml` could not be read or parsed, so the test thresholds new tests inherit were not checked") + if (project && added.length) { + const inherited = inheritedThresholds(project, segmentsOf(file.path, input.layout)) + // dbt resolves `severity` and `error_if` separately: a local `warn_if` or + // `error_if` still leaves `severity` inherited, and vice versa. + const local = (t: TestRef, k: "severity" | "error_if") => t.args?.config?.[k] ?? t.args?.[k] + const inheritingWarn = added.filter((t) => local(t, "severity") === undefined) + const inheritingThreshold = added.filter( + (t) => local(t, "error_if") === undefined && String(local(t, "severity") ?? inherited.severity ?? "error").toLowerCase() !== "warn", + ) + const where = inherited.path.length ? ` (\`data_tests:\` → ${inherited.path.map(span).join(" → ")})` : "" + if (inheritingWarn.length && inherited.severity === "warn") + out.push( + finding(file, undefined, "test-inherits-warn", "suggestion", `${inheritingWarn.length} new test(s) in ${span(file.path)} inherit \`severity: warn\``, + `They inherit \`severity: warn\` from \`dbt_project.yml\`${where}, so failures are reported but never fail \`dbt build\`. ` + + "If a test should gate the build, set `config: {severity: error}` on it."), + ) + else if (inheritingThreshold.length && inherited.error_if && allowedFailures(inherited.error_if) !== 0) + out.push( + finding(file, undefined, "test-inherits-threshold", "suggestion", `${inheritingThreshold.length} new test(s) in ${span(file.path)} inherit ${span(`error_if: ${inherited.error_if}`)}`, + `They fail only when ${span(inherited.error_if)} rows fail, a threshold inherited from \`dbt_project.yml\`${where}. ` + + "Set `config: {error_if: '!= 0'}` on tests that must catch any bad row."), + ) + } + return out +} + +/** A `dbt_project.yml` change that loosens test thresholds for a whole path. + * A version that cannot be read or parsed is reported through `abstain`. */ +export function detectThresholdLoosening( + file: ChangedFile, + oldContent?: string, + newContent?: string, + abstain?: (reason: string) => void, +): Finding[] { + const oldDoc = parse(oldContent) + const newDoc = parse(newContent) + if (!oldDoc || !newDoc) { + const side = !oldDoc && !newDoc ? "either version" : !oldDoc ? "the base version" : "the head version" + abstain?.(`${side} of \`dbt_project.yml\` could not be read or parsed, so loosened test thresholds were not checked`) + return [] + } + // Every config path in either version: a deleted override loosens its subtree too. + const paths = new Map() + const visit = (node: any, path: string[]) => { + if (!node || typeof node !== "object") return + paths.set(path.join("\u0000"), path) + for (const [k, v] of Object.entries(node)) if (!k.startsWith("+") && v && typeof v === "object") visit(v, [...path, k]) + } + visit(oldDoc?.data_tests ?? oldDoc?.tests, []) + visit(newDoc?.data_tests ?? newDoc?.tests, []) + // Effective values at a path, walking the tree from the top (no project-name prepend: + // the path already names it when the config does). + const effective = (doc: any, path: string[]) => { + const eff: { severity: string; error_if?: string } = { severity: "error" } + let node = doc?.data_tests ?? doc?.tests + for (let i = 0; i <= path.length && node && typeof node === "object"; i++) { + const t = thresholds(node) + if (t.severity) eff.severity = t.severity + if (t.error_if) eff.error_if = t.error_if + node = node[path[i]] + } + return eff + } + const loosened = (path: string[]) => { + const prev = effective(oldDoc, path) + const next = effective(newDoc, path) + const toWarn = next.severity === "warn" && prev.severity !== "warn" + // Only a bound that tolerates more failing rows loosens; a changed condition + // that isn't a simple bound is still reported. + const allowed = allowedFailures(next.error_if) + const looserThreshold = + next.severity !== "warn" && + prev.severity !== "warn" && + next.error_if !== prev.error_if && + !!next.error_if && + (allowed === undefined || allowed > (allowedFailures(prev.error_if) ?? 0)) + return toWarn ? { why: "`severity: warn` now applies" } : looserThreshold ? { why: `${span(`error_if: ${next.error_if}`)} now applies` } : undefined + } + const out: Finding[] = [] + for (const path of paths.values()) { + const hit = loosened(path) + // Report only the topmost loosened path, not each folder below it. + if (!hit || (path.length && loosened(path.slice(0, -1)))) continue + const label = path.join(" → ") || "(all tests)" + out.push( + finding(file, undefined, "test-thresholds-loosened", "warning", `test thresholds loosened for ${span(label)}`, + `${hit.why} to every data test under ${span(label)} in \`dbt_project.yml\`, so those tests stop failing the build. ` + + "Prefer setting it on the specific tests that need it.", `:${label}`), + ) + } + return out +} diff --git a/packages/opencode/test/altimate/review-action.test.ts b/packages/opencode/test/altimate/review-action.test.ts new file mode 100644 index 0000000000..ad3cc459ca --- /dev/null +++ b/packages/opencode/test/altimate/review-action.test.ts @@ -0,0 +1,203 @@ +import { describe, test, expect, beforeAll, afterAll } from "bun:test" +import { promises as fs } from "node:fs" +import os from "node:os" +import path from "node:path" +import YAML from "yaml" +import { compiledHeadDirs, makeCompiledResolver } from "../../src/altimate/review/compiled" + +/** The GitHub Action's optional artifact preparation stays opt-in and injection-safe. */ +const actionPath = path.join(import.meta.dir, "../../../../github/review/action.yml") + +describe("action: dbt_prepare", () => { + test("is opt-in, and its script reads inputs only from env", async () => { + const action = YAML.parse(await fs.readFile(actionPath, "utf8")) + expect(action.inputs.dbt_prepare.default).toBe("none") + expect(action.inputs.dbt_command.default).toBe("dbt") + const steps: Array<{ name: string; if?: string; run?: string; env?: Record }> = action.runs.steps + const prep = steps.find((s) => s.name === "Prepare dbt artifacts")! + const review = steps.findIndex((s) => s.name === "Run dbt PR review") + expect(steps.indexOf(prep)).toBeLessThan(review) + expect(prep.if).toBe("inputs.dbt_prepare != 'none'") + expect(prep.run).not.toContain("${{") + expect(prep.env?.IN_DBT).toBe("${{ inputs.dbt_command }}") + // The base is compiled into target-base/, where the compiled-SQL resolver looks. + expect(prep.run).toContain('"$PROJECT/target-base"') + }) + + test("a failed docs generate or base checkout warns and lets the review run", async () => { + const action = YAML.parse(await fs.readFile(actionPath, "utf8")) + const prep = (action.runs.steps as Array<{ name: string; run?: string }>).find((s) => s.name === "Prepare dbt artifacts")! + const run = prep.run! + expect(run).toMatch(/docs generate[^\n]*\) \|\|\n\s*echo "::warning::/) + expect(run).toMatch(/git worktree add[^\n]*\|\| \{ echo "::warning::/) + }) + + test("a mismatched head, an empty dbt_command or a failed head compile never builds the wrong artifacts or fails the job", async () => { + const action = YAML.parse(await fs.readFile(actionPath, "utf8")) + const prep = (action.runs.steps as Array<{ name: string; run?: string; env?: Record }>).find( + (s) => s.name === "Prepare dbt artifacts", + )! + const run = prep.run! + expect(prep.env?.IN_HEAD).toBe("${{ inputs.head }}") + expect(prep.env?.IN_MANIFEST).toBe("${{ inputs.manifest_path }}") + expect(run).toMatch(/\$\{#DBT\[@\]\} -eq 0 \]\]; then echo "::error::/) + // The head check runs before anything is compiled. + expect(run.indexOf('"$IN_HEAD^{commit}"')).toBeLessThan(run.indexOf('build "$PROJECT"')) + expect(run).toMatch(/if ! build "\$PROJECT" "\$TARGET"; then\n\s*echo "::warning::/) + expect(run).toContain('cp "$PROJECT/profiles.yml" "$WT/$REL/profiles.yml"') + expect(action.inputs.dbt_prepare.description).not.toContain("usually works offline") + }) +}) + +/** + * The prepare script itself, run against a throwaway git repo with a stub + * `dbt` that writes the model's SQL into `--target-path`. The review's + * compiled-SQL resolver (as `run.ts` builds it) must then find what was built. + */ +describe("action: dbt_prepare, run with a stub dbt", () => { + let tmp: string + let script: string + const git = (cwd: string, ...args: string[]) => { + const r = Bun.spawnSync(["git", "-c", "user.email=t@example.invalid", "-c", "user.name=t", "-c", "commit.gpgsign=false", ...args], { cwd }) + if (r.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr.toString()}`) + } + + beforeAll(async () => { + tmp = await fs.mkdtemp(path.join(os.tmpdir(), "review-prepare-")) + const action = YAML.parse(await fs.readFile(actionPath, "utf8")) + script = (action.runs.steps as Array<{ name: string; run?: string }>).find((s) => s.name === "Prepare dbt artifacts")!.run! + await fs.mkdir(path.join(tmp, "bin")) + // Stub dbt: `compile` copies each model into /compiled/shop/, or fails when DBT_FAIL is set. + await fs.writeFile( + path.join(tmp, "bin", "dbt"), + [ + "#!/usr/bin/env bash", + "cmd=$1; shift; tp=target", + 'while [[ $# -gt 0 ]]; do [[ $1 == --target-path ]] && { tp=$2; shift; }; shift; done', + '[[ $cmd == compile ]] || exit 0', + '[[ -n "${DBT_FAIL:-}" ]] && exit 1', + 'mkdir -p "$tp/compiled/shop/models" && cp models/a.sql "$tp/compiled/shop/models/a.sql" && echo "{}" > "$tp/manifest.json"', + "", + ].join("\n"), + { mode: 0o755 }, + ) + }) + afterAll(async () => { + await fs.rm(tmp, { recursive: true, force: true }) + }) + + /** A repo whose `main` has `select 1 as id` and whose checked-out PR branch changes it. */ + async function repo(name: string): Promise { + const dir = path.join(tmp, name) + await fs.mkdir(path.join(dir, "models"), { recursive: true }) + await fs.writeFile(path.join(dir, "dbt_project.yml"), "name: shop\n") + await fs.writeFile(path.join(dir, "models", "a.sql"), "select 1 as id\n") + git(dir, "init", "-q", "-b", "main") + git(dir, "add", "-A") + git(dir, "commit", "-qm", "base") + git(dir, "checkout", "-qb", "pr") + await fs.writeFile(path.join(dir, "models", "a.sql"), "select 1 as id, 2 as b\n") + git(dir, "commit", "-qam", "pr") + // A target-base/ left behind by an earlier run. + await fs.mkdir(path.join(dir, "target-base", "compiled", "shop", "models"), { recursive: true }) + await fs.writeFile(path.join(dir, "target-base", "compiled", "shop", "models", "a.sql"), "STALE\n") + return dir + } + + function prepare(dir: string, env: Record) { + const runner = path.join(tmp, `runner-${path.basename(dir)}`) + return Bun.spawnSync(["bash", "-c", script], { + cwd: dir, + env: { + PATH: `${path.join(tmp, "bin")}:${process.env.PATH}`, + HOME: tmp, + RUNNER_TEMP: runner, + IN_PREPARE: "compile", + IN_DBT: "dbt", + IN_PROFILES: "", + IN_PROJECT_DIR: ".", + IN_MANIFEST: "", + IN_BASE: "", + IN_HEAD: "", + EVENT_BASE: "", + ...env, + }, + }) + } + + async function resolve(dir: string, manifest: string) { + const r = makeCompiledResolver({ cwd: dir, projectName: "shop", headDirs: await compiledHeadDirs(dir, manifest) }) + return { head: await r("models/a.sql", "new"), base: await r("models/a.sql", "old") } + } + + test("with a non-default manifest_path the review finds the compiled head, and the merge-base lands in target-base/", async () => { + await fs.mkdir(path.join(tmp, "runner-custom"), { recursive: true }) + const dir = await repo("custom") + const r = prepare(dir, { IN_MANIFEST: "build/manifest.json", IN_BASE: "main" }) + expect(r.exitCode).toBe(0) + expect(await fs.readFile(path.join(dir, "build", "manifest.json"), "utf8")).toBe("{}\n") + expect(await resolve(dir, "build/manifest.json")).toEqual({ head: "select 1 as id, 2 as b\n", base: "select 1 as id\n" }) + }) + + test("a project_dir outside the checkout is skipped, and nothing outside it is removed", async () => { + const dir = await repo("outside") + // `..` from the checkout is `tmp`, which holds a target-base/ of its own. + await fs.mkdir(path.join(tmp, "target-base"), { recursive: true }) + await fs.writeFile(path.join(tmp, "target-base", "keep"), "keep\n") + const r = prepare(dir, { IN_PROJECT_DIR: "..", IN_BASE: "main" }) + expect(r.exitCode).toBe(0) + expect(r.stdout.toString()).toContain("::warning::project_dir (..) is not inside the checked-out repository") + expect(await fs.readFile(path.join(tmp, "target-base", "keep"), "utf8")).toBe("keep\n") + // Another git repository next to the checkout is outside it too. + const other = await repo("other") + const r2 = prepare(dir, { IN_PROJECT_DIR: "../other", IN_BASE: "main" }) + expect(r2.exitCode).toBe(0) + expect(r2.stdout.toString()).toContain("is not inside the checked-out repository") + expect(await fs.readFile(path.join(other, "target-base", "compiled", "shop", "models", "a.sql"), "utf8")).toBe("STALE\n") + // A folder inside the workspace that is not a git checkout is skipped as well. + const plain = path.join(tmp, "plain") + await fs.mkdir(path.join(plain, "target-base"), { recursive: true }) + await fs.writeFile(path.join(plain, "target-base", "keep"), "keep\n") + const r3 = prepare(dir, { IN_PROJECT_DIR: "../plain", GITHUB_WORKSPACE: tmp }) + expect(r3.exitCode).toBe(0) + expect(r3.stdout.toString()).toContain("is not inside the checked-out repository") + expect(await fs.readFile(path.join(plain, "target-base", "keep"), "utf8")).toBe("keep\n") + }) + + test("a project the PR adds has no base to compile: nothing lands in its target-base/", async () => { + await fs.mkdir(path.join(tmp, "runner-added"), { recursive: true }) + const dir = await repo("added") + await fs.mkdir(path.join(dir, "newproj", "models"), { recursive: true }) + await fs.writeFile(path.join(dir, "newproj", "dbt_project.yml"), "name: shop\n") + await fs.writeFile(path.join(dir, "newproj", "models", "a.sql"), "select 9 as z\n") + git(dir, "add", "newproj") + git(dir, "commit", "-qm", "add project") + const r = prepare(dir, { IN_PROJECT_DIR: "newproj", IN_BASE: "main" }) + expect(r.exitCode).toBe(0) + expect(r.stdout.toString()).toContain("no dbt project at this path") + // The root project's base SQL is not written into the new project's base side. + expect(await fs.readdir(path.join(dir, "newproj")).then((e) => e.includes("target-base"))).toBe(false) + }) + + test("a base or head that git would read as an option or a refspec skips preparing", async () => { + const dir = await repo("badref") + const envs: Array> = [{ IN_BASE: "main:refs/heads/x" }, { IN_BASE: "+main" }, { IN_HEAD: "--output=x" }] + for (const env of envs) { + const r = prepare(dir, env) + expect(r.exitCode).toBe(0) + expect(r.stdout.toString()).toContain("::warning::base and head must be plain git refs") + expect(await fs.readdir(dir).then((e) => e.includes("target") || e.includes("target-base"))).toBe(false) + } + }) + + test("a stale target-base/ is removed even when the step exits early", async () => { + // No base branch known: the base compile is skipped. + const noBase = await repo("nobase") + expect(prepare(noBase, {}).exitCode).toBe(0) + expect((await resolve(noBase, "target/manifest.json")).base).toBeUndefined() + // The head compile fails: the step stops before anything else. + const failed = await repo("failed") + expect(prepare(failed, { DBT_FAIL: "1", IN_BASE: "main" }).exitCode).toBe(0) + expect(await resolve(failed, "target/manifest.json")).toEqual({ head: undefined, base: undefined }) + }) +}) diff --git a/packages/opencode/test/altimate/review-incremental-semantics.test.ts b/packages/opencode/test/altimate/review-incremental-semantics.test.ts index 0c462300ee..b9baccd0f7 100644 --- a/packages/opencode/test/altimate/review-incremental-semantics.test.ts +++ b/packages/opencode/test/altimate/review-incremental-semantics.test.ts @@ -554,6 +554,304 @@ describe("end to end through the orchestrator", () => { }) }) +describe("dedup windows split across lines", () => { + const sql = "select *,\n row_number() over (\n partition by job_id\n order by ingestion_timestamp desc\n ) as rn\nfrom t" + const rulesFor = (diffAdded: string) => + detectModelPatterns({ path: "models/m.sql", status: "modified", diff: diffAdded }, sql, DEFAULT_RUBRIC).map( + (f) => (f.evidence?.result as { rule?: string })?.rule, + ) + test("an ORDER BY on its own line is seen: no false 'no ORDER BY', and the load-timestamp rule fires", () => { + const r = rulesFor("+ row_number() over (\n") + expect(r).not.toContain("dedup_no_tiebreaker") + expect(r).toContain("dedup_load_timestamp_only") + }) + test("a window the PR doesn't touch is not reported", () => { + expect(rulesFor("+select 1 as unrelated\n")).not.toContain("dedup_load_timestamp_only") + }) + test("with hunk headers, an added line matching window text elsewhere doesn't touch the window", () => { + const noOrder = + "select\n tenant\n , row_number() over (partition by tenant, id) as rn\nfrom t\nunion all\nselect\n tenant\n , id\nfrom u" + const rules = (diff: string) => + detectModelPatterns({ path: "models/m.sql", status: "modified", diff }, noOrder, DEFAULT_RUBRIC).map( + (f) => (f.evidence?.result as { rule?: string })?.rule, + ) + // Line 8 (` , id`) in the second branch was added; the window on line 3 is old code. + expect(rules("@@ -7,1 +7,2 @@\n tenant\n+ , id\n")).not.toContain("dedup_no_tiebreaker") + expect(rules("@@ -3,1 +3,1 @@\n- , row_number() over () as rn\n+ , row_number() over (partition by tenant, id) as rn\n")).toContain( + "dedup_no_tiebreaker", + ) + }) + test("without hunk headers, a bare identifier that also appears in the window doesn't touch it", () => { + const window = "select customer_id, row_number() over (partition by customer_id) as rn\nfrom t\ngroup by\n customer_id" + const rules = (diff: string) => + detectModelPatterns({ path: "models/m.sql", status: "modified", diff }, window, DEFAULT_RUBRIC).map( + (f) => (f.evidence?.result as { rule?: string })?.rule, + ) + expect(rules("+ customer_id\n")).not.toContain("dedup_no_tiebreaker") + // An added line that is the window itself (whitespace differing) still counts. + expect(rules("+select customer_id, row_number() over (partition by customer_id) as rn\n")).toContain("dedup_no_tiebreaker") + }) +}) + +describe("column changes without compiled SQL (dbt parse-only CI)", () => { + test("on_schema_change='fail' sees columns added to the raw model's SELECT", async () => { + const cfg = "{{ config(materialized='incremental', unique_key='id', on_schema_change='fail') }}\n" + const oldSql = `${cfg}select id, amount from {{ ref('src') }}` + const newSql = `${cfg}select id, amount, region from {{ ref('src') }}` + const env = await runReview({ + changedFiles: [{ path: "models/marts/fct.sql", status: "modified", diff: `-${oldSql}\n+${newSql}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner: { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return {} + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: false } + }, + async detectPii() { + return { columns: [] } + }, + async columnLineage() { + return [] + }, + } as ReviewRunner, + getContent: async (_f, side) => (side === "old" ? oldSql : newSql), + }) + expect(env.findings.find((f) => f.title.includes("on_schema_change"))?.body).toContain("adds `region`") + }) + + test("columns inside a `{% if %}` block are unknown, not added", async () => { + const cfg = "{{ config(materialized='incremental', unique_key='id', on_schema_change='fail') }}\n" + const review = (oldSql: string, newSql: string) => + runReview({ + changedFiles: [{ path: "models/marts/fct.sql", status: "modified", diff: `-${oldSql}\n+${newSql}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner: { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return {} + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: false } + }, + async detectPii() { + return { columns: [] } + }, + async columnLineage() { + return [] + }, + } as ReviewRunner, + getContent: async (_f, side) => (side === "old" ? oldSql : newSql), + }) + const conditional = await review( + `${cfg}select id, amount from {{ ref('src') }}`, + `${cfg}select id, amount {% if var('with_region', false) %}, region {% endif %} from {{ ref('src') }}`, + ) + expect(conditional.findings.some((f) => f.title.includes("on_schema_change"))).toBe(false) + // An item with no name of its own (an unaliased expression) makes the list + // unknown, so the column it replaced is neither removed nor others added. + const unnamed = await review( + `${cfg}select id, amount from {{ ref('src') }}`, + `${cfg}select id, amount * 100, region from {{ ref('src') }}`, + ) + expect(unnamed.findings.some((f) => f.title.includes("on_schema_change"))).toBe(false) + }) +}) + +describe("raw column lists under Jinja control flow (no compiled SQL)", () => { + const consumersRunner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return {} + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: false } + }, + async detectPii() { + return { columns: [] } + }, + async columnLineage() { + return [] + }, + async modelConsumers() { + return { exposures: [{ name: "revenue_dashboard", type: "dashboard" }], contractEnforced: false, contractColumns: [] } + }, + } as unknown as ReviewRunner + const reviewRaw = (oldSql: string, newSql: string) => + runReview({ + changedFiles: [{ path: "models/fct_orders.sql", status: "modified", diff: `-${oldSql}\n+${newSql}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["lineage_breakage", "contract_violation"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: consumersRunner, + getContent: async (_f, side) => (side === "old" ? oldSql : newSql), + }) + const removed = (env: Awaited>) => env.findings.filter((f) => f.title.includes("removed column(s)")) + const listed = (env: Awaited>) => + JSON.stringify(env).includes("output columns could not be listed") + const base = "with orders as (select * from {{ ref('stg_orders') }})\nselect order_id, customer_id, email, amount from orders" + + test("`{% if %}` / `{% else %}` branches with their own SELECT are unknown, not a removal", async () => { + const env = await reviewRaw( + base, + "with orders as (select * from {{ ref('stg_orders') }})\n{% if var('include_pii', true) %}\nselect order_id, customer_id, email, amount from orders\n{% else %}\nselect order_id, customer_id, amount from orders\n{% endif %}", + ) + expect(removed(env)).toEqual([]) + expect(listed(env)).toBe(true) + }) + + test("a `{% set %}` block holding a query is unknown, not the model's SELECT", async () => { + const env = await reviewRaw( + base, + `${base}\n{% set audit_query %}\nselect count(*) as n from {{ ref('stg_orders') }}\n{% endset %}\n{% do log(audit_query) %}`, + ) + expect(removed(env)).toEqual([]) + expect(listed(env)).toBe(true) + }) + + test("a SELECT inside a block that changes which branch names the columns is unknown", async () => { + // Rendered with the default, the model is the second SELECT; read flat, the + // union's first branch would name `total` and drop `amount`. + const old = "select order_id, amount from {{ ref('orders') }}" + const env = await reviewRaw(old, `{% if var('include_legacy', false) %}\nselect order_id, total from {{ ref('legacy_orders') }}\nunion all\n{% endif %}\n${old}`) + expect(removed(env)).toEqual([]) + expect(listed(env)).toBe(true) + }) + + test("a real removal is still reported, also next to an `is_incremental()` subquery filter", async () => { + const filter = "\n{% if is_incremental() %} where order_id > (select max(order_id) from {{ this }}) {% endif %}" + const env = await reviewRaw(`${base}${filter}`, `with orders as (select * from {{ ref('stg_orders') }})\nselect order_id, customer_id, amount from orders${filter}`) + expect(removed(env).map((f) => f.body)).toEqual([expect.stringContaining("removes `email`")]) + }) +}) + +describe("dedup windows: comment-only edits", () => { + const head = "with source as (select * from events),\ndeduped as (\n select *,\n row_number() over (\n -- one row per event\n partition by event_id\n ) as rn\n from source\n)\nselect * from deduped where rn = 1\n" + const rules = (diff: string) => + detectModelPatterns({ path: "models/stg_events.sql", status: "modified", diff }, head, DEFAULT_RUBRIC).map( + (f) => (f.evidence?.result as { rule?: string })?.rule, + ) + test("a comment line added inside an existing window does not touch it; a code line does", () => { + expect(rules("@@ -4,2 +4,3 @@\n row_number() over (\n+ -- one row per event\n partition by event_id\n")).not.toContain("dedup_no_tiebreaker") + expect(rules("@@ -4,3 +4,3 @@\n row_number() over (\n -- one row per event\n- partition by id\n+ partition by event_id\n")).toContain("dedup_no_tiebreaker") + }) +}) + +describe("raw column names glued to a Jinja expression", () => { + const exposures = (models: string[]) => + ({ + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return {} + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: false } + }, + async detectPii() { + return { columns: [] } + }, + async columnLineage() { + return [] + }, + async modelConsumers(model: string) { + return models.includes(model) + ? { exposures: [{ name: `${model}_dash`, type: "dashboard" }], contractEnforced: false, contractColumns: [] } + : undefined + }, + }) as unknown as ReviewRunner + const run = ( + pairs: Array<{ model: string; oldSql: string; newSql: string; compiledNew?: string }>, + ) => + runReview({ + changedFiles: pairs.map((p) => ({ path: `models/${p.model}.sql`, status: "modified" as const, diff: `-${p.oldSql}\n+${p.newSql}\n` })), + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["lineage_breakage", "contract_violation"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: exposures(pairs.map((p) => p.model)), + getContent: async (f, side) => { + const p = pairs.find((x) => f === `models/${x.model}.sql`)! + return side === "old" ? p.oldSql : p.newSql + }, + getCompiled: async (f, side) => (side === "new" ? pairs.find((x) => f === `models/${x.model}.sql`)?.compiledNew : undefined), + }) + const columnNotes = (env: Awaited>) => + (env.scope?.unverified ?? []).filter((u) => u.kind === "abstained" && u.reason.includes("output columns could not be listed")) + const removed = (env: Awaited>) => env.findings.filter((f) => f.title.includes("removed column(s)")) + const sel = (cols: string) => `select ${cols}\nfrom {{ ref('stg_orders') }}` + + test("a name built from `{{ var() }}` or a Jinja alias is unknown, not a removal", async () => { + const cases = { + h07: [sel("order_id, usd_amount"), sel("order_id, {{ var('currency', 'usd') }}_amount")], + h08: [sel(`order_id, amount as "amount_usd"`), sel(`order_id, amount as "amount_{{ var('currency', 'usd') }}"`)], + h26: [ + "with f as (select order_id, usd_amount from {{ ref('p') }})\nselect * from f", + "with f as (select order_id, {{ var('c', 'usd') }}_amount from {{ ref('p') }})\nselect * from f", + ], + // A real rename hidden in the default: unknown, never read as "no change". + r13: [sel("order_id, {{ var('c', 'usd') }}_amount"), sel("order_id, {{ var('c', 'eur') }}_amount")], + } + for (const [name, [oldSql, newSql]] of Object.entries(cases)) { + const env = await run([{ model: name, oldSql, newSql }]) + expect(removed(env)).toEqual([]) + expect(columnNotes(env).map((u) => u.path)).toEqual([`models/${name}.sql`]) + } + }) + + test("three such models in parse-only CI are listed, not REQUEST_CHANGES", async () => { + const pair = { oldSql: sel("order_id, usd_amount"), newSql: sel("order_id, {{ var('currency', 'usd') }}_amount") } + const env = await run(["fct_a", "fct_b", "fct_c"].map((model) => ({ model, ...pair }))) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + expect(removed(env)).toEqual([]) + expect(columnNotes(env)).toHaveLength(3) + }) + + test("with compiled SQL on the head only, both sides are read raw only when both are fully known", async () => { + const oldSql = sel("order_id, usd_amount") + const newSql = sel("order_id, {{ var('currency', 'usd') }}_amount") + const env = await run([{ model: "fct_a", oldSql, newSql, compiledNew: "select order_id, usd_amount\nfrom analytics.stg_orders" }]) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + expect(removed(env)).toEqual([]) + expect(columnNotes(env)).toHaveLength(1) + }) + + test("a Jinja expression standing as an item is unknown, not a removed column", async () => { + const env = await run([{ model: "fct_a", oldSql: sel("order_id, amount"), newSql: sel("order_id, {{ amount_expr() }}") }]) + expect(removed(env)).toEqual([]) + expect(columnNotes(env)).toHaveLength(1) + }) + + test("two top-level SELECTs with no set operator are unknown", async () => { + const env = await run([{ model: "fct_a", oldSql: sel("order_id, amount"), newSql: `${sel("order_id")}\n{# legacy #}\n${sel("order_id, amount")}` }]) + expect(removed(env)).toEqual([]) + expect(columnNotes(env)).toHaveLength(1) + }) +}) + describe("no error text from these checks reaches the comment, the envelope or telemetry; the job log has it", () => { // A unique string per run: if it shows up in public output, error text leaked. const marker = () => ["leak", "marker", Math.random().toString(36).slice(2, 10)].join("-") diff --git a/packages/opencode/test/altimate/review-test-adequacy.test.ts b/packages/opencode/test/altimate/review-test-adequacy.test.ts new file mode 100644 index 0000000000..f5b1ef582b --- /dev/null +++ b/packages/opencode/test/altimate/review-test-adequacy.test.ts @@ -0,0 +1,448 @@ +import { describe, test, expect, spyOn } from "bun:test" +import YAML from "yaml" +import { detectTestAdequacy, detectThresholdLoosening, inheritedThresholds, testKeys } from "../../src/altimate/review/test-adequacy" +import { runReview, type ReviewRunner } from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import { renderSummary } from "../../src/altimate/review/format" +import { emitReviewRun } from "../../src/altimate/review/telemetry" +import { Telemetry } from "../../src/altimate/telemetry" + +/** Data tests that can't do their job, from yml alone (any adapter). */ + +const file = { path: "models/marts/_fct.yml", status: "modified" as const } +const rule = (fs: { evidence?: { result?: unknown } }[]) => fs.map((f) => (f.evidence?.result as { rule: string }).rule) + +describe("tests that compare a model with itself", () => { + const yml = (compare: string) => `models: + - name: fct_orders + data_tests: + - dbt_utils.equal_rowcount: + compare_model: ${compare} + columns: + - name: customer_id + data_tests: + - relationships: + to: ref('fct_orders') + field: customer_id +` + test("own-ref comparisons and self relationships pass by construction", () => { + const out = detectTestAdequacy({ file, newContent: yml("ref('fct_orders')") }) + expect(rule(out)).toEqual(["test-compares-model-with-itself", "test-compares-model-with-itself"]) + }) + + test("a comparison with another model is fine; unchanged tests are skipped", () => { + const other = yml("ref('stg_orders')").replace("to: ref('fct_orders')", "to: ref('dim_customers')") + expect(detectTestAdequacy({ file, newContent: other })).toEqual([]) + expect(detectTestAdequacy({ file, oldContent: yml("ref('fct_orders')"), newContent: yml("ref('fct_orders')") })).toEqual([]) + }) + + test("fewer_rows_than against itself, or an aggregation with a different expression, is not flagged", () => { + const y = `models: + - name: fct_orders + data_tests: + - dbt_utils.fewer_rows_than: + compare_model: ref('fct_orders') + - dbt_expectations.expect_table_aggregation_to_equal_other_table: + expression: sum(line_total) + compare_model: ref('fct_orders') + compare_expression: sum(order_total) +` + expect(detectTestAdequacy({ file, newContent: y })).toEqual([]) + const same = y.replace("sum(order_total)", "sum( line_total )") + expect(rule(detectTestAdequacy({ file, newContent: same }))).toEqual(["test-compares-model-with-itself"]) + }) + + test("dbt 1.8+ `arguments:` form is read too", () => { + const y = `models:\n - name: m\n data_tests:\n - dbt_utils.equality:\n arguments:\n compare_model: ref("m")\n` + expect(rule(detectTestAdequacy({ file: { path: "models/_m.yml", status: "added" }, newContent: y }))).toEqual(["test-compares-model-with-itself"]) + }) +}) + +describe("thresholds inherited from dbt_project.yml", () => { + const project = `name: shop +data_tests: + shop: + marts: + +severity: warn + staging: + +error_if: ">100" +` + const newTests = (own = "") => `models: + - name: fct_orders + columns: + - name: id + data_tests: + - not_null${own} +` + test("the effective value walks project → folders, deeper wins", () => { + const doc = YAML.parse(project) + expect(inheritedThresholds(doc, ["marts"])).toEqual({ severity: "warn", path: ["shop", "marts"] }) + expect(inheritedThresholds(doc, ["staging", "x"])).toEqual({ error_if: ">100", path: ["shop", "staging"] }) + expect(inheritedThresholds(doc, ["core"])).toEqual({ path: [] }) + }) + + test("new tests under a warn folder are reported; a test with its own severity is not", () => { + const out = detectTestAdequacy({ file, newContent: newTests(), projectYml: project }) + expect(rule(out)).toEqual(["test-inherits-warn"]) + expect(out[0].body).toContain("`shop` → `marts`") + const own = newTests(":\n config:\n severity: error") + expect(detectTestAdequacy({ file, newContent: own, projectYml: project })).toEqual([]) + }) + + test("an inherited error_if threshold is reported", () => { + const out = detectTestAdequacy({ file: { path: "models/staging/_stg.yml", status: "modified" }, newContent: newTests(), projectYml: project }) + expect(rule(out)).toEqual(["test-inherits-threshold"]) + }) + + test("a dbt_project.yml change that loosens thresholds is reported", () => { + const before = "name: shop\ndata_tests:\n shop:\n marts:\n +severity: error\n" + const after = "name: shop\ndata_tests:\n shop:\n marts:\n +severity: warn\n" + const out = detectThresholdLoosening({ path: "dbt_project.yml", status: "modified" }, before, after) + expect(out.map((f) => f.title)).toEqual(["test thresholds loosened for `shop → marts`"]) + expect(detectThresholdLoosening({ path: "dbt_project.yml", status: "modified" }, after, after)).toEqual([]) + }) + + test("error_if: only a bound that tolerates more failures loosens; strict forms are the default", () => { + const at = (cond: string) => `name: shop\ndata_tests:\n shop:\n marts:\n +error_if: "${cond}"\n` + const loosened = (from: string, to: string) => + detectThresholdLoosening({ path: "dbt_project.yml", status: "modified" }, at(from), at(to)).length > 0 + expect(loosened(">100", ">10")).toBe(false) + expect(loosened(">10", ">100")).toBe(true) + expect(loosened("!= 0", "> 0")).toBe(false) + expect(loosened("!= 0", ">=1")).toBe(false) + expect(loosened("!= 0", ">5")).toBe(true) + }) + + test("loosening is judged on effective values: a deleted stricter override is reported, a redundant warn is not", () => { + const yml = (body: string) => `name: shop\ndata_tests:\n +severity: warn\n shop:\n${body}` + const ch = (a: string, b: string) => detectThresholdLoosening({ path: "dbt_project.yml", status: "modified" }, a, b) + // Root warn, marts override to error deleted: every marts test now warns. + const deleted = ch(yml(" marts:\n +severity: error\n"), yml(" marts:\n +materialized: view\n")) + expect(deleted.map((f) => f.title)).toEqual(["test thresholds loosened for `shop → marts`"]) + // A redundant warn under an already-warn root changes nothing. + expect(ch(yml(" marts:\n +enabled: true\n"), yml(" marts:\n +severity: warn\n"))).toEqual([]) + // Loosening at the root is reported once, not again for each folder below it. + const root = ch("data_tests:\n shop:\n marts:\n x:\n +enabled: true\n", "data_tests:\n +severity: warn\n shop:\n marts:\n x:\n +enabled: true\n") + expect(root.map((f) => f.title)).toEqual(["test thresholds loosened for `(all tests)`"]) + }) + + test("a local warn_if or error_if leaves severity inherited", () => { + const withCfg = (cfg: string) => newTests(`:\n config:\n ${cfg}`) + expect(rule(detectTestAdequacy({ file, newContent: withCfg("warn_if: '>10'"), projectYml: project }))).toEqual(["test-inherits-warn"]) + expect(rule(detectTestAdequacy({ file, newContent: withCfg("error_if: '!= 0'"), projectYml: project }))).toEqual(["test-inherits-warn"]) + // Under an inherited threshold, a local severity: error still inherits error_if. + const stg = { path: "models/staging/_stg.yml", status: "modified" as const } + expect(rule(detectTestAdequacy({ file: stg, newContent: withCfg("severity: error"), projectYml: project }))).toEqual(["test-inherits-threshold"]) + expect(detectTestAdequacy({ file: stg, newContent: withCfg("error_if: '!= 0'"), projectYml: project })).toEqual([]) + }) + + test("a seed yml is resolved below the seed path, not as a `seeds` folder", () => { + const proj = "name: shop\ndata_tests:\n shop:\n +severity: warn\n seeds:\n +severity: error\n" + const seedYml = "seeds:\n - name: countries\n columns:\n - name: code\n data_tests:\n - not_null\n" + const out = detectTestAdequacy({ file: { path: "seeds/_seeds.yml", status: "added" }, newContent: seedYml, projectYml: proj }) + expect(rule(out)).toEqual(["test-inherits-warn"]) + }) +}) + +describe("cardinality_equality against the same model", () => { + const y = (field: string) => `models: + - name: m + columns: + - name: a + data_tests: + - dbt_utils.cardinality_equality: + to: ref('m') + field: ${field} +` + test("a different field is a real check; the same field is circular", () => { + expect(detectTestAdequacy({ file, newContent: y("b") })).toEqual([]) + expect(rule(detectTestAdequacy({ file, newContent: y("a") }))).toEqual(["test-compares-model-with-itself"]) + }) +}) + +const stubRunner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return {} + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: false } + }, + async detectPii() { + return { columns: [] } + }, + async columnLineage() { + return [] + }, +} as unknown as ReviewRunner + +const review = (changedFiles: Parameters[0]["changedFiles"], getContent: (f: string, side: "old" | "new") => Promise) => + runReview({ config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, rubric: DEFAULT_RUBRIC, mode: "comment", runner: stubRunner, changedFiles, getContent }) + +describe("names and values from the repository are code spans in the summary", () => { + test("a backtick, a team mention, a line break with a heading or an HTML comment never leaves its span", async () => { + // Each hostile value carries a backtick, `@acme/team`, a newline + heading and `` }, + { ...ownBlock, body: "please fix the naming" }, + ]) { + const c = fakeClient({ reviews: [other] }) + const r = await postGitHubReview(env, target, c.octo) + expect(r.silent).toBe(true) + expect(c.calls).toHaveLength(0) + } + // With findings, normal behaviour and no sentence. + const f = buildEnvelope({ findings: [warn("m: w")], tier: "lite", mode: "gate", policy: posting(true) }) + const c = fakeClient({ reviews: [{ ...ownBlock, user: { login: "maintainer" } }] }) + await postGitHubReview(f, target, c.octo) + expect(summaryOf(c.calls)).not.toContain(SENTENCE) + }) + + test("a later approval by this account ends its request: a clean run stays silent", async () => { + const env = buildEnvelope({ findings: [], tier: "lite", mode: "gate", ai: { state: "ok" }, policy: posting(true) }) + const approved = { id: 12, state: "APPROVED", body: "✅ Approved — no findings (lite tier)", user: { login: BOT } } + expect((await postGitHubReview(env, target, fakeClient({ reviews: [ownBlock, approved] }).octo)).silent).toBe(true) + }) +}) + +describe("silentWhenClean", () => { + test("withheld findings: silent only when none of them counts toward the verdict", () => { + const clean = (withheld: VerdictEnvelope["withheld"]) => + buildEnvelope({ findings: [], tier: "lite", mode: "gate", ai: { state: "ok" }, withheld }) + // Not verdict-eligible: the run stays silent; the signed envelope keeps the count. + const quiet = clean([{ rule: "rule-catalog:large-in-list", count: 2, verdict: 0 }]) + expect(renderSummary(quiet)).toBe("") + expect(quiet.withheld?.[0].count).toBe(2) + // Verdict-eligible (an envelope built by hand, so the verdict is still APPROVE): never silent. + const decisive = clean([{ rule: "altimate-core.check:x", count: 1, verdict: 1, at: ["models/m.sql:3"] }]) + expect(renderSummary(decisive)).toContain("`altimate-core.check:x` ×1 at `models/m.sql:3`") + }) + + test("an undecided equivalence is listed as not fully verified, never as plain \"no findings\"", async () => { + const env = await review(runner({ async equivalence() { return { decided: false } } } as Partial), { reviewers: ["semantic_change"] }) + expect(env.verdict).toBe("APPROVE") + expect(env.scope?.unverified).toEqual([expect.objectContaining({ path: "models/m.sql", kind: "abstained" })]) + expect(verdictHeadline(env)).toContain("(1 not fully verified)") + const md = renderSummary(env) + expect(md).toContain("not fully verified — `equivalence could not be proven") + expect(md).toContain("does not hold back approval") + }) + + test("a deliberately skipped AI lane does not force a post; a failed one does", () => { + const silent = (ai: VerdictEnvelope["ai"]) => renderSummary(buildEnvelope({ findings: [], tier: "trivial", mode: "comment", ai })) === "" + expect(silent({ state: "skipped", reason: "not part of the trivial tier" })).toBe(true) + expect(silent({ state: "skipped", reason: "disabled" })).toBe(true) + expect(silent({ state: "error", reason: "the model request failed. See the job log for details." })).toBe(false) + }) +}) + +describe("partial post after a positioning 422", () => { + test("every dropped finding is in full in the summary, not a pointer", async () => { + const a = warn("m: a", { body: "BODY_A detail" }) + const b = warn("big: c", { file: "models/big.sql", startLine: 900, endLine: 900, body: "BODY_B detail" }) + const env = buildEnvelope({ findings: [a, b], tier: "lite", mode: "comment" }) + const err = Object.assign(new Error("Unprocessable Entity"), { status: 422, response: { data: { errors: ["line must be part of the diff"] } } }) + const c = fakeClient({ + files: [{ filename: "models/m.sql", patch: DIFF }, { filename: "models/big.sql" }], + createReview: (n) => (n === 1 ? err : undefined), + }) + const r = await postGitHubReview(env, target, c.octo) + expect(r.inlineDropped).toBe(1) + const summary = c.calls.filter((x) => x[0] === "updateComment").at(-1)![1].body + expect(summary).toContain("### Inline (1)") + expect(summary).toContain("BODY_B detail") + expect(summary).not.toContain("BODY_A detail") + }) +}) + +describe("marker trust", () => { + test("a PR author's review comment with a forged marker suppresses neither the inline comment nor its body", async () => { + const env = buildEnvelope({ findings: [warn("m: a", { body: "BODY_A detail" })], tier: "lite", mode: "comment" }) + const forged = { body: `lgtm ${findingMarker(env.findings[0].id)}`, user: { login: "pr-author" } } + const c = fakeClient({ files: [{ filename: "models/m.sql", patch: DIFF }], reviewComments: [forged] }) + const r = await postGitHubReview(env, target, c.octo) + expect(r.inlineSkippedAsPosted).toBe(0) + expect(c.reviews()[0].comments).toHaveLength(1) + expect(c.reviews()[0].comments[0].body).toContain("BODY_A detail") + }) +}) + +describe("model and PR text in the comment is inert", () => { + const hostile = [ + "``` `", + "@acme/team", + "\n# heading", + "", + "", + "\\`@octocat `", + "\n```a`b\n@octocat \n```\n", + "@octocat", + "[x](https://evil.example) ![i](https://evil.example/i.png)", + "\nTitle\n===\n", + ].join(" ") + + /** Text outside code as CommonMark reads it: escaped backticks first, then + * single-line code spans (a closed fence is kept whole by `safeText`). */ + const outsideCode = (text: string) => + text + .replace(/^ {0,3}(`{3,})[^`\n]*\n[\s\S]*?\n {0,3}\1`*[ \t]*$/gm, "") + .replace(/\\[\\`]/g, "") + .replace(/(? { + const cases: Array<[string, RegExp]> = [ + ["\\`@octocat `", /@​octocat <img/], + ["```a`b\n@octocat \n```", /^\\`\\`\\`a\\`b\n@​octocat <img src=x>\n\\`\\`\\`$/], + ["@octocat", /^&#64;octocat$/], + ["[x](https://evil.example) ![i](u)", /^\\\[x\]\(https:\/\/evil\.example\) !\\\[i\]\(u\)$/], + ["Title\n===\nmore\n---", /^Title\n\\===\nmore\n\\---$/], + ["~~~\n@kept \n~~~", /^~~~\n@kept \n~~~$/], + ] + for (const [raw, want] of cases) { + const once = safeText(raw) + expect(once).toMatch(want) + expect(safeText(once)).toBe(once) + } + expect(safeText(hostile)).toBe(safeText(safeText(hostile))) + }) + + test("inline bodies and the summary carry no live mention, heading, HTML or forged marker", () => { + const ai = makeFinding({ + severity: "warning", + category: "sql_correctness", + title: `m: ${hostile}`, + body: `See ${hostile} and more`, + file: "models/m.sql", + model: "m", + confidence: "high", + tier: "inline", + startLine: 3, + endLine: 3, + evidence: { tool: "ai-review", result: {} }, + }) + const marker = warn("m: temporary", { + file: "models/`@x`.sql", + evidenceLine: `limit 100 -- temporary ${hostile}`.replace(/\n/g, " ").slice(0, 200), + }) + const env = buildEnvelope({ findings: [ai, marker], tier: "lite", mode: "comment" }) + const bodies = inlineComments(env).comments.map((c) => c.body) + const outputs = [...bodies, renderSummary(env), renderSummary(env, { inline: false })] + for (const text of outputs) { + // Outside code: no `@name`, no raw `<`, no line-leading `#`, no link, no + // entity that decodes to `@`, no setext underline. + const plain = outsideCode(text) + expect(plain).not.toMatch(/@[\w-]/) + expect(plain).not.toMatch(/