From 5a4650681f857e32146b48d29f86fc6fd515956e Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 2 Dec 2026 12:30:49 +0530 Subject: [PATCH 1/7] fix(review): three new PII exposures that the last release blocked are reported again A UNION branch computing PII under an existing name, a schema-only source swap, and a column the raw base lacks when the base is not compiled. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 7 + docs/docs/usage/dbt-pr-review.md | 18 +- .../src/altimate/review/orchestrate.ts | 70 ++++-- .../src/altimate/review/rule-catalog.ts | 63 +++++- .../altimate/review-pii-new-exposure.test.ts | 201 ++++++++++++++++++ .../test/altimate/review-rule-catalog.test.ts | 14 +- .../opencode/test/altimate/review.test.ts | 65 +++--- 7 files changed, 383 insertions(+), 55 deletions(-) create mode 100644 packages/opencode/test/altimate/review-pii-new-exposure.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index db4ce2298a..240768fbf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 **Breaking: `dbt_cost_estimate` is BigQuery only, so Snowflake and Databricks are no longer gated by `maxScanBytes`.** The tool used to give a scan figure on Snowflake and Databricks from the warehouse planner's EXPLAIN (bytes assigned there count partitions before runtime pruning and usually overstate what runs). It now answers `supported: false` on every warehouse but BigQuery and compiles nothing, so the Claude plugin's scan check (`maxScanBytes`, 10 GiB by default) no longer holds a `dbt run`, `build` or `show` on those two warehouses; the command runs with a line saying why. On BigQuery the scan figure is unchanged, and `history: true` now also reads what a model's earlier runs cost (billed `INFORMATION_SCHEMA.JOBS` queries; see the dbt tools page). +**Breaking: in `gate` mode, `altimate review` blocks only on engine findings.** Before, any critical finding in a `blockOn` category could block, including pattern rules such as the regex PII check. Now pattern-rule findings comment but don't block unless their id is named in `rubric.blockingRules`; the AI lane never blocks. One pattern finding still blocks without being named: a highly sensitive PII column (SSN, passport or card number, date of birth) proven new when the base or the head can't be compiled. To keep another pattern rule blocking, add its id to `rubric.blockingRules`. (#1722) + +### Changed + +- **`altimate review` reads `.altimate/review.yml` from the base branch.** A PR can no longer relax the policy it is reviewed under; settings it changes are listed in the comment and take effect after merge. The `--mode` and `--severity` flags (the action's `mode` and `severity_threshold`) can only tighten a base policy, and `allowForceTier: false` rejects `--force-tier`. (#1722) +- **`altimate review` flags PII only for columns the change newly exposes**, not for PII columns the base already surfaced. Without a compiled base, a PII column is a non-blocking warning that may predate the PR, unless the base file's own SQL cannot have exposed it (it does not name the column, select `*`, or call a macro); then it is reported as new, as with a compiled base, and can block. A table read under another schema counts as the same table only when the model's code reads it by the same `ref` or `source` call on both sides. (#1721) + ## [0.12.12] - 2026-11-20 **dbt Power User features now work from the command line, and an owner can send a workspace request back for changes.** Nine new tools estimate what a dbt model or query would scan before it runs (BigQuery dry run, Snowflake and Databricks from the planner's EXPLAIN), read the last dbt run, check a model's docs coverage, report DataPilot project health, time a model's CTEs, draw its SQL graph, map raw SQL tables to `ref()` and `source()`, read the defer setting, and reply to comments on shared dbt docs. Call them with `altimate-code tool run` or from another coding agent through `mcp serve`. The new `altimate-code integrations` command connects GitHub, Jira and Linear with your own credentials. On workspaces with review on, a request can be sent back with a comment, then changed and sent again. The TUI says what changed in the workspace's skills and knowledge since your last session. Also in this release: stricter SQL checks in the tool CLI and MCP server, the agent keeps your changes instead of reverting them, `altimate review` reviews only the PR's own changes, and Snowflake key-pair login reads every private-key format. diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 47f3bfd846..7d6ea3415a 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -319,6 +319,10 @@ rubric: highly sensitive PII column proven new when the base or the head cannot be compiled, so the engine has nothing to compare (see the **PII** bullet under "What the PR comment shows"). The advisory AI lane never blocks. +- **Upgrading a `gate` setup.** Before this policy, any critical finding in a + `blockOn` category could block, including pattern rules such as the regex + PII check. Now pattern-rule findings comment but don't block. To keep a + pattern rule blocking, add its id to `rubric.blockingRules`. ### What the PR comment shows @@ -337,10 +341,16 @@ rubric: non-blocking rerun with nothing new and the same headline as the bot's last review only updates the summary. - **PII:** flagged only for PII columns the change newly exposes, not for - columns the base already surfaced. That comparison needs the base version's - SQL; when it can't be compiled, PII columns are reported as non-blocking - warnings that may predate the PR. One case still blocks without a compiled - base: the diff adds a highly sensitive column (an SSN, a passport or card + columns the base already surfaced. A table read under another schema is the + same table only when the model's own code reads it the same way on both sides + (the same `ref` or `source` call, compiled into another environment); a + changed schema or `source` in the code is a different table. That comparison + needs the base version's SQL; when it can't be compiled, a PII column is + reported as a non-blocking warning that may predate the PR, unless the base + file's own SQL cannot have exposed that output column (it does not name it, + select `*`, or call a macro): then it is reported as new, as with a + compiled base, and can block. The pattern check also blocks without a compiled + base when the diff adds a highly sensitive column (an SSN, a passport or card number, a date of birth) to a `marts/` or `reporting/` model, the base file's own SQL cannot expose it (it does not name the column, select `*`, or call a macro), and the column reaches the model's output unmasked, directly or diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 71514f86e4..bca067ecfc 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -22,6 +22,7 @@ import { type SelectItemColumn, finalOutputs, rawReach, + rawRelationsMatch, refCovered, ROOT_SCOPE, SILENT_JINJA_TAG, @@ -1037,16 +1038,19 @@ async function piiClassifyLane( // intermediate model surfacing PII is a warning, not a hard block. const highExposureLayer = /(^|\/)(marts|reporting)\//.test(file.path) // Without a compiled base, every head column counts as "introduced", so a - // pre-existing column can't be told apart: never escalate to critical then. + // pre-existing column can't be told apart: never escalate to critical then, + // unless the raw base provably lacks the output name (it cannot have exposed it). const baseUnknown = hasOldSide(file) && !ctx.engineOldSql + const rawBase = baseUnknown ? rawBaseCode(ctx.oldSql) : undefined 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 && !rawBaseLacks(rawBase, [col]) const highConfidence = p.confidence >= 0.9 - const severity: Severity = highExposureLayer && highConfidence && !lowRiskClass && !baseUnknown ? "critical" : "warning" + const severity: Severity = highExposureLayer && highConfidence && !lowRiskClass && !undecided ? "critical" : "warning" out.push( makeFinding({ severity: clampSeverity("pii_exposure", severity, highConfidence ? "high" : "medium"), @@ -1060,7 +1064,7 @@ async function piiClassifyLane( model, // Without a base, exposure is undecided: `unknown` keeps these warnings // out of the warning-pattern count, so they never block. - confidence: baseUnknown ? "unknown" : highConfidence ? "high" : "medium", + confidence: undecided ? "unknown" : highConfidence ? "high" : "medium", evidence: { tool: "altimate_core.classify_pii", result: p }, ruleKey: `pii_exposure:${col}`, }), @@ -1069,11 +1073,26 @@ async function piiClassifyLane( return { findings: out, classifiedColumns, completed: true } } -/** `baseUnknown`: the file had a previous version but its base SQL could not - * be compiled, so these columns may predate the PR. Reported as a warning - * (never blocking) instead of a critical "newly exposed" finding. */ -function piiLane(file: ChangedFile & { kind: string }, columns: string[], baseUnknown = false): Finding[] { +/** `undecided(column)`: the file had a previous version but its base SQL could + * not be compiled and its raw code does not prove the column absent, so the + * column may predate the PR. Those are reported as a warning (never blocking) + * instead of a critical "newly exposed" finding. */ +function piiLane( + file: ChangedFile & { kind: string }, + columns: string[], + undecided: (column: string) => boolean = () => false, +): Finding[] { if (file.status === "deleted" || !columns.length) return [] + const proven = columns.filter((c) => !undecided(c)) + const open = columns.filter((c) => undecided(c)) + return [ + ...piiLaneFinding(file, proven, false, "pii:exposure"), + // Its own key when beside a proven finding, so dedup keeps both. + ...piiLaneFinding(file, open, true, proven.length ? "pii:exposure:undecided" : "pii:exposure"), + ] +} +function piiLaneFinding(file: ChangedFile & { kind: string }, columns: string[], baseUnknown: boolean, ruleKey: string): Finding[] { + if (!columns.length) return [] const model = modelNameFromPath(file.path) return [ makeFinding({ @@ -1091,7 +1110,7 @@ function piiLane(file: ChangedFile & { kind: string }, columns: string[], baseUn // `unknown`: undecided exposure never counts toward the warning pattern. confidence: baseUnknown ? "unknown" : "high", evidence: { tool: "schema.detect_pii", result: { columns } }, - ruleKey: "pii:exposure", + ruleKey, }), ] } @@ -1282,8 +1301,25 @@ export async function runReview(input: OrchestrateInput): Promise ({ base: outputs(file, "old").prefixes }) + // tables under different prefixes, which `refCovered` then ignores, but only + // for tables the raw model code names the same way on both sides. + const envByFile = new Map() + const envOf = (file: string): RelationPrefixes => { + let env = envByFile.get(file) + if (!env) { + const ctx = ctxByPath.get(file) + // Parsed only when a prefix difference needs it: it re-parses both raw sides. + let same: Set | undefined + env = { + base: outputs(file, "old").prefixes, + get sameRelation() { + return (same ??= rawRelationsMatch(ctx?.oldSql, ctx?.newSql)) + }, + } + envByFile.set(file, env) + } + return env + } // `source.column` refs the base exposed raw under a name its PII detection // reported: named in its final select, or passed through its plain `*` // (`select * from customers` exposes `customers.ssn` when `ssn` is base PII). @@ -1340,7 +1376,12 @@ export async function runReview(input: OrchestrateInput): Promise refCovered(ref, exposed, envOf(file))) + const covered = (ref: string) => refCovered(ref, exposed, envOf(file)) + if (![...rawColumns].every(covered)) return false + // A later UNION branch may compute the name from other columns (base raw + // `email` → head adds `lower(ssn) as email`): the raw match alone is not + // proof, so uncovered reads fall through to the comparison below. + if ([...(head.reads.get(name) ?? [])].every(covered)) return true } if (!basePii.has(name)) return false const base = outputs(file, "old") @@ -1438,8 +1479,13 @@ export async function runReview(input: OrchestrateInput): Promise !isBaseExposedOutput(currentCtx.file.path, col.toLowerCase(), basePii), ) + // Without a compiled base a column is undecided unless the raw base + // provably lacks that output name. const baseUnknown = hasOldSide(currentCtx.file) && !currentCtx.engineOldSql - findings.push(...piiLane(currentCtx.file, fallbackPii, baseUnknown)) + const rawBase = baseUnknown ? rawBaseCode(currentCtx.oldSql) : undefined + findings.push( + ...piiLane(currentCtx.file, fallbackPii, (col) => baseUnknown && !rawBaseLacks(rawBase, [col.toLowerCase()])), + ) } return findings })(), diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 94274f12dd..42ab9cadce 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -996,18 +996,64 @@ function splitTable(table: string): { prefix: string; name: string } { * asks only whether the base already read tables under the head's prefix. */ export interface RelationPrefixes { base: Set + /** Table own names the RAW (uncompiled) model code reads by the same relation + * text on both sides (`rawRelationsMatch`). */ + sameRelation?: Set +} + +/** A Jinja relation's own name: the last positional string argument of + * `{{ ref(…) }}` / `{{ source(…) }}`. */ +function jinjaRelationName(name: string): string | undefined { + const call = /^\{\{-?(?:ref|source)\((.*)\)-?\}\}$/.exec(name) + if (!call) return undefined + const args = [...call[1].matchAll(/(?> { + const { items, sources } = parseSelects(sql) + const scopes = new Set(items.map((i) => i.scope)) + const out = new Map>() + for (const list of sources.values()) + for (const src of list) { + if (scopes.has(src.name)) continue + const own = jinjaRelationName(src.name) ?? splitTable(src.name).name + const texts = out.get(own) + if (texts) texts.add(src.name) + else out.set(own, new Set([src.name])) + } + return out +} + +/** The table own names the raw base and head code read by exactly the same + * relation texts (the same `{{ ref(…) }}` / `{{ source(…) }}` call, or the + * same literal name). Only these may differ by prefix in compiled SQL as an + * environment change; a missing side proves nothing. */ +export function rawRelationsMatch(oldSql: string | undefined, newSql: string | undefined): Set { + const out = new Set() + if (!oldSql || !newSql) return out + const base = relationTexts(oldSql) + for (const [own, texts] of relationTexts(newSql)) { + const baseTexts = base.get(own) + if (baseTexts && baseTexts.size === texts.size && [...texts].every((t) => baseTexts.has(t))) out.add(own) + } + return out } /** * Head table `h` and base table `b` are the same table. Equal names are. With - * the same own name, an unqualified side matches a qualified one, and two - * different prefixes are different tables when the base already read tables - * under the head's prefix (that prefix exists in the base's environment, so - * the head chose another schema): base `restricted.customers` + - * `public.orders` → head `public.customers` is a swap. A head prefix the base - * never read is an environment difference: a base compiled into `dbt_prod` - * and a head into `dbt_ci_pr_42` (or a `+schema` change) read the same tables. - * Without `env`, names must be equal. + * the same own name, a prefix difference is an environment difference (a base + * compiled into `dbt_prod` and a head into `dbt_ci_pr_42`, or a `+schema` + * change) only when the raw model code reads that table by the same relation + * text on both sides (`env.sameRelation`): compiled SQL alone cannot tell a + * remap from a real swap (`masked.customers` → `raw.customers`, or + * `source('masked', …)` → `source('raw', …)`). Even then, an unqualified side + * matches a qualified one, and two different prefixes are different tables + * when the base already read tables under the head's prefix (that prefix + * exists in the base's environment, so the head chose another schema): base + * `restricted.customers` + `public.orders` → head `public.customers` is a + * swap. Without `env`, names must be equal. */ function sameTable(h: string, b: string, env?: RelationPrefixes): boolean { if (h === b) return true @@ -1015,6 +1061,7 @@ function sameTable(h: string, b: string, env?: RelationPrefixes): boolean { const x = splitTable(h) const y = splitTable(b) if (x.name !== y.name) return false + if (!env.sameRelation?.has(x.name)) return false if (!x.prefix || !y.prefix) return true return !env.base.has(x.prefix) } diff --git a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts new file mode 100644 index 0000000000..792f24c78d --- /dev/null +++ b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts @@ -0,0 +1,201 @@ +import { describe, test, expect } from "bun:test" +import { runReview, DEFAULT_RUBRIC, DEFAULT_REVIEW_CONFIG, type ReviewRunner, type ChangedFile } from "../../src/altimate/review" + +// The PII check reports only columns a change NEWLY exposes, and is one-sided: +// when it cannot tell, it reports. Three shapes it used to wave through: +// 1. a UNION branch that computes PII under a name the first branch already had; +// 2. a schema-only source swap, read as a dev/prod environment difference; +// 3. no compiled base, but the raw base provably lacks the output name. + +const base: ReviewRunner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [] } + }, + async equivalence() { + return { decided: false } + }, + async detectPii() { + return { columns: [] } + }, +} as any +// Output names a PII source column reaches: its aliases, else the column itself. +const outputNames = (sql: string, col: string): string[] => { + const aliases = [...sql.matchAll(new RegExp(`\\b${col}\\s+as\\s+(\\w+)`, "gi"))].map((m) => m[1]) + if (aliases.length) return aliases + return new RegExp(`\\b${col}\\b`, "i").test(sql) ? [col] : [] +} +const piiRunner = (cols: string[], classify: ReviewRunner["classifyPii"] = async () => []): ReviewRunner => ({ + ...base, + async detectPii(sql: string) { + return { columns: [...new Set(cols.flatMap((c) => outputNames(sql, c)))] } + }, + async columnLineage(sql: string) { + return ["customer_id", ...cols].flatMap((c) => outputNames(sql, c).map((target) => ({ source: `customers.${c}`, target }))) + }, + classifyPii: classify, +}) +const classifyAll = (re: RegExp) => async (cols: string[]) => + cols.map((c) => ({ column: c, classification: re.test(c) ? "PII" : "none", confidence: re.test(c) ? 0.95 : 0.1 })) +const P = "models/marts/m.sql" +const run = async (o: { + head: string + base: string + diff: string + reviewers: string[] + runner: ReviewRunner + compiled?: (side: "old" | "new") => string | undefined +}) => { + const env = await runReview({ + changedFiles: [{ path: P, status: "modified", diff: o.diff } as ChangedFile], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: o.reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: o.runner, + getContent: async (_f: string, side: "old" | "new") => (side === "new" ? o.head : o.base), + getCompiled: o.compiled ? async (_f: string, side: "old" | "new") => o.compiled!(side) : undefined, + }) + const pii = env.findings.filter((f) => f.category === "pii_exposure") + return { + verdict: env.verdict, + pii, + critical: pii.some((f) => f.severity === "critical"), + } +} +const REVIEWER_SETS = [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []] +const expectBlocks = (r: Awaited>, label: unknown) => + expect({ label, verdict: r.verdict, critical: r.critical }).toEqual({ label, verdict: "REQUEST_CHANGES", critical: true }) + +describe("1: a UNION branch that computes PII under a name the first branch had", () => { + const baseSql = "select customer_id, email from customers" + const runner = () => piiRunner(["email"]) + + test("`lower(ssn) as email` in a new branch is new exposure", async () => { + const head = `${baseSql}\nunion all\nselect customer_id, lower(ssn) as email from secrets` + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) { + const r = await run({ base: baseSql, head, diff: "+union all\n+select customer_id, lower(ssn) as email from secrets\n", reviewers, runner: runner() }) + expectBlocks(r, reviewers) + expect(r.pii.some((f) => f.evidence?.tool === "schema.detect_pii")).toBe(true) + } + }) + + test("a raw `ssn as email` branch still blocks", async () => { + const head = `${baseSql}\nunion all\nselect customer_id, ssn as email from secrets` + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks(await run({ base: baseSql, head, diff: "+union all\n+select customer_id, ssn as email from secrets\n", reviewers, runner: runner() }), reviewers) + }) + + test("a branch over the same source column is not new", async () => { + for (const branch of ["select customer_id, email from customers where customer_id < 0", "select customer_id, lower(email) as email from customers"]) { + const head = `${baseSql}\nunion all\n${branch}` + for (const reviewers of REVIEWER_SETS) { + const r = await run({ base: baseSql, head, diff: `+union all\n+${branch}\n`, reviewers, runner: runner() }) + expect({ reviewers, branch, pii: r.pii.map((f) => f.title) }).toEqual({ reviewers, branch, pii: [] }) + } + } + }) + + test("the same union already in the base is not new", async () => { + const union = `${baseSql}\nunion all\nselect customer_id, lower(ssn) as email from secrets` + for (const reviewers of REVIEWER_SETS) { + const r = await run({ base: union, head: `-- unioned contacts\n${union}`, diff: "+-- unioned contacts\n", reviewers, runner: runner() }) + expect({ reviewers, pii: r.pii.map((f) => f.title) }).toEqual({ reviewers, pii: [] }) + } + }) +}) + +describe("2: a schema-only source swap is a different table unless the raw code names it the same way", () => { + const runner = () => piiRunner(["ssn"]) + + test("a literal `masked.customers` → `raw.customers` swap is new exposure", async () => { + const b = "select customer_id, ssn from masked.customers" + const h = "select customer_id, ssn from raw.customers" + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks(await run({ base: b, head: h, diff: `-${b}\n+${h}\n`, reviewers, runner: runner() }), reviewers) + }) + + test("`source('masked', …)` → `source('raw', …)` is new exposure", async () => { + const raw = (schema: string) => `select customer_id,\n ssn\nfrom {{ source('${schema}', 'customers') }}` + const compiled = (side: "old" | "new") => `select customer_id,\n ssn\nfrom analytics.${side === "old" ? "masked" : "raw"}.customers` + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks( + await run({ + base: raw("masked"), + head: raw("raw"), + diff: "-from {{ source('masked', 'customers') }}\n+from {{ source('raw', 'customers') }}\n", + reviewers, + runner: runner(), + compiled, + }), + reviewers, + ) + }) + + test("the same `ref` compiled into another schema stays quiet", async () => { + const b = "select customer_id,\n ssn\nfrom {{ ref('customers') }}" + const h = b.replace("select customer_id,", "select customer_id, region,") + const compiled = (side: "old" | "new") => + (side === "old" ? b : h).replace("{{ ref('customers') }}", side === "old" ? "prod.customers" : "dev_x.customers") + for (const reviewers of REVIEWER_SETS) { + const r = await run({ base: b, head: h, diff: "-select customer_id,\n+select customer_id, region,\n", reviewers, runner: runner(), compiled }) + expect({ reviewers, pii: r.pii.map((f) => f.title), verdict: r.verdict === "REQUEST_CHANGES" }).toEqual({ reviewers, pii: [], verdict: false }) + } + }) +}) + +describe("3: without a compiled base, a column the raw base provably lacks blocks", () => { + const ref = "{{ ref('stg_customers') }}" + const compiledHead = (h: string) => (side: "old" | "new") => (side === "new" ? h.replace(ref, "analytics.stg_customers") : undefined) + + for (const col of ["email", "national_id", "iban"]) { + test(`\`${col}\` added over a raw base that lacks it is new exposure`, async () => { + const b = `select customer_id\nfrom ${ref}` + const h = `select customer_id,\n ${col}\nfrom ${ref}` + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []]) + expectBlocks( + await run({ base: b, head: h, diff: `+ ${col}\n`, reviewers, runner: piiRunner([col], classifyAll(new RegExp(col))), compiled: compiledHead(h) }), + { col, reviewers }, + ) + }) + } + + test("a raw base that may expose the column keeps it a non-blocking warning", async () => { + const h = `select customer_id,\n email\nfrom ${ref}` + const bases = { + star: `select *\nfrom ${ref}`, + names: `select customer_id\nfrom ${ref}\nwhere email is not null`, + macro: `select {{ dbt_utils.star(ref('stg_customers'), except=['customer_id']) }}, customer_id\nfrom ${ref}`, + } + for (const [kind, b] of Object.entries(bases)) + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []]) { + const r = await run({ base: b, head: h, diff: "+ email\n", reviewers, runner: piiRunner(["email"], classifyAll(/email/)), compiled: compiledHead(h) }) + expect({ kind, reviewers, reported: r.pii.length > 0, critical: r.critical, verdict: r.verdict }).toEqual({ + kind, + reviewers, + reported: true, + critical: false, + verdict: "COMMENT", + }) + expect(r.pii.every((f) => f.confidence === "unknown")).toBe(true) + } + }) + + test("a renamed output (`email as contact`) is reported: the base never named `contact`", async () => { + // The proof is about the output name the base would need to expose. The raw + // base names only `email`, so it cannot have exposed `contact`; without a + // compiled base nothing shows `contact` carries the same values, so the + // one-sided answer is to report it. + const b = `select customer_id,\n email\nfrom ${ref}` + const h = `select customer_id,\n email as contact\nfrom ${ref}` + for (const reviewers of [["pii_exposure"], []]) + expectBlocks( + await run({ base: b, head: h, diff: "- email\n+ email as contact\n", reviewers, runner: piiRunner(["email"], classifyAll(/email|contact/)), compiled: compiledHead(h) }), + reviewers, + ) + }) +}) diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 07bbbb7e92..8f5a1831cb 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -238,20 +238,26 @@ describe("finalOutputs().raw", () => { test("`refCovered` compares database/schema only within one environment", () => { const prod = new Set(["analytics.dbt_prod.customers.ssn"]) // Different environments: the head reads under `analytics.dbt_ci_pr_42`, which the base never read. - const envs = { base: new Set(["analytics.dbt_prod"]) } + // `sameRelation`: the raw model code reads `customers` by the same relation text on both sides. + const sameRelation = new Set(["customers"]) + const envs = { base: new Set(["analytics.dbt_prod"]), sameRelation } expect(refCovered("analytics.dbt_ci_pr_42.customers.ssn", prod, envs)).toBe(true) expect(refCovered("analytics.dbt_ci_pr_42.spouses.ssn", prod, envs)).toBe(false) // An unqualified side matches a qualified one. expect(refCovered("customers.ssn", prod, envs)).toBe(true) // Both schemas read on both sides: the prefix is compared. - const both = { base: new Set(["restricted", "public"]) } + const both = { base: new Set(["restricted", "public"]), sameRelation } expect(refCovered("public.customers.ssn", new Set(["restricted.customers.ssn"]), both)).toBe(false) // The base already read `public`: moving `customers` there is a swap. - const swap = { base: new Set(["restricted", "public"]) } + const swap = { base: new Set(["restricted", "public"]), sameRelation } expect(refCovered("public.customers.ssn", new Set(["restricted.customers.ssn"]), swap)).toBe(false) // A single-table swap to a schema the base never read looks like an environment change. - const alone = { base: new Set(["restricted"]) } + const alone = { base: new Set(["restricted"]), sameRelation } expect(refCovered("public.customers.ssn", new Set(["restricted.customers.ssn"]), alone)).toBe(true) + // Unless the raw code names it differently (or cannot say): a real swap. + const rawDiffers = { base: new Set(["restricted"]) } + expect(refCovered("public.customers.ssn", new Set(["restricted.customers.ssn"]), rawDiffers)).toBe(false) + expect(refCovered("customers.ssn", prod, { base: new Set(["analytics.dbt_prod"]) })).toBe(false) // Without an environment, names must be equal. expect(refCovered("analytics.dbt_ci_pr_42.customers.ssn", prod)).toBe(false) }) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index e7f9f0aa0e..c696a69c45 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2684,14 +2684,14 @@ describe("orchestrate", () => { expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure" && !isTwin(f)).length }).toEqual({ reviewers, pii: 0 }) }) - test("a table moved to another schema: quiet as an environment change, reported when the base read that schema", async () => { - // One schema on each side (`analytics` → `raw_restricted`): indistinguishable - // from a base compiled into another environment, so not new exposure. + test("a table moved to another schema in the model's own code is a different source", async () => { + // One schema on each side (`analytics` → `raw_restricted`): the raw model code + // names the table differently, so it is a swap, not an environment change + // (the same `{{ ref }}` compiled into two schemas stays quiet, see below). const base = "select customer_id,\n ssn\nfrom analytics.customers" const head = base.replace("analytics.customers", "raw_restricted.customers") const diff = "-from analytics.customers\n+from raw_restricted.customers\n" - for (const { reviewers, env } of await piiRuns(head, base, diff, ["ssn"])) - expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) + expectReportedPii(await piiRuns(head, base, diff, ["ssn"]), ["ssn"], "none") // The base already read `raw_restricted`: moving `customers` there is a swap. const baseBoth = "select c.customer_id,\n c.ssn\nfrom analytics.customers c\njoin raw_restricted.orders o using (customer_id)" const headBoth = baseBoth.replace("analytics.customers", "raw_restricted.customers") @@ -2749,19 +2749,23 @@ describe("orchestrate", () => { expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) expect(env.verdict).not.toBe("REQUEST_CHANGES") } - // An unqualified column over a join compiled into other schemas is the same exposure. - const joined = (schema: string) => - `select customer_id,\n ssn\nfrom analytics.${schema}.customers c\njoin raw.crm.orders o on true` - const joinRuns = await piiRuns(joined("dbt_ci").replace("customer_id,", "customer_id, region,"), joined("dbt_prod"), "-select customer_id,\n+select customer_id, region,\n", ["ssn"]) + // An unqualified column over a join compiled into other schemas is the same + // exposure (the raw model code reads both tables the same way on both sides). + const joined = (customers: string) => `select customer_id,\n ssn\nfrom ${customers} c\njoin {{ source('crm', 'orders') }} o on true` + const joinedRaw = joined("{{ ref('customers') }}") + const joinedCompiled = (schema: string) => joined(`analytics.${schema}.customers`).replace("{{ source('crm', 'orders') }}", "raw.crm.orders") + const widen = (sql: string) => sql.replace("customer_id,", "customer_id, region,") + const joinRuns = await piiRuns(widen(joinedRaw), joinedRaw, "-select customer_id,\n+select customer_id, region,\n", ["ssn"], { + head: widen(joinedCompiled("dbt_ci")), + base: joinedCompiled("dbt_prod"), + }) for (const { reviewers, env } of joinRuns) expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) - // An unqualified base table and a qualified head table are the same table too. - const quiet = await piiRuns( - "select customer_id,\n ssn\nfrom analytics.customers", - "select customer_id,\n ssn\nfrom customers", - "-from customers\n+from analytics.customers\n", - ["ssn"], - ) + // An unqualified compiled base table and a qualified head table are the same table too. + const quiet = await piiRuns(widen(raw), raw, "-select customer_id,\n+select customer_id, region,\n", ["ssn"], { + head: widen(raw).replace("{{ ref('customers') }}", "analytics.customers"), + base: raw.replace("{{ ref('customers') }}", "customers"), + }) for (const { reviewers, env } of quiet) expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) }) @@ -3526,20 +3530,27 @@ describe("orchestrate", () => { }) test("the broad PII fallback without a compiled base is an unknown-confidence warning", async () => { - const env = await runReview({ - changedFiles: [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ ssn\n" }], - config: { ...DEFAULT_REVIEW_CONFIG }, - rubric: DEFAULT_RUBRIC, - mode: "gate", - runner: piiRunner(["ssn"], async () => { - throw new Error("classifier unavailable") - }), - getContent: content("select customer_id, ssn from customers", "select customer_id from {{ ref('customers') }}"), - }) - const fallback = env.findings.filter((f) => f.evidence?.tool === "schema.detect_pii") + const fallbackOf = async (rawBase: string) => { + const env = await runReview({ + changedFiles: [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ ssn\n" }], + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"], async () => { + throw new Error("classifier unavailable") + }), + getContent: content("select customer_id, ssn from customers", rawBase), + }) + return env.findings.filter((f) => f.evidence?.tool === "schema.detect_pii") + } + // A raw base that may expose `ssn` (a `*`) leaves the column undecided. + const fallback = await fallbackOf("select * from {{ ref('customers') }}") expect(fallback.length).toBe(1) expect(fallback[0].severity).toBe("warning") expect(fallback[0].confidence).toBe("unknown") + // A raw base that provably lacks `ssn` cannot have exposed it: new exposure. + const proven = await fallbackOf("select customer_id from {{ ref('customers') }}") + expect(proven.map((f) => [f.severity, f.confidence])).toEqual([["critical", "high"]]) }) test("case-variant PII detector output does not duplicate core diff-scoped finding", async () => { From 2e7c0f1ab471550fca31cff67e53141c40a015e3 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 2 Dec 2026 13:12:25 +0530 Subject: [PATCH 2/7] fix(review): review fixes: no false block for aliased models, and a Jinja schema swap is seen The same-relation check compares the original relation text, and no longer needs the compiled table name to match the `ref` argument. A UNION name the base already computed the same way is not re-reported. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 5 +- docs/docs/usage/dbt-pr-review.md | 41 +++-- .../src/altimate/review/orchestrate.ts | 80 +++++++--- .../src/altimate/review/rule-catalog.ts | 147 +++++++++++++----- .../altimate/review-pii-new-exposure.test.ts | 147 +++++++++++++++++- .../test/altimate/review-rule-catalog.test.ts | 2 +- 6 files changed, 347 insertions(+), 75 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 240768fbf0..16147345df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,12 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 **Breaking: `dbt_cost_estimate` is BigQuery only, so Snowflake and Databricks are no longer gated by `maxScanBytes`.** The tool used to give a scan figure on Snowflake and Databricks from the warehouse planner's EXPLAIN (bytes assigned there count partitions before runtime pruning and usually overstate what runs). It now answers `supported: false` on every warehouse but BigQuery and compiles nothing, so the Claude plugin's scan check (`maxScanBytes`, 10 GiB by default) no longer holds a `dbt run`, `build` or `show` on those two warehouses; the command runs with a line saying why. On BigQuery the scan figure is unchanged, and `history: true` now also reads what a model's earlier runs cost (billed `INFORMATION_SCHEMA.JOBS` queries; see the dbt tools page). -**Breaking: in `gate` mode, `altimate review` blocks only on engine findings.** Before, any critical finding in a `blockOn` category could block, including pattern rules such as the regex PII check. Now pattern-rule findings comment but don't block unless their id is named in `rubric.blockingRules`; the AI lane never blocks. One pattern finding still blocks without being named: a highly sensitive PII column (SSN, passport or card number, date of birth) proven new when the base or the head can't be compiled. To keep another pattern rule blocking, add its id to `rubric.blockingRules`. (#1722) +**Breaking: in `gate` mode, `altimate review` blocks only on engine findings, on pattern rules named in `rubric.blockingRules`, and on one proven-new PII pattern finding.** Before, any critical finding in a `blockOn` category could block, including pattern rules such as the regex PII check. Now pattern-rule findings comment but don't block unless their id is named in `rubric.blockingRules`; the AI lane never blocks. One pattern finding still blocks without being named: a highly sensitive PII column (SSN, passport or card number, date of birth) proven new when the base or the head can't be compiled. To keep another pattern rule blocking, add its id to `rubric.blockingRules`. (#1722) ### Changed - **`altimate review` reads `.altimate/review.yml` from the base branch.** A PR can no longer relax the policy it is reviewed under; settings it changes are listed in the comment and take effect after merge. The `--mode` and `--severity` flags (the action's `mode` and `severity_threshold`) can only tighten a base policy, and `allowForceTier: false` rejects `--force-tier`. (#1722) -- **`altimate review` flags PII only for columns the change newly exposes**, not for PII columns the base already surfaced. Without a compiled base, a PII column is a non-blocking warning that may predate the PR, unless the base file's own SQL cannot have exposed it (it does not name the column, select `*`, or call a macro); then it is reported as new, as with a compiled base, and can block. A table read under another schema counts as the same table only when the model's code reads it by the same `ref` or `source` call on both sides. (#1721) +- **`altimate review` flags PII only for columns the change newly exposes**, not for PII columns the base already surfaced. Without a compiled base, a PII column is a non-blocking warning that may predate the PR. (#1721) +- **`altimate review` reports three PII exposures it used to call pre-existing.** Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, selects no `*` or `COLUMNS(…)`, and holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. A renamed PII output (`email as contact`) is then new. A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name, quote style and spacing aside), or, for a model compiled under a name its `ref` does not show (an alias or a version), when no relation in the model's code changed; a schema, `source` or `var` swapped in the code is reported. A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported. (#1875) ## [0.12.12] - 2026-11-20 diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 7d6ea3415a..9930180575 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -321,8 +321,9 @@ rubric: "What the PR comment shows"). The advisory AI lane never blocks. - **Upgrading a `gate` setup.** Before this policy, any critical finding in a `blockOn` category could block, including pattern rules such as the regex - PII check. Now pattern-rule findings comment but don't block. To keep a - pattern rule blocking, add its id to `rubric.blockingRules`. + PII check. Now pattern-rule findings comment but don't block, except the one + highly sensitive PII finding described in the previous bullet. To keep + another pattern rule blocking, add its id to `rubric.blockingRules`. ### What the PR comment shows @@ -342,18 +343,30 @@ rubric: review only updates the summary. - **PII:** flagged only for PII columns the change newly exposes, not for columns the base already surfaced. A table read under another schema is the - same table only when the model's own code reads it the same way on both sides - (the same `ref` or `source` call, compiled into another environment); a - changed schema or `source` in the code is a different table. That comparison - needs the base version's SQL; when it can't be compiled, a PII column is - reported as a non-blocking warning that may predate the PR, unless the base - file's own SQL cannot have exposed that output column (it does not name it, - select `*`, or call a macro): then it is reported as new, as with a - compiled base, and can block. The pattern check also blocks without a compiled - base when the diff adds a highly sensitive column (an SSN, a passport or card - number, a date of birth) to a `marts/` or `reporting/` model, the base file's - own SQL cannot expose it (it does not name the column, select `*`, or call a - macro), and the column reaches the model's output unmasked, directly or + same table only when the model's own code reads it the same way on both sides, + compiled into another environment: the same `ref` or `source` call or table + name (quote style and spacing aside). A model whose compiled table name is not + the name in its `ref` (an `alias`, a version such as `ref('customers', v=2)`, + a custom alias macro) counts as the same table only when no `ref`, `source` or + table name in the model's code changed. A changed schema, `source`, `var` or + package argument in the code is a different table, and so, under another + schema, is a quoted name whose case changed. A source whose schema changes + only in `sources.yml` or in a var, with the model's code unchanged, is not + detected as a swap. That + comparison needs the base version's SQL; when it can't be compiled, a PII + column is reported as a non-blocking warning that may predate the PR, unless + the base file's own SQL cannot have exposed that output column name: then it + is reported as new, as with a compiled base, and can block. The base cannot + have exposed the name when it does not name it anywhere outside comments + (string literals count), selects no `*` and no dynamic column selector + (`COLUMNS(…)`), and holds no Jinja but `ref`, `source`, `config`, `this` and + `if`/`for`/`set` tags (a macro call, a variable or an `{% include %}` could + emit any column). The proof is about the output name, so a renamed PII output + (`email as contact`) is reported as new. The pattern check also blocks + without a compiled base when the diff adds a highly sensitive column (an SSN, + a passport or card number, a date of birth) to a `marts/` or `reporting/` + model, the base file's own SQL cannot expose that column (by the same test), + and the column reaches the model's output unmasked, directly or through CTEs and subqueries, from the added line or from anywhere else in the model. A column that is hashed, masked or dropped everywhere it is read (`sha2(ssn)`, `right(ssn, 4)`, `* exclude (ssn)`) stays a warning; one that diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index bca067ecfc..dcebdd8ecd 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -993,6 +993,8 @@ async function piiClassifyLane( ctx: ModelContext, runner: ReviewRunner, dialect: string, + /** The file's raw base as `rawBaseCode` reads it, parsed once per file. */ + baseCode: () => string | undefined, ): Promise<{ findings: Finding[]; classifiedColumns: Set; completed: boolean }> { const empty = { findings: [], classifiedColumns: new Set(), completed: false } if (!runner.classifyPii) return empty @@ -1041,14 +1043,13 @@ async function piiClassifyLane( // pre-existing column can't be told apart: never escalate to critical then, // unless the raw base provably lacks the output name (it cannot have exposed it). const baseUnknown = hasOldSide(file) && !ctx.engineOldSql - const rawBase = baseUnknown ? rawBaseCode(ctx.oldSql) : undefined 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 && !rawBaseLacks(rawBase, [col]) + const undecided = baseUnknown && !rawBaseLacks(baseCode(), [col]) const highConfidence = p.confidence >= 0.9 const severity: Severity = highExposureLayer && highConfidence && !lowRiskClass && !undecided ? "critical" : "warning" out.push( @@ -1142,11 +1143,13 @@ interface ModelContext { * column, so any other tag proves nothing. String literals still count as * evidence: a JSON path (`payload:ssn`, `'$.ssn'`) can expose the column. * A `*` is any `*` token not preceded by a word (`*`, `c.*`, `*except(email)`, - * `as struct *`, `object_construct(*)`); `count(*)` reads no column. Spaced - * multiplication (`a * b`) also matches, which only leaves the base undecided. + * `as struct *`, `object_construct(*)`, `* like 'e%'`); `count(*)` reads no + * column. Spaced multiplication (`a * b`) also matches, which only leaves the + * base undecided. A DuckDB `COLUMNS(…)` selector picks columns by a pattern or + * a lambda (`COLUMNS('^e')`), so it counts like a `*`. */ const RAW_BASE_PLAIN_EXPR = /^\{\{-?\s*(?:(?:ref|source|config)\s*\([^{}]*\)|this)\s*-?\}\}$/ -const RAW_BASE_STAR = /(?:^|[\s.(])\*(?=\s|$|[a-z(),])/i +const RAW_BASE_STAR = /(?:^|[\s.(])\*(?=\s|$|[a-z(),])|(? | undefined + let same: ((table: string) => boolean) | undefined env = { base: outputs(file, "old").prefixes, - get sameRelation() { - return (same ??= rawRelationsMatch(ctx?.oldSql, ctx?.newSql)) - }, + sameRelation: (table) => (same ??= rawRelationsMatch(ctx?.oldSql, ctx?.newSql))(table), } envByFile.set(file, env) } @@ -1380,8 +1381,21 @@ export async function runReview(input: OrchestrateInput): Promise() + const baseLineage = base.lineage.get(name) + if ( + reads.every((ref) => covered(ref) || refCovered(ref, baseReads, envOf(file))) && + !!baseLineage && + [...(head.lineage.get(name) ?? [])].every((sig) => baseLineage.has(sig)) + ) + return true } if (!basePii.has(name)) return false const base = outputs(file, "old") @@ -1409,6 +1423,13 @@ export async function runReview(input: OrchestrateInput): Promise 0 && [...starRefs].every((ref) => refCovered(ref, exposed, envOf(file))) } + // The raw base as `rawBaseLacks` reads it, parsed once per file and only when + // a PII lane needs it (the engine lanes and the regex twins share it). + const rawBaseCodeByFile = new Map() + const baseCode = (file: string) => { + if (!rawBaseCodeByFile.has(file)) rawBaseCodeByFile.set(file, rawBaseCode(ctxByPath.get(file)?.oldSql)) + return rawBaseCodeByFile.get(file) + } for (const ctx of ctxByPath.values()) { const tasks: Promise[] = [] // Engine lanes consume COMPILED SQL (rendered by dbt) when available. @@ -1445,7 +1466,7 @@ export async function runReview(input: OrchestrateInput): Promise { - const diffScopedPii = await piiClassifyLane(currentCtx, input.runner, dialect) + const diffScopedPii = await piiClassifyLane(currentCtx, input.runner, dialect, () => baseCode(currentCtx.file.path)) if (diffScopedPii.completed) { diffScopedPiiCompletedFiles.add(currentCtx.file.path) classifiedPiiColumnsByFile.set(currentCtx.file.path, diffScopedPii.classifiedColumns) @@ -1482,9 +1503,12 @@ export async function runReview(input: OrchestrateInput): Promise baseUnknown && !rawBaseLacks(rawBase, [col.toLowerCase()])), + ...piiLane( + currentCtx.file, + fallbackPii, + (col) => baseUnknown && !rawBaseLacks(baseCode(currentCtx.file.path), [col.toLowerCase()]), + ), ) } return findings @@ -1586,6 +1610,27 @@ export async function runReview(input: OrchestrateInput): Promise f.category === "pii_exposure" && f.evidence?.tool === "schema.detect_pii").map((f) => f.file), ) + // Per file, the output columns an engine PII lane reported as new (not + // undecided), at the highest severity it gave each. A regex twin for such a + // column at no higher severity only repeats that finding. + const enginePiiByFile = new Map>() + for (const f of flat) { + if (f.category !== "pii_exposure" || f.confidence === "unknown") continue + const result = (f.evidence?.result ?? {}) as { column?: string; columns?: string[] } + const tool = f.evidence?.tool + const columns = tool === "altimate_core.classify_pii" ? [result.column] : tool === "schema.detect_pii" ? (result.columns ?? []) : [] + for (const c of columns) { + if (!c) continue + const perFile = enginePiiByFile.get(f.file) ?? new Map() + const prev = perFile.get(c.toLowerCase()) + if (!prev || SEVERITY_ORDER[f.severity] > SEVERITY_ORDER[prev]) perFile.set(c.toLowerCase(), f.severity) + enginePiiByFile.set(f.file, perFile) + } + } + const engineReported = (twin: Finding, output: string) => { + const severity = enginePiiByFile.get(twin.file)?.get(output.toLowerCase()) + return !!severity && SEVERITY_ORDER[severity] >= SEVERITY_ORDER[twin.severity] + } // Per file, the concatenated rule names core's AST lint actually emitted — // so we suppress a regex twin only when core genuinely covered that concern. const coreRulesByFile = new Map() @@ -1695,11 +1740,6 @@ export async function runReview(input: OrchestrateInput): Promise() - const baseCode = (file: string) => { - if (!rawBaseCodeByFile.has(file)) rawBaseCodeByFile.set(file, rawBaseCode(ctxByPath.get(file)?.oldSql)) - return rawBaseCodeByFile.get(file) - } // Asked for each twin in the dedup and again for its severity: kept per finding // (per-token twins share a fingerprint, so the finding itself is the key). const provenByFinding = new WeakMap() @@ -1757,6 +1797,7 @@ export async function runReview(input: OrchestrateInput): Promise isReindented(f.file, i.line) || isBaseExposed(f.file, i.column, i.alias, i.line))) return false + if (items.length && items.every((i) => engineReported(f, i.alias ?? i.column))) return false // Otherwise suppress only when a precise detector actually EMITTED a PII // finding for the file (so the exposure is reported by the better source, // not silently dropped). diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 42ab9cadce..fee62df0bb 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -2,6 +2,7 @@ import { type Finding, type Severity, type ReviewCategory, makeFinding } from ". import { type ChangedFile, fileKind } from "./diff-filter" import { type Rubric, clampSeverity, exclusionReason } from "./rubric" import path from "node:path" +import { createHash } from "node:crypto" /** * Declarative rule catalog for dbt/SQL PR review. @@ -412,6 +413,8 @@ interface Source { /** A schema-qualified table's last segment, which a column qualifier names it by. */ short?: string alias?: string + /** A table's relation exactly as the SQL writes it (Jinja and quoting kept). */ + text?: string } interface ParsedSelects { @@ -807,6 +810,7 @@ function parseSelects(sql: string): ParsedSelects { const lead = after + (/^\s*/.exec(s.slice(after, after + 200))?.[0].length ?? 0) let name: string | undefined let short: string | undefined + let text: string | undefined let rest = lead if (s[lead] === "(") { // A FROM subquery is a source under its alias; any other parenthesis @@ -827,12 +831,14 @@ function parseSelects(sql: string): ParsedSelects { // and `public.customers` are different tables. name = [...segments.slice(0, -1).map(unquote), short].join(".") rest = after + ref[0].length + text = sql.slice(rest - ref[1].length, rest) } } if (name) { const aliased = aliasRe.exec(s.slice(rest, rest + 200)) const alias = aliased?.[1] const src: Source = short && short !== name ? { name, short } : { name } + if (text !== undefined) src.text = text if (alias && !NOT_A_SOURCE_ALIAS.has(unquote(alias))) { src.alias = unquote(alias) // `from c as t(x, y)` renames a CTE's or a subquery's columns. @@ -965,6 +971,12 @@ export interface FinalOutputs { * literals as written, each FROM/JOIN alias named by its source) plus the * full text of every CTE or subquery its select reads. Equal signatures on two sides mean the name is computed the same way. */ signatures: Map> + /** Per output name, as `signatures` but following columns, not whole bodies: + * the item text plus, per CTE or subquery it reads, that scope's `lineage` + * of each column the item names (the scope's whole body when a `*` there may + * pass the column on). Another column or a filter added to that CTE leaves it + * unchanged; unmasking the column there (`md5(ssn) as ssn` → `ssn`) does not. */ + lineage: Map> /** Per output name, every `source.column` ref its value is computed from, raw * or not, resolved like `raw` (`lower(s.ssn) as email` with `spouses s` → * `email: {spouses.ssn}`; through a CTE, what that CTE's column reads). */ @@ -996,57 +1008,101 @@ function splitTable(table: string): { prefix: string; name: string } { * asks only whether the base already read tables under the head's prefix. */ export interface RelationPrefixes { base: Set - /** Table own names the RAW (uncompiled) model code reads by the same relation - * text on both sides (`rawRelationsMatch`). */ - sameRelation?: Set + /** The compiled table own name may differ by prefix as an environment change: + * the RAW (uncompiled) model code reads it the same way on both sides + * (`rawRelationsMatch`). */ + sameRelation?: (table: string) => boolean } -/** A Jinja relation's own name: the last positional string argument of - * `{{ ref(…) }}` / `{{ source(…) }}`. */ -function jinjaRelationName(name: string): string | undefined { - const call = /^\{\{-?(?:ref|source)\((.*)\)-?\}\}$/.exec(name) - if (!call) return undefined - const args = [...call[1].matchAll(/(? { + if (m.startsWith('"') || m.startsWith("`")) return m + if (!m.startsWith("{{")) return m.replace(/\s+/g, "").toLowerCase() + const call = m.replace(/^\{\{[-+]?/, "").replace(/[-+]?\}\}$/, "") + const flat = call.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|\s+/g, (t) => + t.startsWith("'") || t.startsWith('"') ? `'${t.slice(1, -1)}'` : "", + ) + return `{{${flat}}}` + }) +} + +/** A normalised relation's own name, lowercased to compare with a compiled + * name: the last positional string argument of `{{ ref(…) }}` / `{{ source(…) }}`, + * else its last dot-separated segment outside Jinja and quotes. */ +function relationOwnName(text: string): string { + const call = /^\{\{(?:ref|source)\((.*)\)\}\}$/.exec(text) + if (call) { + const args = [...call[1].matchAll(/(?> { - const { items, sources } = parseSelects(sql) +/** Per own name, the normalised relation texts `sql` reads tables by, and + * whether every source was named (`complete`). */ +function relationTexts(sql: string): { byName: Map>; all: Set; complete: boolean } { + const { items, sources, unknownSources } = parseSelects(sql) const scopes = new Set(items.map((i) => i.scope)) - const out = new Map>() + const byName = new Map>() + const all = new Set() for (const list of sources.values()) for (const src of list) { - if (scopes.has(src.name)) continue - const own = jinjaRelationName(src.name) ?? splitTable(src.name).name - const texts = out.get(own) - if (texts) texts.add(src.name) - else out.set(own, new Set([src.name])) + if (scopes.has(src.name) || src.text === undefined) continue + // The original text, not the parser's name: that masks Jinja to `_`, so two + // prefixes of one length (`var('masked')`, `var('raw_db')`) would look alike. + const text = normalizeRelation(src.text) + const own = relationOwnName(text) + all.add(text) + const texts = byName.get(own) + if (texts) texts.add(text) + else byName.set(own, new Set([text])) } - return out + return { byName, all, complete: unknownSources.size === 0 } } -/** The table own names the raw base and head code read by exactly the same - * relation texts (the same `{{ ref(…) }}` / `{{ source(…) }}` call, or the - * same literal name). Only these may differ by prefix in compiled SQL as an - * environment change; a missing side proves nothing. */ -export function rawRelationsMatch(oldSql: string | undefined, newSql: string | undefined): Set { - const out = new Set() - if (!oldSql || !newSql) return out +/** Whether a compiled table own name may differ by prefix between base and head + * as an environment change, judged from the raw model code. A name the raw code + * reads (`ref('customers')`, `analytics.customers`) must be read by the same + * relation texts on both sides. A name it never writes (a model with an + * `alias`, a version, a custom alias macro: `ref('customers', v=2)` compiles + * to `customers_v2`) cannot be tied to one call, so every relation text must + * be unchanged and every source named. A missing side proves nothing. */ +export function rawRelationsMatch(oldSql: string | undefined, newSql: string | undefined): (table: string) => boolean { + if (!oldSql || !newSql) return () => false const base = relationTexts(oldSql) - for (const [own, texts] of relationTexts(newSql)) { - const baseTexts = base.get(own) - if (baseTexts && baseTexts.size === texts.size && [...texts].every((t) => baseTexts.has(t))) out.add(own) + const head = relationTexts(newSql) + const sameSet = (a: Set | undefined, b: Set | undefined) => + !!a && !!b && a.size === b.size && [...a].every((t) => b.has(t)) + const unchanged = base.complete && head.complete && sameSet(base.all, head.all) + return (table) => { + const a = base.byName.get(table) + const b = head.byName.get(table) + return a || b ? sameSet(a, b) : unchanged } - return out } /** * Head table `h` and base table `b` are the same table. Equal names are. With * the same own name, a prefix difference is an environment difference (a base * compiled into `dbt_prod` and a head into `dbt_ci_pr_42`, or a `+schema` - * change) only when the raw model code reads that table by the same relation - * text on both sides (`env.sameRelation`): compiled SQL alone cannot tell a + * change) only when the raw model code reads that table the same way on both + * sides (`env.sameRelation`, see `rawRelationsMatch`): compiled SQL alone cannot tell a * remap from a real swap (`masked.customers` → `raw.customers`, or * `source('masked', …)` → `source('raw', …)`). Even then, an unqualified side * matches a qualified one, and two different prefixes are different tables @@ -1061,7 +1117,7 @@ function sameTable(h: string, b: string, env?: RelationPrefixes): boolean { const x = splitTable(h) const y = splitTable(b) if (x.name !== y.name) return false - if (!env.sameRelation?.has(x.name)) return false + if (!env.sameRelation?.(x.name)) return false if (!x.prefix || !y.prefix) return true return !env.base.has(x.prefix) } @@ -1215,6 +1271,7 @@ export function finalOutputs(sql: string): FinalOutputs { const raw = new Map>() const names = new Set() const signatures = new Map>() + const lineage = new Map>() const reads = new Map>() const stars: ScopeOutputs["stars"] = [] const addTo = (map: Map>, name: string, values: Iterable) => { @@ -1239,6 +1296,7 @@ export function finalOutputs(sql: string): FinalOutputs { for (const n of out.names) names.add(n) for (const [n, cols] of out.raw) addTo(raw, n, cols) for (const [n, sigs] of out.signatures) addTo(signatures, n, [...sigs].map((sig) => `*${sig}`)) + for (const [n, sigs] of out.lineage) addTo(lineage, n, [...sigs].map((sig) => `*${src.name}:${sig}`)) for (const [n, cols] of out.reads) addTo(reads, n, cols) } continue @@ -1246,7 +1304,20 @@ export function finalOutputs(sql: string): FinalOutputs { const name = item.branch === 0 ? item.name : firstNames.get(item.position) if (!name) continue names.add(name) - addTo(signatures, name, [`${signatureText(item, scope)}\u0001${bodies.join("\u0002")}`]) + const text = signatureText(item, scope) + addTo(signatures, name, [`${text}\u0001${bodies.join("\u0002")}`]) + const columns = item.rawColumn ? [item.rawColumn] : (item.reads ?? []).map((r) => r.column) + const upstream = derived + .map((src) => { + const out = resolve(src.name, inner) + const of = (c: string) => + out.names.has(c) ? [...(out.lineage.get(c) ?? [])].sort().join("\u0005") : out.stars.length ? out.body : "" + return `${src.name}:${columns.map(of).join("\u0006")}` + }) + .sort() + // A digest, so a column computed from several upstream columns at every + // level of a CTE chain does not grow its key exponentially. + addTo(lineage, name, [createHash("sha1").update(`${text}\u0001${upstream.join("\u0002")}`).digest("base64")]) if (item.rawColumn) { const refs = resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen) addTo(raw, name, refs.raw) @@ -1262,11 +1333,11 @@ export function finalOutputs(sql: string): FinalOutputs { } for (const [n, cols] of raw) if (!cols.size) raw.delete(n) const body = [scopeItems.map((i) => signatureText(i, scope)).join(","), ...[...readBodies].sort()].join("\u0003") - const result = { raw, names, signatures, reads, stars, body } + const result = { raw, names, signatures, lineage, reads, stars, body } memo.set(scope, result) return result } - const { raw, names, signatures, reads, stars } = resolve(ROOT_SCOPE, new Set()) + const { raw, names, signatures, lineage, reads, stars } = resolve(ROOT_SCOPE, new Set()) // The raw refs a `*` passes `col` through as. Unlike an unqualified column // read over several sources (one combined ref: it comes from exactly one of // them), a `*` passes every source's columns through, so each source is @@ -1316,7 +1387,7 @@ export function finalOutputs(sql: string): FinalOutputs { union(stars.map((st) => starRefs(ROOT_SCOPE, st.branch, st.qualifier, column, new Set()))) const prefixes = new Set() for (const list of sources.values()) for (const src of list) if (!byScope.has(src.name)) prefixes.add(splitTable(src.name).prefix) - return { raw, names, signatures, reads, passthrough: stars.length > 0, starRaw, prefixes } + return { raw, names, signatures, lineage, reads, passthrough: stars.length > 0, starRaw, prefixes } } /** A Jinja statement tag that emits no text of its own: control flow and `set`. */ diff --git a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts index 792f24c78d..495fba7cd7 100644 --- a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts +++ b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts @@ -70,6 +70,8 @@ const run = async (o: { const REVIEWER_SETS = [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []] const expectBlocks = (r: Awaited>, label: unknown) => expect({ label, verdict: r.verdict, critical: r.critical }).toEqual({ label, verdict: "REQUEST_CHANGES", critical: true }) +const expectQuiet = (r: Awaited>, label: unknown) => + expect({ label, pii: r.pii.map((f) => f.title), blocks: r.verdict === "REQUEST_CHANGES" }).toEqual({ label, pii: [], blocks: false }) describe("1: a UNION branch that computes PII under a name the first branch had", () => { const baseSql = "select customer_id, email from customers" @@ -107,9 +109,35 @@ describe("1: a UNION branch that computes PII under a name the first branch had" expect({ reviewers, pii: r.pii.map((f) => f.title) }).toEqual({ reviewers, pii: [] }) } }) + + // The base already exposes `email` (raw from `customers`, computed from `s.ssn`). + const cteUnion = (cte: string, branch = "lower(ssn) as email") => + `with s as (\n select customer_id,\n ${cte}\n from secrets\n)\nselect customer_id, email from customers\nunion all\nselect customer_id, ${branch} from s` + + test("an unrelated edit to the CTE a branch reads keeps an already-exposed name quiet", async () => { + for (const [label, head, diff] of [ + ["new filter", cteUnion("ssn").replace(" from secrets\n", " from secrets\n where active\n"), "+ where active\n"], + ["new column", cteUnion("region,\n ssn"), "+ region,\n"], + ]) + for (const reviewers of REVIEWER_SETS) { + const r = await run({ base: cteUnion("ssn"), head, diff, reviewers, runner: runner() }) + expectQuiet(r, { label, reviewers }) + } + }) + + test("unmasking the column a branch computes the name from is new exposure", async () => { + // In the branch itself, and inside the CTE it reads. + const cases = [ + { base: cteUnion("ssn", "md5(ssn) as email"), head: cteUnion("ssn", "lower(ssn) as email"), diff: "-select customer_id, md5(ssn) as email from s\n+select customer_id, lower(ssn) as email from s\n" }, + { base: cteUnion("md5(ssn) as ssn"), head: cteUnion("ssn"), diff: "- md5(ssn) as ssn\n+ ssn\n" }, + ] + for (const c of cases) + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks(await run({ ...c, reviewers, runner: runner() }), { diff: c.diff, reviewers }) + }) }) -describe("2: a schema-only source swap is a different table unless the raw code names it the same way", () => { +describe("2:a schema-only source swap is a different table unless the raw code names it the same way", () => { const runner = () => piiRunner(["ssn"]) test("a literal `masked.customers` → `raw.customers` swap is new exposure", async () => { @@ -146,6 +174,76 @@ describe("2: a schema-only source swap is a different table unless the raw code expect({ reviewers, pii: r.pii.map((f) => f.title), verdict: r.verdict === "REQUEST_CHANGES" }).toEqual({ reviewers, pii: [], verdict: false }) } }) + + // Raw model code on each side, and the compiled SQL with `from` replaced. + const sides = (rawBase: string, rawHead: string, fromBase: string, fromHead: string, diff: string) => ({ + base: `select customer_id,\n ssn\nfrom ${rawBase}`, + head: `select customer_id, region,\n ssn\nfrom ${rawHead}`, + compiled: (side: "old" | "new") => + side === "old" ? `select customer_id,\n ssn\nfrom ${fromBase}` : `select customer_id, region,\n ssn\nfrom ${fromHead}`, + diff: `-select customer_id,\n+select customer_id, region,\n${diff}`, + }) + + test("the same `ref` to a model compiled under another name (alias, version) stays quiet across environments", async () => { + const cases = { + alias: sides("{{ ref('customers') }}", "{{ ref('customers') }}", "analytics.dbt_prod.customers_v2", "analytics.dbt_ci_42.customers_v2", ""), + version: sides("{{ ref('customers', v=2) }}", "{{ ref('customers', v=2) }}", "dbt_prod.customers_v2", "dbt_ci.customers_v2", ""), + } + for (const [label, c] of Object.entries(cases)) + for (const reviewers of REVIEWER_SETS) expectQuiet(await run({ ...c, reviewers, runner: runner() }), { label, reviewers }) + }) + + test("a reformatted `ref` call is the same relation", async () => { + const cases = { + quotes: sides("{{ ref('customers') }}", '{{ ref("customers") }}', "dbt_prod.customers", "dbt_ci.customers", "-from {{ ref('customers') }}\n+from {{ ref(\"customers\") }}\n"), + spacing: sides("{{ ref('customers') }}", "{{ref( 'customers' )}}", "dbt_prod.customers", "dbt_ci.customers", "-from {{ ref('customers') }}\n+from {{ref( 'customers' )}}\n"), + "quotes, aliased model": sides("{{ ref('customers') }}", '{{ ref("customers") }}', "dbt_prod.customers_v2", "dbt_ci.customers_v2", "-from {{ ref('customers') }}\n+from {{ ref(\"customers\") }}\n"), + } + for (const [label, c] of Object.entries(cases)) + for (const reviewers of REVIEWER_SETS) expectQuiet(await run({ ...c, reviewers, runner: runner() }), { label, reviewers }) + }) + + test("a compiled name no unchanged relation call explains is a different table", async () => { + const cases = { + // Two different models aliased to the same table name. + "another ref, same alias": sides("{{ ref('masked_customers') }}", "{{ ref('raw_customers') }}", "analytics.masked.customers", "analytics.dbt_ci.customers", "-x\n+y\n"), + // One-sided: `customers_v2` is tied to no unchanged call once another relation call changed. + "aliased, another ref changed": sides( + "{{ ref('customers') }} c join {{ ref('orders') }} o on true", + "{{ ref('customers') }} c join {{ ref('orders_v2') }} o on true", + "dbt_prod.customers_v2 c join dbt_prod.orders o on true", + "dbt_ci.customers_v2 c join dbt_ci.orders_v2 o on true", + "-x\n+y\n", + ), + } + for (const [label, c] of Object.entries(cases)) + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) expectBlocks(await run({ ...c, reviewers, runner: runner() }), { label, reviewers }) + }) + + test("a swapped Jinja prefix is a different table, whatever its length", async () => { + const cases = { + "same length": sides("{{ var('masked') }}.customers", "{{ var('raw_db') }}.customers", "analytics.pii_masked.customers", "analytics.pii_raw.customers", "-x\n+y\n"), + "other length": sides("{{ var('masked') }}.customers", "{{ var('rawdata') }}.customers", "analytics.pii_masked.customers", "analytics.pii_raw.customers", "-x\n+y\n"), + } + for (const [label, c] of Object.entries(cases)) + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) expectBlocks(await run({ ...c, reviewers, runner: runner() }), { label, reviewers }) + // The same Jinja prefix compiled into another schema is an environment change. + const same = sides("{{ var('db') }}.customers", "{{ var('db') }}.customers", "analytics.pii_masked.customers", "analytics.dbt_ci.customers", "") + for (const reviewers of REVIEWER_SETS) expectQuiet(await run({ ...same, reviewers, runner: runner() }), reviewers) + }) + + test("quoted relation names that differ only in case are different tables", async () => { + const c = sides('{{ var(\'db\') }}."Customers"', '{{ var(\'db\') }}."customers"', 'analytics.prod."Customers"', 'analytics.dbt_ci."customers"', "-x\n+y\n") + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) expectBlocks(await run({ ...c, reviewers, runner: runner() }), reviewers) + }) + + test("without a compile step, an unqualified name qualified in the head is reported", async () => { + // `customers` resolves through the search path, so `analytics.customers` may be another table. + const b = "select customer_id,\n ssn\nfrom customers" + const h = "select customer_id,\n ssn\nfrom analytics.customers" + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks(await run({ base: b, head: h, diff: "-from customers\n+from analytics.customers\n", reviewers, runner: runner() }), reviewers) + }) }) describe("3: without a compiled base, a column the raw base provably lacks blocks", () => { @@ -185,6 +283,53 @@ describe("3: without a compiled base, a column the raw base provably lacks block } }) + test("a dynamic projection in the raw base (`COLUMNS(…)`, `* like`) leaves the column undecided", async () => { + const h = `select customer_id,\n email\nfrom ${ref}` + const bases = { + regex: `select customer_id, COLUMNS('^e')\nfrom ${ref}`, + lambda: `select customer_id, columns(c -> c like 'e%')\nfrom ${ref}`, + all: `select columns(*)\nfrom ${ref}`, + like: `select * like 'e%'\nfrom ${ref}`, + } + for (const [kind, b] of Object.entries(bases)) + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []]) { + const r = await run({ base: b, head: h, diff: "+ email\n", reviewers, runner: piiRunner(["email"], classifyAll(/email/)), compiled: compiledHead(h) }) + expect({ kind, reviewers, reported: r.pii.length > 0, critical: r.critical, unknown: r.pii.every((f) => f.confidence === "unknown") }).toEqual({ + kind, + reviewers, + reported: true, + critical: false, + unknown: true, + }) + } + }) + + test("a column proven new is reported once: the regex twins defer to the engine finding", async () => { + const b = `select customer_id\nfrom ${ref}` + for (const col of ["ssn", "email"]) + for (const classify of [classifyAll(new RegExp(col)), undefined]) { + const h = `select customer_id,\n ${col}\nfrom ${ref}` + for (const reviewers of [["pii_exposure", "dbt_patterns"], []]) { + const r = await run({ base: b, head: h, diff: `+ ${col}\n`, reviewers, runner: piiRunner([col], classify), compiled: compiledHead(h) }) + const label = { col, classified: !!classify, reviewers } + expectBlocks(r, label) + expect({ label, findings: r.pii.map((f) => `${f.severity}/${f.evidence?.tool}`) }).toEqual({ + label, + findings: [`critical/${classify ? "altimate_core.classify_pii" : "schema.detect_pii"}`], + }) + } + } + }) + + test("a regex twin for a column no engine lane reported is kept, and blocks when proven new", async () => { + // Only the pattern lanes run with a classifier that misses `ssn`. + const b = `select customer_id\nfrom ${ref}` + const h = `select customer_id,\n ssn\nfrom ${ref}` + const r = await run({ base: b, head: h, diff: "+ ssn\n", reviewers: ["dbt_patterns"], runner: piiRunner(["ssn"]), compiled: compiledHead(h) }) + expectBlocks(r, "twin") + expect(r.pii.some((f) => f.evidence?.tool === "dbt-patterns" && f.severity === "critical")).toBe(true) + }) + test("a renamed output (`email as contact`) is reported: the base never named `contact`", async () => { // The proof is about the output name the base would need to expose. The raw // base names only `email`, so it cannot have exposed `contact`; without a diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 8f5a1831cb..99965db66c 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -239,7 +239,7 @@ describe("finalOutputs().raw", () => { const prod = new Set(["analytics.dbt_prod.customers.ssn"]) // Different environments: the head reads under `analytics.dbt_ci_pr_42`, which the base never read. // `sameRelation`: the raw model code reads `customers` by the same relation text on both sides. - const sameRelation = new Set(["customers"]) + const sameRelation = (table: string) => table === "customers" const envs = { base: new Set(["analytics.dbt_prod"]), sameRelation } expect(refCovered("analytics.dbt_ci_pr_42.customers.ssn", prod, envs)).toBe(true) expect(refCovered("analytics.dbt_ci_pr_42.spouses.ssn", prod, envs)).toBe(false) From cb12a0b893f3180a6b59f463980eee9dad0ece31 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 2 Dec 2026 13:25:47 +0530 Subject: [PATCH 3/7] fix(review): an unmodelled query proves no relation unchanged, and a base with no select list is undecided A macro that emits the whole query lists no relation, so "nothing changed" was vacuous. `table x` and a DuckDB `from x` select every column. Docs and changelog say what quote style is ignored. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 4 ++-- docs/docs/usage/dbt-pr-review.md | 5 +++-- .../opencode/src/altimate/review/orchestrate.ts | 5 ++++- .../opencode/src/altimate/review/rule-catalog.ts | 6 ++++-- .../test/altimate/review-pii-new-exposure.test.ts | 15 ++++++++++++++- 5 files changed, 27 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16147345df..40edbd16f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,8 +14,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - **`altimate review` reads `.altimate/review.yml` from the base branch.** A PR can no longer relax the policy it is reviewed under; settings it changes are listed in the comment and take effect after merge. The `--mode` and `--severity` flags (the action's `mode` and `severity_threshold`) can only tighten a base policy, and `allowForceTier: false` rejects `--force-tier`. (#1722) -- **`altimate review` flags PII only for columns the change newly exposes**, not for PII columns the base already surfaced. Without a compiled base, a PII column is a non-blocking warning that may predate the PR. (#1721) -- **`altimate review` reports three PII exposures it used to call pre-existing.** Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, selects no `*` or `COLUMNS(…)`, and holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. A renamed PII output (`email as contact`) is then new. A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name, quote style and spacing aside), or, for a model compiled under a name its `ref` does not show (an alias or a version), when no relation in the model's code changed; a schema, `source` or `var` swapped in the code is reported. A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported. (#1875) +- **`altimate review` flags PII only for columns the change newly exposes**, not for PII columns the base already surfaced. Without a compiled base, a PII column is a non-blocking warning that may predate the PR, unless the base SQL cannot have exposed it (see the next entry). (#1721) +- **`altimate review` reports three PII exposures it used to call pre-existing.** Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, has a select list with no `*` or `COLUMNS(…)`, and holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. A renamed PII output (`email as contact`) is then new. A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name; the quote style and spacing inside a `ref` or `source` call do not count, a quoted SQL name is compared as written), or, for a model compiled under a name its `ref` does not show (an alias or a version), when no relation in the model's code changed; a schema, `source` or `var` swapped in the code is reported. A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported. (#1875) ## [0.12.12] - 2026-11-20 diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 9930180575..75c503d65a 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -345,7 +345,8 @@ rubric: columns the base already surfaced. A table read under another schema is the same table only when the model's own code reads it the same way on both sides, compiled into another environment: the same `ref` or `source` call or table - name (quote style and spacing aside). A model whose compiled table name is not + name (the quote style and spacing inside a `ref` or `source` call aside; a + quoted SQL name is compared as written). A model whose compiled table name is not the name in its `ref` (an `alias`, a version such as `ref('customers', v=2)`, a custom alias macro) counts as the same table only when no `ref`, `source` or table name in the model's code changed. A changed schema, `source`, `var` or @@ -358,7 +359,7 @@ rubric: the base file's own SQL cannot have exposed that output column name: then it is reported as new, as with a compiled base, and can block. The base cannot have exposed the name when it does not name it anywhere outside comments - (string literals count), selects no `*` and no dynamic column selector + (string literals count), has a select list with no `*` and no dynamic column selector (`COLUMNS(…)`), and holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags (a macro call, a variable or an `{% include %}` could emit any column). The proof is about the output name, so a renamed PII output diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index dcebdd8ecd..c5524eefc8 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1156,7 +1156,10 @@ function rawBaseCode(oldSql: string | undefined): string | undefined { if (!oldSql) return undefined if (!(oldSql.match(/\{\{[\s\S]*?\}\}/g) ?? []).every((e) => RAW_BASE_PLAIN_EXPR.test(e))) return undefined if (!(oldSql.match(/\{%[\s\S]*?%\}/g) ?? []).every((t) => SILENT_JINJA_TAG.test(t))) return undefined - if (selectItems(oldSql).some((i) => RAW_BASE_STAR.test(i.text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ")))) return undefined + const items = selectItems(oldSql) + // No select list at all (`table customers`, a DuckDB `from customers`) selects every column. + if (!items.length) return undefined + if (items.some((i) => RAW_BASE_STAR.test(i.text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ")))) return undefined // Comments out, literals and quoted identifiers kept (one pass, so `--` inside // `'…'` or `"…"` is not a comment). return oldSql.replace(/\{#[\s\S]*?#\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"/g, (m) => diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index fee62df0bb..6a4824600a 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -1057,7 +1057,7 @@ function relationOwnName(text: string): string { /** Per own name, the normalised relation texts `sql` reads tables by, and * whether every source was named (`complete`). */ function relationTexts(sql: string): { byName: Map>; all: Set; complete: boolean } { - const { items, sources, unknownSources } = parseSelects(sql) + const { items, sources, unknownSources, unmodelled, misread } = parseSelects(sql) const scopes = new Set(items.map((i) => i.scope)) const byName = new Map>() const all = new Set() @@ -1073,7 +1073,9 @@ function relationTexts(sql: string): { byName: Map>; all: Se if (texts) texts.add(text) else byName.set(own, new Set([text])) } - return { byName, all, complete: unknownSources.size === 0 } + // A query the parser does not model (a macro that emits the whole query, say) may read + // relations it never lists: the relation set then proves nothing. + return { byName, all, complete: unknownSources.size === 0 && !unmodelled && !misread } } /** Whether a compiled table own name may differ by prefix between base and head diff --git a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts index 495fba7cd7..4a08963abd 100644 --- a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts +++ b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts @@ -1,4 +1,5 @@ import { describe, test, expect } from "bun:test" +import { rawRelationsMatch } from "../../src/altimate/review/rule-catalog" import { runReview, DEFAULT_RUBRIC, DEFAULT_REVIEW_CONFIG, type ReviewRunner, type ChangedFile } from "../../src/altimate/review" // The PII check reports only columns a change NEWLY exposes, and is one-sided: @@ -137,7 +138,7 @@ describe("1: a UNION branch that computes PII under a name the first branch had" }) }) -describe("2:a schema-only source swap is a different table unless the raw code names it the same way", () => { +describe("2: a schema-only source swap is a different table unless the raw code names it the same way", () => { const runner = () => piiRunner(["ssn"]) test("a literal `masked.customers` → `raw.customers` swap is new exposure", async () => { @@ -220,6 +221,15 @@ describe("2:a schema-only source swap is a different table unless the raw code n for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) expectBlocks(await run({ ...c, reviewers, runner: runner() }), { label, reviewers }) }) + test("a macro that emits the whole query proves no relation unchanged", () => { + // The parser lists no relation for either side, so "nothing changed" would be vacuous. + expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('raw') }}")("customers")).toBe(false) + expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('masked') }}")("customers")).toBe(false) + // A fully read model whose calls are unchanged still explains an aliased name. + const same = "select id from {{ ref('customers', v=2) }}" + expect(rawRelationsMatch(same, same)("customers_v2")).toBe(true) + }) + test("a swapped Jinja prefix is a different table, whatever its length", async () => { const cases = { "same length": sides("{{ var('masked') }}.customers", "{{ var('raw_db') }}.customers", "analytics.pii_masked.customers", "analytics.pii_raw.customers", "-x\n+y\n"), @@ -287,6 +297,9 @@ describe("3: without a compiled base, a column the raw base provably lacks block const h = `select customer_id,\n email\nfrom ${ref}` const bases = { regex: `select customer_id, COLUMNS('^e')\nfrom ${ref}`, + // No select list: every column is selected. + table: `table ${ref}`, + fromFirst: `from ${ref}`, lambda: `select customer_id, columns(c -> c like 'e%')\nfrom ${ref}`, all: `select columns(*)\nfrom ${ref}`, like: `select * like 'e%'\nfrom ${ref}`, From e68ff2d7485ad7cf94793f2411f6d246cbe0dc65 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 2 Dec 2026 14:27:28 +0530 Subject: [PATCH 4/7] fix(review): review round: no block from an unrelated CTE or an implicit base projection, and "cannot tell" is a warning Lineage follows each read to its own source. Absence is proven only from an explicit root projection. A schema difference the model's code does not explain is undecided, not a swap. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- docs/docs/usage/dbt-pr-review.md | 24 ++- .../src/altimate/review/orchestrate.ts | 110 ++++++++---- .../src/altimate/review/rule-catalog.ts | 167 +++++++++++++----- .../altimate/review-pii-new-exposure.test.ts | 140 ++++++++++++++- 5 files changed, 349 insertions(+), 94 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40edbd16f5..16b9dd8bb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`altimate review` reads `.altimate/review.yml` from the base branch.** A PR can no longer relax the policy it is reviewed under; settings it changes are listed in the comment and take effect after merge. The `--mode` and `--severity` flags (the action's `mode` and `severity_threshold`) can only tighten a base policy, and `allowForceTier: false` rejects `--force-tier`. (#1722) - **`altimate review` flags PII only for columns the change newly exposes**, not for PII columns the base already surfaced. Without a compiled base, a PII column is a non-blocking warning that may predate the PR, unless the base SQL cannot have exposed it (see the next entry). (#1721) -- **`altimate review` reports three PII exposures it used to call pre-existing.** Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, has a select list with no `*` or `COLUMNS(…)`, and holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. A renamed PII output (`email as contact`) is then new. A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name; the quote style and spacing inside a `ref` or `source` call do not count, a quoted SQL name is compared as written), or, for a model compiled under a name its `ref` does not show (an alias or a version), when no relation in the model's code changed; a schema, `source` or `var` swapped in the code is reported. A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported. (#1875) +- **`altimate review` reports three PII exposures it used to call pre-existing.** Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, its final query names every column in its own select list (no `*`, `COLUMNS(…)`, whole-row reference or struct expansion), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. A renamed PII output (`email as contact`) is then new. A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name; the quote style and spacing inside a `ref` or `source` call do not count, a quoted SQL name is compared as written), or, for a model compiled under a name its `ref` does not show (an alias, a version or a source `identifier:`), when no relation in the model's code changed; a schema, `source` or `var` swapped in the model's code is reported. Where the code cannot decide, and for a source while the PR edits a `schema:`, `database:` or `identifier:` line in YAML, the column is a non-blocking warning that may predate the PR; a schema swap made only in YAML outside the PR is not detected. A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported, also after a first branch that selects `*`. (#1875) ## [0.12.12] - 2026-11-20 diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 75c503d65a..b608810f24 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -348,19 +348,27 @@ rubric: name (the quote style and spacing inside a `ref` or `source` call aside; a quoted SQL name is compared as written). A model whose compiled table name is not the name in its `ref` (an `alias`, a version such as `ref('customers', v=2)`, - a custom alias macro) counts as the same table only when no `ref`, `source` or - table name in the model's code changed. A changed schema, `source`, `var` or - package argument in the code is a different table, and so, under another - schema, is a quoted name whose case changed. A source whose schema changes - only in `sources.yml` or in a var, with the model's code unchanged, is not - detected as a swap. That + a custom alias macro, a source `identifier:`) counts as the same table only + when no `ref`, `source` or table name in the model's code changed. A changed + schema, `source`, `var` or package argument in the code is a different table, + and so, under another schema, is a quoted name whose case changed. When the + code cannot decide (such a model only gained a relation, or its SQL is a + shape the review does not parse and no Jinja expression in it changed), the + column is reported as a non-blocking warning that may predate the PR. A + source whose schema changes only in YAML is flagged the same way when the PR + edits a `schema:`, `database:` or `identifier:` line in a YAML file; + otherwise (a schema set by a var, or changed outside the PR) it is not + detected. That comparison needs the base version's SQL; when it can't be compiled, a PII column is reported as a non-blocking warning that may predate the PR, unless the base file's own SQL cannot have exposed that output column name: then it is reported as new, as with a compiled base, and can block. The base cannot have exposed the name when it does not name it anywhere outside comments - (string literals count), has a select list with no `*` and no dynamic column selector - (`COLUMNS(…)`), and holds no Jinja but `ref`, `source`, `config`, `this` and + (string literals count), its final query has its own select list naming each + column (no `*`, no dynamic column selector such as `COLUMNS(…)`, no source + selected as a whole row such as `select c` or `to_json(c)`, no struct or array + expansion such as `unnest(payload)`; a final `table c` or `from c` selects + every column), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags (a macro call, a variable or an `{% include %}` could emit any column). The proof is about the output name, so a renamed PII output (`email as contact`) is reported as new. The pattern check also blocks diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index c5524eefc8..841235a674 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -22,7 +22,9 @@ import { type SelectItemColumn, finalOutputs, rawReach, + explicitProjection, rawRelationsMatch, + type RelationMatch, refCovered, ROOT_SCOPE, SILENT_JINJA_TAG, @@ -1084,32 +1086,39 @@ function piiLane( undecided: (column: string) => boolean = () => false, ): Finding[] { if (file.status === "deleted" || !columns.length) return [] - const proven = columns.filter((c) => !undecided(c)) - const open = columns.filter((c) => undecided(c)) + const provenColumns = columns.filter((c) => !undecided(c)) + const undecidedColumns = columns.filter((c) => undecided(c)) return [ - ...piiLaneFinding(file, proven, false, "pii:exposure"), - // Its own key when beside a proven finding, so dedup keeps both. - ...piiLaneFinding(file, open, true, proven.length ? "pii:exposure:undecided" : "pii:exposure"), + ...piiLaneFinding(file, provenColumns, false, "pii:exposure"), + // Its own key when beside a proven finding: findings with one fingerprint + // are merged into one. The finding has no line, so it is never an inline + // comment and no later run matches it by fingerprint. + ...piiLaneFinding(file, undecidedColumns, true, provenColumns.length ? "pii:exposure:undecided" : "pii:exposure"), ] } -function piiLaneFinding(file: ChangedFile & { kind: string }, columns: string[], baseUnknown: boolean, ruleKey: string): Finding[] { +function piiLaneFinding( + file: ChangedFile & { kind: string }, + columns: string[], + undecided: boolean, + ruleKey: string, +): Finding[] { if (!columns.length) return [] const model = modelNameFromPath(file.path) return [ makeFinding({ - severity: baseUnknown ? "warning" : "critical", + severity: undecided ? "warning" : "critical", category: "pii_exposure", title: `${model}: exposes PII column${columns.length !== 1 ? "s" : ""} (${columns.join(", ")})`, body: `This model surfaces PII-classified column(s): ${columns.map((c) => `\`${c}\``).join(", ")}.` + ` Confirm masking/access policy before merging to a non-restricted schema.` + - (baseUnknown - ? " The base version could not be compiled, so these columns may already be exposed before this PR." + (undecided + ? " These columns may already be exposed before this PR: the base version could not be compiled, or it read a table under another schema that the model's code does not explain." : ""), file: file.path, model, // `unknown`: undecided exposure never counts toward the warning pattern. - confidence: baseUnknown ? "unknown" : "high", + confidence: undecided ? "unknown" : "high", evidence: { tool: "schema.detect_pii", result: { columns } }, ruleKey, }), @@ -1156,14 +1165,17 @@ function rawBaseCode(oldSql: string | undefined): string | undefined { if (!oldSql) return undefined if (!(oldSql.match(/\{\{[\s\S]*?\}\}/g) ?? []).every((e) => RAW_BASE_PLAIN_EXPR.test(e))) return undefined if (!(oldSql.match(/\{%[\s\S]*?%\}/g) ?? []).every((t) => SILENT_JINJA_TAG.test(t))) return undefined - const items = selectItems(oldSql) - // No select list at all (`table customers`, a DuckDB `from customers`) selects every column. - if (!items.length) return undefined - if (items.some((i) => RAW_BASE_STAR.test(i.text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ")))) return undefined + // Only the final query's own select lists can prove a column absent: a CTE's + // list does not (`with u as (select id from c) table c`), nor a final query + // without one, nor a whole row or a struct expansion (`select c`, `unnest(s)`). + if (!explicitProjection(oldSql)) return undefined + if (selectItems(oldSql).some((i) => RAW_BASE_STAR.test(i.text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ")))) + return undefined // Comments out, literals and quoted identifiers kept (one pass, so `--` inside - // `'…'` or `"…"` is not a comment). - return oldSql.replace(/\{#[\s\S]*?#\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"/g, (m) => - m.startsWith("'") || m.startsWith('"') ? m : " ", + // `'…'`, `"…"`, `` `…` `` or `$$…$$` is not a comment). + return oldSql.replace( + /\{#[\s\S]*?#\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"|`(?:[^`]|``)*`|\$([A-Za-z_]\w*)?\$[\s\S]*?\$\1\$/g, + (m) => (/^['"`$]/.test(m) ? m : " "), ) } function rawBaseLacks(code: string | undefined, names: string[]): boolean { @@ -1309,21 +1321,32 @@ export async function runReview(input: OrchestrateInput): Promise() - const envOf = (file: string): RelationPrefixes => { - let env = envByFile.get(file) - if (!env) { + // A YAML edit to a `schema:`/`database:`/`identifier:` line may move a + // `source()` whose text in the model is unchanged. + const sourcesEdited = input.changedFiles.some( + (f) => + /\.ya?ml$/i.test(f.path) && /^[+-](?![+-])\s*(?:-\s*)?(?:schema|database|identifier)\s*:/m.test(f.diff ?? ""), + ) + // Parsed only when a prefix difference needs it: it re-parses both raw sides. + const relationMatchByFile = new Map RelationMatch>() + const relationMatch = (file: string, table: string) => { + let matchesRaw = relationMatchByFile.get(file) + if (!matchesRaw) { const ctx = ctxByPath.get(file) - // Parsed only when a prefix difference needs it: it re-parses both raw sides. - let same: ((table: string) => boolean) | undefined - env = { - base: outputs(file, "old").prefixes, - sameRelation: (table) => (same ??= rawRelationsMatch(ctx?.oldSql, ctx?.newSql))(table), - } - envByFile.set(file, env) + relationMatchByFile.set(file, (matchesRaw = rawRelationsMatch(ctx?.oldSql, ctx?.newSql, sourcesEdited))) } - return env + return matchesRaw(table) } + // `unknownAs`: whether a prefix difference the raw code cannot decide counts + // as the same table; `seen.unknown` records that one was asked. + const envOf = (file: string, unknownAs = false, seen?: { unknown: boolean }): RelationPrefixes => ({ + base: outputs(file, "old").prefixes, + sameRelation: (table) => { + const match = relationMatch(file, table) + if (match === "unknown" && seen) seen.unknown = true + return match === "same" || (match === "unknown" && unknownAs) + }, + }) // `source.column` refs the base exposed raw under a name its PII detection // reported: named in its final select, or passed through its plain `*` // (`select * from customers` exposes `customers.ssn` when `ssn` is base PII). @@ -1360,6 +1383,7 @@ export async function runReview(input: OrchestrateInput): Promise { const refs = [...(head.get(name) ?? [])].filter((r) => r.endsWith(`.${column}`)) + // An undecided prefix difference is not the same table: it never drops a twin. return refs.length > 0 && refs.every((r) => refCovered(r, exposed, envOf(file))) }) } @@ -1375,12 +1399,12 @@ export async function runReview(input: OrchestrateInput): Promise) => { + const isBaseExposedOutput = (file: string, name: string, basePii: Set, env: RelationPrefixes) => { const head = outputs(file, "new") const rawColumns = head.raw.get(name) if (rawColumns?.size) { const exposed = baseRawPii(file) - const covered = (ref: string) => refCovered(ref, exposed, envOf(file)) + const covered = (ref: string) => refCovered(ref, exposed, env) if (![...rawColumns].every(covered)) return false // A later UNION branch may compute the name from other columns (base raw // `email` → head adds `lower(ssn) as email`): the raw match alone is not @@ -1394,7 +1418,7 @@ export async function runReview(input: OrchestrateInput): Promise() const baseLineage = base.lineage.get(name) if ( - reads.every((ref) => covered(ref) || refCovered(ref, baseReads, envOf(file))) && + reads.every((ref) => covered(ref) || refCovered(ref, baseReads, env)) && !!baseLineage && [...(head.lineage.get(name) ?? [])].every((sig) => baseLineage.has(sig)) ) @@ -1405,7 +1429,7 @@ export async function runReview(input: OrchestrateInput): Promise refCovered(ref, exposed, envOf(file)))) return true + if (reads && [...reads].every((ref) => refCovered(ref, exposed, env))) return true // The same computation counts only over the same source columns: the // signature holds the item text and derived-query bodies, not the tables // (`lower(email)` from `customers` → from `spouses` is new). Refs no @@ -1413,7 +1437,7 @@ export async function runReview(input: OrchestrateInput): Promise() const sameReads = [...(reads ?? [])] .filter((ref) => !ref.startsWith("?")) - .every((ref) => refCovered(ref, baseReads, envOf(file))) + .every((ref) => refCovered(ref, baseReads, env)) const baseSigs = base.signatures.get(name) return sameReads && !!baseSigs && [...(head.signatures.get(name) ?? [])].every((sig) => baseSigs.has(sig)) } @@ -1424,7 +1448,14 @@ export async function runReview(input: OrchestrateInput): Promise 0 && [...starRefs].every((ref) => refCovered(ref, exposed, envOf(file))) + return starRefs.size > 0 && [...starRefs].every((ref) => refCovered(ref, exposed, env)) + } + // Exposed whatever the undecided prefix differences are; `undecided` when only + // reading them as environment changes makes it exposed; else `new`. + const baseExposure = (file: string, name: string, basePii: Set) => { + const seen = { unknown: false } + if (isBaseExposedOutput(file, name, basePii, envOf(file, false, seen))) return "exposed" + return seen.unknown && isBaseExposedOutput(file, name, basePii, envOf(file, true)) ? "undecided" : "new" } // The raw base as `rawBaseLacks` reads it, parsed once per file and only when // a PII lane needs it (the engine lanes and the regex twins share it). @@ -1500,9 +1531,10 @@ export async function runReview(input: OrchestrateInput): Promise !diffScopedPii.classifiedColumns.has(col.toLowerCase())) : currentCtx.pii // The fallback reports only columns the base did not already expose. - fallbackPii = fallbackPii.filter( - (col) => !isBaseExposedOutput(currentCtx.file.path, col.toLowerCase(), basePii), + const exposure = new Map( + fallbackPii.map((col) => [col, baseExposure(currentCtx.file.path, col.toLowerCase(), basePii)]), ) + fallbackPii = fallbackPii.filter((col) => exposure.get(col) !== "exposed") // Without a compiled base a column is undecided unless the raw base // provably lacks that output name. const baseUnknown = hasOldSide(currentCtx.file) && !currentCtx.engineOldSql @@ -1510,7 +1542,9 @@ export async function runReview(input: OrchestrateInput): Promise baseUnknown && !rawBaseLacks(baseCode(currentCtx.file.path), [col.toLowerCase()]), + (col) => + exposure.get(col) === "undecided" || + (baseUnknown && !rawBaseLacks(baseCode(currentCtx.file.path), [col.toLowerCase()])), ), ) } diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 6a4824600a..78fad5fdf6 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -1008,12 +1008,17 @@ function splitTable(table: string): { prefix: string; name: string } { * asks only whether the base already read tables under the head's prefix. */ export interface RelationPrefixes { base: Set - /** The compiled table own name may differ by prefix as an environment change: - * the RAW (uncompiled) model code reads it the same way on both sides - * (`rawRelationsMatch`). */ + /** The compiled table's own name may differ by prefix as an environment + * change: the RAW (uncompiled) model code reads it the same way on both + * sides (`rawRelationsMatch`). Without it, a prefix difference is always a + * different table. */ sameRelation?: (table: string) => boolean } +/** Whether a prefix difference is an environment change (`same`), a change in + * the model's code (`different`), or cannot be told from the raw code. */ +export type RelationMatch = "same" | "different" | "unknown" + /** A relation as the raw code writes it, for comparing two sides: a Jinja call * without white space, its strings in one quote style (`{{ ref("a") }}` = * `{{ref('a')}}`), a quoted identifier as spelled (`"Customers"` is not @@ -1026,7 +1031,8 @@ function normalizeRelation(text: string): string { const flat = call.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|\s+/g, (t) => t.startsWith("'") || t.startsWith('"') ? `'${t.slice(1, -1)}'` : "", ) - return `{{${flat}}}` + // `version=2` is spelled `v=2` too. + return `{{${flat.replace(/'[^']*'|(? (t.startsWith("'") ? t : "v="))}}}` }) } @@ -1078,24 +1084,44 @@ function relationTexts(sql: string): { byName: Map>; all: Se return { byName, all, complete: unknownSources.size === 0 && !unmodelled && !misread } } -/** Whether a compiled table own name may differ by prefix between base and head - * as an environment change, judged from the raw model code. A name the raw code - * reads (`ref('customers')`, `analytics.customers`) must be read by the same - * relation texts on both sides. A name it never writes (a model with an - * `alias`, a version, a custom alias macro: `ref('customers', v=2)` compiles - * to `customers_v2`) cannot be tied to one call, so every relation text must - * be unchanged and every source named. A missing side proves nothing. */ -export function rawRelationsMatch(oldSql: string | undefined, newSql: string | undefined): (table: string) => boolean { - if (!oldSql || !newSql) return () => false +/** Whether a compiled table's own name may differ by prefix between base and + * head as an environment change, judged from the raw model code. A name the + * raw code reads (`ref('customers')`, `analytics.customers`) is `same` when the + * same relation texts read it on both sides, else `different`. A name it never + * writes (a model with an `alias`, a version, a source `identifier:`: + * `ref('customers', v=2)` compiles to `customers_v2`) cannot be tied to one + * call: `same` when every source is named and none changed; `different` when a + * relation the base read is gone, or when the parse is incomplete and the + * model's Jinja expressions changed (a macro that emits the whole query, its + * arguments changed); otherwise (relations only added, or an incomplete parse + * with no change seen) `unknown`. A `source()` read while the pull request + * edits a `schema:`/`database:`/`identifier:` line in YAML (`sourcesEdited`) is + * at best `unknown`: the swap may be there. A missing side proves nothing. */ +export function rawRelationsMatch( + oldSql: string | undefined, + newSql: string | undefined, + sourcesEdited = false, +): (table: string) => RelationMatch { + if (!oldSql || !newSql) return () => "different" const base = relationTexts(oldSql) const head = relationTexts(newSql) const sameSet = (a: Set | undefined, b: Set | undefined) => !!a && !!b && a.size === b.size && [...a].every((t) => b.has(t)) - const unchanged = base.complete && head.complete && sameSet(base.all, head.all) + const unchanged = (texts: Set): RelationMatch => + sourcesEdited && [...texts].some((t) => t.startsWith("{{source(")) ? "unknown" : "same" + const complete = base.complete && head.complete + const jinja = (sql: string) => new Set((sql.match(/\{\{[\s\S]*?\}\}/g) ?? []).map(normalizeRelation)) + const untied: RelationMatch = + [...base.all].some((t) => !head.all.has(t)) || (!complete && !sameSet(jinja(oldSql), jinja(newSql))) + ? "different" + : complete && sameSet(base.all, head.all) + ? unchanged(base.all) + : "unknown" return (table) => { const a = base.byName.get(table) const b = head.byName.get(table) - return a || b ? sameSet(a, b) : unchanged + if (!a && !b) return untied + return sameSet(a, b) ? unchanged(a!) : "different" } } @@ -1188,6 +1214,11 @@ export function finalOutputs(sql: string): FinalOutputs { } const isDerived = (src: Source, scope: string, seen: Set) => src.name !== scope && byScope.has(src.name) && !seen.has(src.name) + // The source a qualifier names: by alias, else by the table's last segment. + const sourceNamed = (srcs: Source[], qualifier: string) => { + const named = (x: Source) => x.name === qualifier || x.short === qualifier + return srcs.find((x) => x.alias === qualifier) ?? srcs.find((x) => !x.alias && named(x)) ?? srcs.find(named) + } // The `source.column` refs a column read in `scope#branch` resolves to: those // it exposes raw (`raw`; a column a CTE computes is none), and every one its // value is computed from (`reads`). @@ -1221,10 +1252,7 @@ export function finalOutputs(sql: string): FinalOutputs { return same(unresolved(col)) } if (qualifier) { - // A qualifier names its source by alias, else by the table's last segment. - const named = (x: Source) => x.name === qualifier || x.short === qualifier - const src = - srcs.find((x) => x.alias === qualifier) ?? srcs.find((x) => !x.alias && named(x)) ?? srcs.find(named) + const src = sourceNamed(srcs, qualifier) return src ? fromSource(src) : same(unresolved(col)) } // A column merged by `using (…)` / `natural join` takes values from every @@ -1283,6 +1311,7 @@ export function finalOutputs(sql: string): FinalOutputs { } const scopeItems = byScope.get(scope) ?? [] const firstNames = new Map(scopeItems.filter((i) => i.branch === 0).map((i) => [i.position, i.name])) + const firstStar = scopeItems.find((i) => i.branch === 0 && STAR.test(i.text))?.position const readBodies = new Set() for (const item of scopeItems) { const derived = (sources.get(`${scope}#${item.branch}`) ?? []).filter((src) => isDerived(src, scope, seen)) @@ -1304,33 +1333,57 @@ export function finalOutputs(sql: string): FinalOutputs { continue } const name = item.branch === 0 ? item.name : firstNames.get(item.position) - if (!name) continue - names.add(name) + // A later branch's item at or after a `*` of the first branch has no known + // name: its reads count toward every name the scope outputs, so the `*` + // does not hide a computed read (`select * from c union all select + // lower(email) as email from secrets`). Never a raw exposure. + const targets = name + ? [name] + : item.branch > 0 && firstStar !== undefined && item.position >= firstStar + ? [...names] + : [] + if (!targets.length) continue + if (name) names.add(name) const text = signatureText(item, scope) - addTo(signatures, name, [`${text}\u0001${bodies.join("\u0002")}`]) - const columns = item.rawColumn ? [item.rawColumn] : (item.reads ?? []).map((r) => r.column) - const upstream = derived - .map((src) => { - const out = resolve(src.name, inner) - const of = (c: string) => - out.names.has(c) ? [...(out.lineage.get(c) ?? [])].sort().join("\u0005") : out.stars.length ? out.body : "" - return `${src.name}:${columns.map(of).join("\u0006")}` + // Each read follows only the CTE or subquery it comes from: a qualifier + // names one source; an unqualified read may come from any that has it. + const srcs = sources.get(`${scope}#${item.branch}`) ?? [] + const itemReads = item.rawColumn ? [{ qualifier: item.rawQualifier, column: item.rawColumn }] : (item.reads ?? []) + const upstream = itemReads + .flatMap(({ qualifier, column }) => { + const named = qualifier ? sourceNamed(srcs, qualifier) : undefined + const from = named ? [named].filter((src) => derived.includes(src)) : derived + return from + .map((src) => ({ src, out: resolve(src.name, inner) })) + .filter(({ out }) => named || out.names.has(column) || out.stars.length) + .map(({ src, out }) => { + const of = out.names.has(column) + ? [...(out.lineage.get(column) ?? [])].sort().join("\u0005") + : out.stars.length + ? out.body + : "" + return `${src.name}.${column}:${of}` + }) }) .sort() // A digest, so a column computed from several upstream columns at every // level of a CTE chain does not grow its key exponentially. - addTo(lineage, name, [createHash("sha1").update(`${text}\u0001${upstream.join("\u0002")}`).digest("base64")]) - if (item.rawColumn) { - const refs = resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen) - addTo(raw, name, refs.raw) - addTo(reads, name, refs.reads) - } else { - reads.set(name, reads.get(name) ?? new Set()) - for (const r of item.reads ?? []) addTo(reads, name, resolveRef(scope, item.branch, r.qualifier, r.column, seen).reads) - // An expression whose column reads parse to nothing is not known to read - // nothing: it is never "already exposed" by its reads (the signature may - // still match). Only a constant reads nothing. - if (!item.reads?.length && !item.constant) addTo(reads, name, unresolved(name)) + const digest = createHash("sha1").update(`${text}\u0001${upstream.join("\u0002")}`).digest("base64") + const refs = item.rawColumn + ? resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen) + : { + raw: new Set(), + reads: union((item.reads ?? []).map((r) => resolveRef(scope, item.branch, r.qualifier, r.column, seen).reads)), + } + // An expression whose column reads parse to nothing is not known to read + // nothing: it is never "already exposed" by its reads (the signature may + // still match). Only a constant reads nothing. + if (!item.rawColumn && !item.reads?.length && !item.constant) refs.reads = unresolved(name ?? "") + for (const target of targets) { + addTo(signatures, target, [`${text}\u0001${bodies.join("\u0002")}`]) + addTo(lineage, target, [digest]) + if (name) addTo(raw, target, refs.raw) + addTo(reads, target, refs.reads) } } for (const [n, cols] of raw) if (!cols.size) raw.delete(n) @@ -1467,6 +1520,38 @@ function namesRow(expr: string, name: string): boolean { ) } +/** Calls that output columns the SQL never names: a struct or array expanded + * (`unnest(payload)`, `untuple(t)`, `inline(arr)`), a name or position + * resolved at run time (`identifier($col)`, `$2`). */ +const UNNAMED_COLUMNS = /(? i.scope === ROOT_SCOPE) + return ( + root.length > 0 && + root.every((item) => { + if (jinjaItems.has(item) || UNNAMED_COLUMNS.test(item.text)) return false + // A source's alias, name, and for an unaliased `ref`/`source` its model. + const rows = (sources.get(`${ROOT_SCOPE}#${item.branch}`) ?? []).flatMap((src) => { + const model = !src.alias && /["']([^"']+)["'][^"']*$/.exec(src.short ?? src.name)?.[1] + return [src.alias, src.name, src.short, model || undefined].filter((x): x is string => !!x) + }) + const { expr } = splitAlias(item.text) + return !rows.some((row) => namesRow(expr, row)) + }) + ) +} + /** What a `*` select item passes on: which source it spans and under which * names it carries a column (`* exclude (a)`, `* except (a)`, `* replace (f(a) * as a)`, `* rename (a as b)`, in any combination). `undefined` for an item diff --git a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts index 4a08963abd..fd300b5a5c 100644 --- a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts +++ b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts @@ -51,14 +51,16 @@ const run = async (o: { reviewers: string[] runner: ReviewRunner compiled?: (side: "old" | "new") => string | undefined + /** Other files the pull request changes (a `sources.yml`, say). */ + others?: ChangedFile[] }) => { const env = await runReview({ - changedFiles: [{ path: P, status: "modified", diff: o.diff } as ChangedFile], + changedFiles: [{ path: P, status: "modified", diff: o.diff } as ChangedFile, ...(o.others ?? [])], config: { ...DEFAULT_REVIEW_CONFIG, reviewers: o.reviewers }, rubric: DEFAULT_RUBRIC, mode: "gate", runner: o.runner, - getContent: async (_f: string, side: "old" | "new") => (side === "new" ? o.head : o.base), + getContent: async (f: string, side: "old" | "new") => (f !== P ? "" : side === "new" ? o.head : o.base), getCompiled: o.compiled ? async (_f: string, side: "old" | "new") => o.compiled!(side) : undefined, }) const pii = env.findings.filter((f) => f.category === "pii_exposure") @@ -222,12 +224,13 @@ describe("2: a schema-only source swap is a different table unless the raw code }) test("a macro that emits the whole query proves no relation unchanged", () => { - // The parser lists no relation for either side, so "nothing changed" would be vacuous. - expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('raw') }}")("customers")).toBe(false) - expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('masked') }}")("customers")).toBe(false) + // The parser lists no relation for either side, so "nothing changed" would be + // vacuous: changed arguments are a change, unchanged ones leave it unknown. + expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('raw') }}")("customers")).toBe("different") + expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('masked') }}")("customers")).toBe("unknown") // A fully read model whose calls are unchanged still explains an aliased name. const same = "select id from {{ ref('customers', v=2) }}" - expect(rawRelationsMatch(same, same)("customers_v2")).toBe(true) + expect(rawRelationsMatch(same, same)("customers_v2")).toBe("same") }) test("a swapped Jinja prefix is a different table, whatever its length", async () => { @@ -357,3 +360,128 @@ describe("3: without a compiled base, a column the raw base provably lacks block ) }) }) + +// Undecided: reported as a warning of unknown confidence, which never blocks. +const expectUndecided = (r: Awaited>, label: unknown) => + expect({ + label, + reported: r.pii.length > 0, + critical: r.critical, + blocks: r.verdict === "REQUEST_CHANGES", + unknown: r.pii.every((f) => f.confidence === "unknown"), + }).toEqual({ label, reported: true, critical: false, blocks: false, unknown: true }) + +describe("review round: lineage follows each read to its own source", () => { + test("editing a joined CTE the branch does not read keeps an already-exposed name quiet", async () => { + // `s` and `d` both expose `email`; the branch reads `s.email` only. + const sql = (d: string) => + `with s as (select email from secrets),\n d as (select ${d} as email from other)\nselect email from customers\nunion all\nselect lower(s.email) as email from s cross join d` + for (const reviewers of REVIEWER_SETS) + expectQuiet( + await run({ base: sql("md5(email)"), head: sql("email"), diff: "- d as (select md5(email) as email from other)\n+ d as (select email as email from other)\n", reviewers, runner: piiRunner(["email"]) }), + reviewers, + ) + }) + + test("unmasking the CTE a qualified read names is still new exposure", async () => { + const sql = (s: string) => + `with s as (select ${s} as email from secrets),\n d as (select email from other)\nselect email from customers\nunion all\nselect lower(s.email) as email from s cross join d` + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks( + await run({ base: sql("md5(email)"), head: sql("email"), diff: "-with s as (select md5(email) as email from secrets),\n+with s as (select email as email from secrets),\n", reviewers, runner: piiRunner(["email"]) }), + reviewers, + ) + }) +}) + +describe("review round: only the final query's explicit projection proves a column absent", () => { + const ref = "{{ ref('stg_customers') }}" + const h = `select customer_id,\n email\nfrom ${ref}` + const compiledHead = (side: "old" | "new") => (side === "new" ? h.replace(ref, "analytics.stg_customers") : undefined) + + test("a base whose final query selects every column, or a whole row or struct, leaves the column undecided", async () => { + const bases = { + "CTE then table": `with unused as (select customer_id from ${ref})\ntable ${ref}`, + "CTE then FROM-only": `with unused as (select customer_id from ${ref})\nfrom ${ref}`, + unnest: `select unnest(payload)\nfrom ${ref}`, + "whole row": `select c\nfrom ${ref} c`, + "row as JSON": `select to_json(t) as payload\nfrom ${ref} t`, + } + for (const [kind, b] of Object.entries(bases)) + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []]) + expectUndecided( + await run({ base: b, head: h, diff: "+ email\n", reviewers, runner: piiRunner(["email"], classifyAll(/email/)), compiled: compiledHead }), + { kind, reviewers }, + ) + }) + + test("a quoted identifier or dollar-quoted string holding `--` does not hide a mention", async () => { + const bases = { + backtick: `select customer_id, \`a--b\`.email\nfrom ${ref} as \`a--b\``, + dollar: `select customer_id, $q$--$q$ || email as note\nfrom ${ref}`, + } + for (const [kind, b] of Object.entries(bases)) + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []]) + expectUndecided( + await run({ base: b, head: h, diff: "+ email\n", reviewers, runner: piiRunner(["email"], classifyAll(/email/)), compiled: compiledHead }), + { kind, reviewers }, + ) + }) +}) + +describe("review round: a prefix difference the raw code cannot explain is undecided", () => { + const runner = () => piiRunner(["ssn"]) + const compiledFrom = (b: string, h: string, fromBase: string, fromHead: string) => (side: "old" | "new") => + side === "old" ? b.replace(/\{\{ source\('crm', 'cust'\) \}\}|\{\{ ref\('customers'\) \}\}/, fromBase) : h.replace(/\{\{ source\('crm', 'cust'\) \}\}|\{\{ ref\('customers'\) \}\}/, fromHead).replace("{{ ref('regions') }}", "analytics.dbt_ci.regions") + + test("a source with `identifier:` plus an added join, across environments", async () => { + // `cust` compiles to `customers` (`identifier:`), so the compiled name is tied to no call. + const b = "select c.customer_id,\n c.ssn\nfrom {{ source('crm', 'cust') }} c" + const h = "select c.customer_id, r.region,\n c.ssn\nfrom {{ source('crm', 'cust') }} c\njoin {{ ref('regions') }} r on r.id = c.region_id" + const compiled = compiledFrom(b, h, "analytics.dbt_prod.customers", "analytics.dbt_ci.customers") + for (const reviewers of REVIEWER_SETS) + expectUndecided(await run({ base: b, head: h, diff: "+join {{ ref('regions') }} r on r.id = c.region_id\n", reviewers, runner: runner(), compiled }), reviewers) + }) + + test("an unmodelled raw parse with no relation change, across environments", async () => { + // Two Jinja alternatives of one body: the parser does not model the raw query. + const alt = (cols: string) => + `{% if var('full', false) %}\nselect ${cols}\nfrom {{ ref('customers') }}\n{% else %}\nselect ${cols}\nfrom {{ ref('customers') }}\nwhere active\n{% endif %}` + const b = alt("customer_id,\n ssn") + const h = alt("customer_id, region,\n ssn") + const compiled = (side: "old" | "new") => + side === "old" ? "select customer_id,\n ssn\nfrom analytics.dbt_prod.customers_v2" : "select customer_id, region,\n ssn\nfrom analytics.dbt_ci.customers_v2" + for (const reviewers of REVIEWER_SETS) + expectUndecided(await run({ base: b, head: h, diff: "-select customer_id,\n+select customer_id, region,\n", reviewers, runner: runner(), compiled }), reviewers) + }) + + test("`version=` and `v=` name the same model version", () => { + expect(rawRelationsMatch("select id from {{ ref('customers', version=2) }}", "select id from {{ ref('customers', v=2) }}")("customers_v2")).toBe("same") + }) + + test("a schema swap made in `sources.yml` is undecided when the pull request edits it", async () => { + const b = "select customer_id,\n ssn\nfrom {{ source('crm', 'customers') }}" + const h = b.replace("select customer_id,", "select customer_id, region,") + const compiled = (side: "old" | "new") => + (side === "old" ? b : h).replace("{{ source('crm', 'customers') }}", `analytics.${side === "old" ? "masked" : "raw"}.customers`) + const yml = (diff: string) => [{ path: "models/staging/sources.yml", status: "modified", diff } as ChangedFile] + const diff = "-select customer_id,\n+select customer_id, region,\n" + for (const reviewers of REVIEWER_SETS) { + expectUndecided( + await run({ base: b, head: h, diff, reviewers, runner: runner(), compiled, others: yml("@@ -3,1 +3,1 @@\n- schema: masked\n+ schema: raw\n") }), + reviewers, + ) + // A `sources.yml` edit that moves no relation leaves the environment difference quiet. + expectQuiet(await run({ base: b, head: h, diff, reviewers, runner: runner(), compiled, others: yml("@@ -5,1 +5,1 @@\n- description: old\n+ description: new\n") }), reviewers) + } + }) +}) + +describe("review round: a `*` first branch does not hide a later branch's computed read", () => { + test("`lower(email)` from another table in a branch after `select * from c` is new exposure", async () => { + const b = "with c as (select email from customers)\nselect * from c" + const h = `${b}\nunion all\nselect lower(email) as email from secrets` + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks(await run({ base: b, head: h, diff: "+union all\n+select lower(email) as email from secrets\n", reviewers, runner: piiRunner(["email"]) }), reviewers) + }) +}) From 7f1724d4123e7d8623f1fdf63689e08778606657 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 2 Dec 2026 16:03:33 +0530 Subject: [PATCH 5/7] fix(review): agreed rules: UNION positions through a known `*`, replacement-only swaps, a stricter YAML check A later UNION branch maps through a CTE `*` with known columns. A relation counts as swapped only when one was removed and another added. A harmless-edit test guards against blocks from edits that expose nothing. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- docs/docs/usage/dbt-pr-review.md | 48 ++-- .../src/altimate/review/orchestrate.ts | 95 ++++++-- .../src/altimate/review/rule-catalog.ts | 209 ++++++++++++------ .../altimate/review-pii-new-exposure.test.ts | 185 +++++++++++++++- .../review-pii-no-change-edits.test.ts | 178 +++++++++++++++ 6 files changed, 602 insertions(+), 115 deletions(-) create mode 100644 packages/opencode/test/altimate/review-pii-no-change-edits.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 16b9dd8bb3..75af656c6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`altimate review` reads `.altimate/review.yml` from the base branch.** A PR can no longer relax the policy it is reviewed under; settings it changes are listed in the comment and take effect after merge. The `--mode` and `--severity` flags (the action's `mode` and `severity_threshold`) can only tighten a base policy, and `allowForceTier: false` rejects `--force-tier`. (#1722) - **`altimate review` flags PII only for columns the change newly exposes**, not for PII columns the base already surfaced. Without a compiled base, a PII column is a non-blocking warning that may predate the PR, unless the base SQL cannot have exposed it (see the next entry). (#1721) -- **`altimate review` reports three PII exposures it used to call pre-existing.** Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, its final query names every column in its own select list (no `*`, `COLUMNS(…)`, whole-row reference or struct expansion), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. A renamed PII output (`email as contact`) is then new. A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name; the quote style and spacing inside a `ref` or `source` call do not count, a quoted SQL name is compared as written), or, for a model compiled under a name its `ref` does not show (an alias, a version or a source `identifier:`), when no relation in the model's code changed; a schema, `source` or `var` swapped in the model's code is reported. Where the code cannot decide, and for a source while the PR edits a `schema:`, `database:` or `identifier:` line in YAML, the column is a non-blocking warning that may predate the PR; a schema swap made only in YAML outside the PR is not detected. A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported, also after a first branch that selects `*`. (#1875) +- **`altimate review` reports three PII exposures it used to call pre-existing.** Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, its final query names every column in its own select list (no `*`, `COLUMNS(…)`, whole-row reference, struct expansion or Unicode-escaped name such as `U&"…"`), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. A renamed PII output (`email as contact`) is then new. A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name; the quote style and spacing inside a `ref` or `source` call do not count, a quoted SQL name is compared as written), or, for a model compiled under a name its `ref` does not show (an alias, a version or a source `identifier:`), when no relation in the model's code was added or replaced; a schema, `source` or `var` swapped in the model's code is reported. Where the code cannot decide (such a model only gained a relation, the SQL is a shape the review does not fully parse, or two different relations share one table name), the column is a non-blocking warning that may predate the PR. A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported, also after a first branch that selects `*` from a CTE or subquery whose columns are all known, and so is a swap of which table each branch's computation reads (`md5(email)` from `a` and `lower(email)` from `b` reversed). Now reported that was not before: qualifying a raw table name (`from customers` → `from analytics.customers`), and replacing any relation, even an unrelated join, in a model compiled under a name its `ref` does not show. Not reliably detected yet: a computed UNION branch after a `*` over a table, a `ref()` or a CTE that itself selects `*` (its columns are matched only by their position among the select items). A source schema changed in YAML is a non-blocking warning, for every `source()` in the reviewed models, when the same PR edits a `schema:`, `database:` or `identifier:` key in a source YAML (or deletes one) and also changes a model that reads a source; a PR that edits only the YAML gets no finding, and a `+schema` for sources in `dbt_project.yml`, a schema from `var()` or `env_var()`, and changes made outside the PR are not detected. (#1875) ## [0.12.12] - 2026-11-20 diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index b608810f24..ce90179557 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -346,19 +346,38 @@ rubric: same table only when the model's own code reads it the same way on both sides, compiled into another environment: the same `ref` or `source` call or table name (the quote style and spacing inside a `ref` or `source` call aside; a - quoted SQL name is compared as written). A model whose compiled table name is not - the name in its `ref` (an `alias`, a version such as `ref('customers', v=2)`, - a custom alias macro, a source `identifier:`) counts as the same table only - when no `ref`, `source` or table name in the model's code changed. A changed - schema, `source`, `var` or package argument in the code is a different table, - and so, under another schema, is a quoted name whose case changed. When the - code cannot decide (such a model only gained a relation, or its SQL is a - shape the review does not parse and no Jinja expression in it changed), the - column is reported as a non-blocking warning that may predate the PR. A - source whose schema changes only in YAML is flagged the same way when the PR - edits a `schema:`, `database:` or `identifier:` line in a YAML file; - otherwise (a schema set by a var, or changed outside the PR) it is not - detected. That + quoted SQL name is compared as written). So qualifying a raw table name + (`from customers` → `from analytics.customers`) is reported: the qualified + name may be another table. A model whose compiled table name is not the name + in its `ref` (an `alias`, a version such as `ref('customers', v=2)`, a custom + alias macro, a source `identifier:`) counts as the same table when no + relation in the model's code was added or replaced (removing a join is + fine). When a relation was replaced, even an unrelated join, the compiled + name cannot be tied to the unchanged call, so it counts as a different table + and can block. A changed schema, `source`, `var` or package argument in the + code is a different table, and so, under another schema, is a quoted name + whose case changed. When the code cannot decide (such a model only gained a + relation; its SQL is a shape the review does not fully parse and no relation + in it was replaced, where a `config()` or select-list Jinja edit does not + count; or it reads two different relations with one table name, such as two + `source()` calls for `customers`), the column is reported as a non-blocking + warning that may predate the PR. A source whose schema changes only in YAML + is flagged the same way when the same PR edits a `schema:`, `database:` or + `identifier:` key in a source YAML (a YAML file that declares `sources:`; a + deleted one counts) and also changes a model that reads a source; the warning + then covers every `source()` the reviewed models read, not only the edited + source. A PR that edits only the YAML gets no PII finding, and a `+schema` + set for sources in `dbt_project.yml`, a schema from `var()` or `env_var()`, + and changes made outside the PR are not detected. A UNION branch that + computes PII under a name the base already exposed (`lower(ssn) as email`) is + reported. After a first branch that selects `*` from a CTE or subquery whose + columns are all known, each later-branch column is matched to the output + column it lands in (`select *, 'web' as channel from c` puts `channel` after + all of `c`'s columns). After a `*` over a table, a `ref()` or a CTE that + itself selects `*`, the columns are unknown: a later-branch column is matched + only by its position among the first branch's select items, which the `*` + throws off, so a computed PII read at or after that `*` is not reliably + detected yet. That comparison needs the base version's SQL; when it can't be compiled, a PII column is reported as a non-blocking warning that may predate the PR, unless the base file's own SQL cannot have exposed that output column name: then it @@ -367,7 +386,8 @@ rubric: (string literals count), its final query has its own select list naming each column (no `*`, no dynamic column selector such as `COLUMNS(…)`, no source selected as a whole row such as `select c` or `to_json(c)`, no struct or array - expansion such as `unnest(payload)`; a final `table c` or `from c` selects + expansion such as `unnest(payload)`, no Unicode-escaped name such as + `U&"e\006Dail"`; a final `table c` or `from c` selects every column), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags (a macro call, a variable or an `{% include %}` could emit any column). The proof is about the output name, so a renamed PII output diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 841235a674..ba6a987826 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -8,7 +8,14 @@ import { dedupe, SEVERITY_ORDER, } from "./finding" -import { type ChangedFile, type DbtProjectLayout, filterChangedFiles, hasOldSide } from "./diff-filter" +import { + type ChangedFile, + type DbtProjectLayout, + classifyDbtFile, + filterChangedFiles, + hasOldSide, + looksLikeSourceYml, +} from "./diff-filter" import { classifyPR, compilePathTokenResolver, TIER_LANES } from "./risk-tier" import { type Rubric, exclusionReason, clampSeverity } from "./rubric" import { type ReviewConfig } from "./config" @@ -25,6 +32,7 @@ import { explicitProjection, rawRelationsMatch, type RelationMatch, + lineageCovered, refCovered, ROOT_SCOPE, SILENT_JINJA_TAG, @@ -1169,6 +1177,8 @@ function rawBaseCode(oldSql: string | undefined): string | undefined { // list does not (`with u as (select id from c) table c`), nor a final query // without one, nor a whole row or a struct expansion (`select c`, `unnest(s)`). if (!explicitProjection(oldSql)) return undefined + // A Unicode-escaped name (`U&"e\006Dail"` is `email`) is not searched as written. + if (/(? RAW_BASE_STAR.test(i.text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ")))) return undefined // Comments out, literals and quoted identifiers kept (one pass, so `--` inside @@ -1183,6 +1193,35 @@ function rawBaseLacks(code: string | undefined, names: string[]): boolean { return names.every((n) => !new RegExp(`(? { + if (!/\.ya?ml$/i.test(file.path) || classifyDbtFile(file.path, layout) === "project_config") return false + const read = (path: string, side: "old" | "new") => Promise.resolve(getContent?.(path, side)).catch(() => undefined) + const contents = ( + await Promise.all([ + file.status !== "deleted" ? read(file.path, "new") : undefined, + file.status !== "added" ? read(file.oldPath ?? file.path, "old") : undefined, + ]) + ).filter((c): c is string => !!c?.trim()) + const declaresSources = contents.some((c) => /^["']?sources["']?\s*:/m.test(c)) || looksLikeSourceYml(file.diff) + if (contents.length && !declaresSources) return false + if (file.status === "deleted" || !file.diff?.trim()) return true + return file.diff.split("\n").some((line) => !/^(?:\+\+\+|---)(?:\s|$)/.test(line) && SOURCE_KEY_EDIT.test(line)) +} + export async function runReview(input: OrchestrateInput): Promise { const reviewable = filterChangedFiles(input.changedFiles, input.rubric.exclusions.excludeGlobs, input.layout) const dialect = input.config.dialect @@ -1321,11 +1360,9 @@ export async function runReview(input: OrchestrateInput): Promise - /\.ya?ml$/i.test(f.path) && /^[+-](?![+-])\s*(?:-\s*)?(?:schema|database|identifier)\s*:/m.test(f.diff ?? ""), + // A source YAML edit may move a `source()` whose text in the model is unchanged. + const sourcesEdited = (await Promise.all(input.changedFiles.map((f) => sourceYamlEdited(f, getContent, input.layout)))).some( + Boolean, ) // Parsed only when a prefix difference needs it: it re-parses both raw sides. const relationMatchByFile = new Map RelationMatch>() @@ -1337,14 +1374,17 @@ export async function runReview(input: OrchestrateInput): Promise ({ + // `unknownAsSame`: whether a prefix difference the raw code cannot decide + // counts as the same table; `unknownAsked` records that one was asked. + const envOf = ( + file: string, + opts: { unknownAsSame?: boolean; unknownAsked?: { value: boolean } } = {}, + ): RelationPrefixes => ({ base: outputs(file, "old").prefixes, sameRelation: (table) => { const match = relationMatch(file, table) - if (match === "unknown" && seen) seen.unknown = true - return match === "same" || (match === "unknown" && unknownAs) + if (match === "unknown" && opts.unknownAsked) opts.unknownAsked.value = true + return match === "same" || (match === "unknown" && !!opts.unknownAsSame) }, }) // `source.column` refs the base exposed raw under a name its PII detection @@ -1420,7 +1460,7 @@ export async function runReview(input: OrchestrateInput): Promise covered(ref) || refCovered(ref, baseReads, env)) && !!baseLineage && - [...(head.lineage.get(name) ?? [])].every((sig) => baseLineage.has(sig)) + [...(head.lineage.get(name) ?? [])].every((sig) => lineageCovered(sig, baseLineage, env)) ) return true } @@ -1432,14 +1472,22 @@ export async function runReview(input: OrchestrateInput): Promise refCovered(ref, exposed, env))) return true // The same computation counts only over the same source columns: the // signature holds the item text and derived-query bodies, not the tables - // (`lower(email)` from `customers` → from `spouses` is new). Refs no + // (`lower(email)` from `customers` → from `spouses` is new), and each + // lineage record pairs a computation with the columns it reads (`md5` + // and `lower` swapped between two tables' `email` is new). Refs no // source explains are left to the signature. const baseReads = base.reads.get(name) ?? new Set() const sameReads = [...(reads ?? [])] .filter((ref) => !ref.startsWith("?")) .every((ref) => refCovered(ref, baseReads, env)) const baseSigs = base.signatures.get(name) - return sameReads && !!baseSigs && [...(head.signatures.get(name) ?? [])].every((sig) => baseSigs.has(sig)) + const baseLineage = base.lineage.get(name) + return ( + sameReads && + !!baseSigs && + [...(head.signatures.get(name) ?? [])].every((sig) => baseSigs.has(sig)) && + [...(head.lineage.get(name) ?? [])].every((sig) => lineageCovered(sig, baseLineage, env)) + ) } // Unresolved only through a plain `*`: a shape the parser does not model (a // parenthesised top-level union, `* except (…)`) is reported. A `*` the @@ -1452,10 +1500,14 @@ export async function runReview(input: OrchestrateInput): Promise) => { - const seen = { unknown: false } - if (isBaseExposedOutput(file, name, basePii, envOf(file, false, seen))) return "exposed" - return seen.unknown && isBaseExposedOutput(file, name, basePii, envOf(file, true)) ? "undecided" : "new" + const unknownAsked = { value: false } + if (isBaseExposedOutput(file, name, basePii, envOf(file, { unknownAsked }))) return "exposed" + if (!unknownAsked.value) return "new" + return isBaseExposedOutput(file, name, basePii, envOf(file, { unknownAsSame: true })) ? "undecided" : "new" } // The raw base as `rawBaseLacks` reads it, parsed once per file and only when // a PII lane needs it (the engine lanes and the regex twins share it). @@ -1751,10 +1803,11 @@ export async function runReview(input: OrchestrateInput): Promise { if (m.startsWith('"')) return m - if (m.startsWith("{{")) return m.replace(/[^\n]/g, "_") + if (m.startsWith("{{")) return "_".repeat(m.length) if (m.startsWith("'")) return keepLiterals ? m : `'${m.slice(1, -1).replace(/[^\n]/g, " ")}'` return m.replace(/[^\n]/g, " ") }) @@ -491,7 +493,7 @@ function parseSelects(sql: string): ParsedSelects { const s = maskSql(sql) const withLiterals = maskSql(sql, true) const lineStarts = [0] - for (let i = 0; i < s.length; i++) if (s[i] === "\n") lineStarts.push(i + 1) + for (let i = 0; i < sql.length; i++) if (sql[i] === "\n") lineStarts.push(i + 1) const lineOf = (offset: number) => { let lo = 0 let hi = lineStarts.length - 1 @@ -934,6 +936,8 @@ export function selectSources(sql: string): (scope: string, branch: number) => s } const STAR = new RegExp(String.raw`^(?:${SEGMENT}\.)*\*$`) +/** A `*` with modifiers (`* exclude (a)`, `c.* replace (…)`, `* like 'e%'`). */ +const STAR_PREFIX = new RegExp(String.raw`^(?:${SEGMENT}\.)*\*`) /** The model's final output, as `finalOutputs` resolves it. */ export interface FinalOutputs { @@ -971,11 +975,14 @@ export interface FinalOutputs { * literals as written, each FROM/JOIN alias named by its source) plus the * full text of every CTE or subquery its select reads. Equal signatures on two sides mean the name is computed the same way. */ signatures: Map> - /** Per output name, as `signatures` but following columns, not whole bodies: - * the item text plus, per CTE or subquery it reads, that scope's `lineage` - * of each column the item names (the scope's whole body when a `*` there may - * pass the column on). Another column or a filter added to that CTE leaves it - * unchanged; unmasking the column there (`md5(ssn) as ssn` → `ssn`) does not. */ + /** Per output name, as `signatures` but following columns, not whole bodies, + * one record per item: the item text plus, per CTE or subquery it reads, that + * scope's `lineage` of each column the item names (the scope's whole body + * when a `*` there may pass the column on), paired with the `source.column` + * refs the item reads (`lineageCovered` compares them). Another column or a + * filter added to that CTE leaves it unchanged; unmasking the column there + * (`md5(ssn) as ssn` → `ssn`), or moving `md5(…)` to another table's column, + * does not. */ lineage: Map> /** Per output name, every `source.column` ref its value is computed from, raw * or not, resolved like `raw` (`lower(s.ssn) as email` with `spouses s` → @@ -986,6 +993,10 @@ export interface FinalOutputs { interface ScopeOutputs extends Omit { /** `*` 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 + * every column is known: no `*` over a table, a `ref()` or a scope whose + * columns are themselves not all known. */ + layout?: Array /** Every item's text, and that of every scope it reads. */ body: string } @@ -997,7 +1008,7 @@ const splitRef = (ref: string) => { return { tables: ref.slice(0, dot).split("|"), column: ref.slice(dot + 1) } } -/** A table name split into its database/schema prefix and its own name. A Jinja +/** A table name split into its database/schema prefix and its unqualified name. A Jinja * `{{ ref(…) }}` name has no prefix. */ function splitTable(table: string): { prefix: string; name: string } { const dot = table.startsWith("{{") ? -1 : table.lastIndexOf(".") @@ -1008,7 +1019,7 @@ function splitTable(table: string): { prefix: string; name: string } { * asks only whether the base already read tables under the head's prefix. */ export interface RelationPrefixes { base: Set - /** The compiled table's own name may differ by prefix as an environment + /** The compiled table's unqualified name may differ by prefix as an environment * change: the RAW (uncompiled) model code reads it the same way on both * sides (`rawRelationsMatch`). Without it, a prefix difference is always a * different table. */ @@ -1036,10 +1047,10 @@ function normalizeRelation(text: string): string { }) } -/** A normalised relation's own name, lowercased to compare with a compiled +/** A normalised relation's unqualified table name, lowercased to compare with a compiled * name: the last positional string argument of `{{ ref(…) }}` / `{{ source(…) }}`, * else its last dot-separated segment outside Jinja and quotes. */ -function relationOwnName(text: string): string { +function relationTableName(text: string): string { const call = /^\{\{(?:ref|source)\((.*)\)\}\}$/.exec(text) if (call) { const args = [...call[1].matchAll(/(?>; all: Set; complete: boolean } { const { items, sources, unknownSources, unmodelled, misread } = parseSelects(sql) @@ -1073,7 +1084,7 @@ function relationTexts(sql: string): { byName: Map>; all: Se // The original text, not the parser's name: that masks Jinja to `_`, so two // prefixes of one length (`var('masked')`, `var('raw_db')`) would look alike. const text = normalizeRelation(src.text) - const own = relationOwnName(text) + const own = relationTableName(text) all.add(text) const texts = byName.get(own) if (texts) texts.add(text) @@ -1084,19 +1095,22 @@ function relationTexts(sql: string): { byName: Map>; all: Se return { byName, all, complete: unknownSources.size === 0 && !unmodelled && !misread } } -/** Whether a compiled table's own name may differ by prefix between base and - * head as an environment change, judged from the raw model code. A name the - * raw code reads (`ref('customers')`, `analytics.customers`) is `same` when the - * same relation texts read it on both sides, else `different`. A name it never - * writes (a model with an `alias`, a version, a source `identifier:`: - * `ref('customers', v=2)` compiles to `customers_v2`) cannot be tied to one - * call: `same` when every source is named and none changed; `different` when a - * relation the base read is gone, or when the parse is incomplete and the - * model's Jinja expressions changed (a macro that emits the whole query, its - * arguments changed); otherwise (relations only added, or an incomplete parse - * with no change seen) `unknown`. A `source()` read while the pull request - * edits a `schema:`/`database:`/`identifier:` line in YAML (`sourcesEdited`) is - * at best `unknown`: the swap may be there. A missing side proves nothing. */ +/** Whether a compiled table's unqualified name may differ by prefix between + * base and head as an environment change, judged from the raw model code. A + * name the raw code reads (`ref('customers')`, `analytics.customers`) is + * `same` when the same relation texts read it on both sides, `different` when + * they differ, and `unknown` when it is read by two different texts (two + * `source()` calls or package `ref`s for `customers`: which one the compiled + * table is cannot be told). A name it never writes (a model with an `alias`, + * a version, a source `identifier:`: `ref('customers', v=2)` compiles to + * `customers_v2`) cannot be tied to one call. Only relations are evidence + * (the FROM/JOIN texts, or, when the parser lists none, the query's Jinja + * expressions but `config()`, as a macro that emits the whole query): a + * replacement (one removed and one added) is `different`; with a complete + * parse, relations only removed or none changed is `same`; anything else + * (relations only added, an incomplete parse) is `unknown`. A `source()` read + * while the pull request edits a source YAML (`sourcesEdited`) is at best + * `unknown`: the swap may be there. A missing side proves nothing. */ export function rawRelationsMatch( oldSql: string | undefined, newSql: string | undefined, @@ -1107,27 +1121,31 @@ export function rawRelationsMatch( const head = relationTexts(newSql) const sameSet = (a: Set | undefined, b: Set | undefined) => !!a && !!b && a.size === b.size && [...a].every((t) => b.has(t)) - const unchanged = (texts: Set): RelationMatch => + const unchangedMatch = (texts: Set): RelationMatch => sourcesEdited && [...texts].some((t) => t.startsWith("{{source(")) ? "unknown" : "same" - const complete = base.complete && head.complete - const jinja = (sql: string) => new Set((sql.match(/\{\{[\s\S]*?\}\}/g) ?? []).map(normalizeRelation)) - const untied: RelationMatch = - [...base.all].some((t) => !head.all.has(t)) || (!complete && !sameSet(jinja(oldSql), jinja(newSql))) - ? "different" - : complete && sameSet(base.all, head.all) - ? unchanged(base.all) - : "unknown" + const evidence = (side: typeof base, sql: string) => + side.all.size || side.complete + ? side.all + : new Set((sql.match(/\{\{[\s\S]*?\}\}/g) ?? []).map(normalizeRelation).filter((t) => !t.startsWith("{{config("))) + const was = evidence(base, oldSql) + const now = evidence(head, newSql) + const removed = [...was].some((t) => !now.has(t)) + const added = [...now].some((t) => !was.has(t)) + let untied: RelationMatch = "unknown" + if (removed && added) untied = "different" + else if (base.complete && head.complete && !added) untied = unchangedMatch(base.all) return (table) => { const a = base.byName.get(table) const b = head.byName.get(table) if (!a && !b) return untied - return sameSet(a, b) ? unchanged(a!) : "different" + if (!sameSet(a, b)) return "different" + return a!.size > 1 ? "unknown" : unchangedMatch(a!) } } /** * Head table `h` and base table `b` are the same table. Equal names are. With - * the same own name, a prefix difference is an environment difference (a base + * the same unqualified name, a prefix difference is an environment difference (a base * compiled into `dbt_prod` and a head into `dbt_ci_pr_42`, or a `+schema` * change) only when the raw model code reads that table the same way on both * sides (`env.sameRelation`, see `rawRelationsMatch`): compiled SQL alone cannot tell a @@ -1178,6 +1196,26 @@ export function refCovered(ref: string, exposed: Set, env?: RelationPref return false } +/** A `lineage` record: a digest of the item's computation, including the + * unqualified table name of each column it reads, then its full refs. */ +const LINEAGE_REFS = "\u0006" + +/** + * The head `record` (see `FinalOutputs.lineage`) is computed as one of the base + * records: the same digest, and every ref it reads covered by that record's + * refs (`refCovered`, so a table compiled into another environment matches). + */ +export function lineageCovered(record: string, base: Set | undefined, env?: RelationPrefixes): boolean { + if (!base) return false + if (base.has(record)) return true + const [digest, refs] = record.split(LINEAGE_REFS) + return [...base].some((b) => { + const [baseDigest, baseRefs] = b.split(LINEAGE_REFS) + const covered = new Set(baseRefs ? baseRefs.split("\u0007") : []) + return baseDigest === digest && (!refs || refs.split("\u0007").every((ref) => refCovered(ref, covered, env))) + }) +} + /** `sql` lowercased except inside string literals, whose case can change what * an expression does (`regexp_replace(email, '[a-z]', '*')`). */ const lowerOutsideLiterals = (sql: string) => @@ -1275,7 +1313,7 @@ export function finalOutputs(sql: string): FinalOutputs { return same(unresolved(col)) } // An item's text for signatures: lowercased outside literals, with each - // FROM/JOIN alias replaced by the source it names (a table by its own name, + // FROM/JOIN alias replaced by the source it names (a table by its unqualified name, // without database/schema, which `refCovered` compares environment-aware via // `reads`; a CTE or subquery by its scope), so renaming an alias // (`md5(c.ssn)` → `md5(cu.ssn)` on one table) keeps the signature. @@ -1311,7 +1349,31 @@ export function finalOutputs(sql: string): FinalOutputs { } const scopeItems = byScope.get(scope) ?? [] const firstNames = new Map(scopeItems.filter((i) => i.branch === 0).map((i) => [i.position, i.name])) - const firstStar = scopeItems.find((i) => i.branch === 0 && STAR.test(i.text))?.position + // The columns an item outputs, in order: one; for a `*` over CTEs or + // subqueries whose columns are all known, theirs; else unknown (a `*` over + // a table, `* exclude (…)`, `unnest(…)`). + const columnsOf = (item: SelectItem): Array | undefined => { + if (!STAR.test(item.text)) return STAR_PREFIX.test(item.text) || UNNAMED_COLUMNS.test(item.text) ? undefined : [item.name] + const q = /([^.]+)\.\*$/.exec(item.text)?.[1] + const srcs = (sources.get(`${scope}#${item.branch}`) ?? []).filter((src) => !q || src.alias === unquote(q) || src.name === unquote(q)) + const parts = srcs.map((src) => (isDerived(src, scope, seen) ? resolve(src.name, inner).layout : undefined)) + return srcs.length && parts.every((p) => p) ? parts.flatMap((p) => p!) : undefined + } + // Each item's first output column (unknown past a `*` with unknown columns), + // and the first branch's names by column up to its first unknown `*`. + const ordinal = new Map() + const offsets = new Map() + const firstColumns: Array = [] + let layout: Array | undefined = firstColumns + for (const item of [...scopeItems].sort((a, b) => a.branch - b.branch || a.position - b.position)) { + const offset = offsets.has(item.branch) ? offsets.get(item.branch) : 0 + const columns = offset === undefined ? undefined : columnsOf(item) + if (offset !== undefined) ordinal.set(item, offset) + offsets.set(item.branch, columns && offset !== undefined ? offset + columns.length : undefined) + if (item.branch !== 0 || !layout) continue + if (columns) firstColumns.push(...columns) + else layout = undefined + } const readBodies = new Set() for (const item of scopeItems) { const derived = (sources.get(`${scope}#${item.branch}`) ?? []).filter((src) => isDerived(src, scope, seen)) @@ -1332,18 +1394,17 @@ export function finalOutputs(sql: string): FinalOutputs { } continue } - const name = item.branch === 0 ? item.name : firstNames.get(item.position) - // A later branch's item at or after a `*` of the first branch has no known - // name: its reads count toward every name the scope outputs, so the `*` - // does not hide a computed read (`select * from c union all select - // lower(email) as email from secrets`). Never a raw exposure. - const targets = name - ? [name] - : item.branch > 0 && firstStar !== undefined && item.position >= firstStar - ? [...names] - : [] - if (!targets.length) continue - if (name) names.add(name) + // A later branch's item takes the first branch's name at its column: past + // a `*` of known columns, through them (`select *, 'web' as channel from c` + // puts `channel` after all of `c`'s columns); where a `*`'s columns are + // unknown (a table, a `ref()`), at its position among the select items. + let name = item.name + if (item.branch > 0) { + const at = ordinal.get(item) + name = at !== undefined && at < firstColumns.length ? firstColumns[at] : firstNames.get(item.position) + } + if (!name) continue + names.add(name) const text = signatureText(item, scope) // Each read follows only the CTE or subquery it comes from: a qualifier // names one source; an unqualified read may come from any that has it. @@ -1357,18 +1418,14 @@ export function finalOutputs(sql: string): FinalOutputs { .map((src) => ({ src, out: resolve(src.name, inner) })) .filter(({ out }) => named || out.names.has(column) || out.stars.length) .map(({ src, out }) => { - const of = out.names.has(column) - ? [...(out.lineage.get(column) ?? [])].sort().join("\u0005") - : out.stars.length - ? out.body - : "" + let of = "" + if (out.names.has(column)) + of = [...(out.lineage.get(column) ?? [])].map((sig) => sig.split(LINEAGE_REFS)[0]).sort().join("\u0005") + else if (out.stars.length) of = out.body return `${src.name}.${column}:${of}` }) }) .sort() - // A digest, so a column computed from several upstream columns at every - // level of a CTE chain does not grow its key exponentially. - const digest = createHash("sha1").update(`${text}\u0001${upstream.join("\u0002")}`).digest("base64") const refs = item.rawColumn ? resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen) : { @@ -1378,17 +1435,27 @@ export function finalOutputs(sql: string): FinalOutputs { // An expression whose column reads parse to nothing is not known to read // nothing: it is never "already exposed" by its reads (the signature may // still match). Only a constant reads nothing. - if (!item.rawColumn && !item.reads?.length && !item.constant) refs.reads = unresolved(name ?? "") - for (const target of targets) { - addTo(signatures, target, [`${text}\u0001${bodies.join("\u0002")}`]) - addTo(lineage, target, [digest]) - if (name) addTo(raw, target, refs.raw) - addTo(reads, target, refs.reads) - } + if (!item.rawColumn && !item.reads?.length && !item.constant) refs.reads = unresolved(name) + // The computation paired with what it reads: its digest holds each read's + // unqualified table name (an environment change keeps it), the record its + // full refs. A digest, so a column computed from several upstream columns + // at every level of a CTE chain does not grow its key exponentially. + const known = [...refs.reads].filter((r) => !r.startsWith("?")).sort() + const tables = known.map((r) => { + const split = splitRef(r) + return `${split.tables.map((t) => splitTable(t).name).join("|")}.${split.column}` + }) + const digest = createHash("sha256") + .update(`${text}\u0001${upstream.join("\u0002")}\u0001${tables.join("\u0002")}`) + .digest("base64") + addTo(signatures, name, [`${text}\u0001${bodies.join("\u0002")}`]) + addTo(lineage, name, [`${digest}${LINEAGE_REFS}${known.join("\u0007")}`]) + addTo(raw, name, refs.raw) + addTo(reads, name, refs.reads) } for (const [n, cols] of raw) if (!cols.size) raw.delete(n) const body = [scopeItems.map((i) => signatureText(i, scope)).join(","), ...[...readBodies].sort()].join("\u0003") - const result = { raw, names, signatures, lineage, reads, stars, body } + const result = { raw, names, signatures, lineage, reads, stars, body, layout } memo.set(scope, result) return result } @@ -2132,7 +2199,7 @@ export function rawReach(sql: string): RawReach { masked ??= maskSql(sql) if (!lineStarts) { lineStarts = [0] - for (let i = 0; i < masked.length; i++) if (masked[i] === "\n") lineStarts.push(i + 1) + for (let i = 0; i < sql.length; i++) if (sql[i] === "\n") lineStarts.push(i + 1) } const start = lineStarts[line - 1] if (start === undefined) return false diff --git a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts index fd300b5a5c..e2c106c14a 100644 --- a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts +++ b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts @@ -51,8 +51,8 @@ const run = async (o: { reviewers: string[] runner: ReviewRunner compiled?: (side: "old" | "new") => string | undefined - /** Other files the pull request changes (a `sources.yml`, say). */ - others?: ChangedFile[] + /** Other files the pull request changes (a `sources.yml`, say), with their content. */ + others?: Array }) => { const env = await runReview({ changedFiles: [{ path: P, status: "modified", diff: o.diff } as ChangedFile, ...(o.others ?? [])], @@ -60,7 +60,8 @@ const run = async (o: { rubric: DEFAULT_RUBRIC, mode: "gate", runner: o.runner, - getContent: async (f: string, side: "old" | "new") => (f !== P ? "" : side === "new" ? o.head : o.base), + getContent: async (f: string, side: "old" | "new") => + f === P ? (side === "new" ? o.head : o.base) : o.others?.find((x) => x.path === f)?.content?.[side], getCompiled: o.compiled ? async (_f: string, side: "old" | "new") => o.compiled!(side) : undefined, }) const pii = env.findings.filter((f) => f.category === "pii_exposure") @@ -369,9 +370,11 @@ const expectUndecided = (r: Awaited>, label: unknown) => critical: r.critical, blocks: r.verdict === "REQUEST_CHANGES", unknown: r.pii.every((f) => f.confidence === "unknown"), - }).toEqual({ label, reported: true, critical: false, blocks: false, unknown: true }) + // A warning, so `severityThreshold: warning` still shows it. + warning: r.pii.every((f) => f.severity === "warning"), + }).toEqual({ label, reported: true, critical: false, blocks: false, unknown: true, warning: true }) -describe("review round: lineage follows each read to its own source", () => { +describe("lineage follows each read to its own source", () => { test("editing a joined CTE the branch does not read keeps an already-exposed name quiet", async () => { // `s` and `d` both expose `email`; the branch reads `s.email` only. const sql = (d: string) => @@ -394,7 +397,7 @@ describe("review round: lineage follows each read to its own source", () => { }) }) -describe("review round: only the final query's explicit projection proves a column absent", () => { +describe("only the final query's explicit projection proves a column absent", () => { const ref = "{{ ref('stg_customers') }}" const h = `select customer_id,\n email\nfrom ${ref}` const compiledHead = (side: "old" | "new") => (side === "new" ? h.replace(ref, "analytics.stg_customers") : undefined) @@ -429,7 +432,7 @@ describe("review round: only the final query's explicit projection proves a colu }) }) -describe("review round: a prefix difference the raw code cannot explain is undecided", () => { +describe("a prefix difference the raw code cannot explain is undecided", () => { const runner = () => piiRunner(["ssn"]) const compiledFrom = (b: string, h: string, fromBase: string, fromHead: string) => (side: "old" | "new") => side === "old" ? b.replace(/\{\{ source\('crm', 'cust'\) \}\}|\{\{ ref\('customers'\) \}\}/, fromBase) : h.replace(/\{\{ source\('crm', 'cust'\) \}\}|\{\{ ref\('customers'\) \}\}/, fromHead).replace("{{ ref('regions') }}", "analytics.dbt_ci.regions") @@ -477,11 +480,177 @@ describe("review round: a prefix difference the raw code cannot explain is undec }) }) -describe("review round: a `*` first branch does not hide a later branch's computed read", () => { +describe("a later UNION branch after a first-branch `*`", () => { test("`lower(email)` from another table in a branch after `select * from c` is new exposure", async () => { const b = "with c as (select email from customers)\nselect * from c" const h = `${b}\nunion all\nselect lower(email) as email from secrets` for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) expectBlocks(await run({ base: b, head: h, diff: "+union all\n+select lower(email) as email from secrets\n", reviewers, runner: piiRunner(["email"]) }), reviewers) }) + + const cte = "with c as (select id, email from customers)\n" + test("an identical branch after a `*` over a CTE is not new exposure", async () => { + const b = `${cte}select * from c` + const h = `${b}\nunion all\nselect id, email from customers` + for (const reviewers of REVIEWER_SETS) + expectQuiet(await run({ base: b, head: h, diff: "+union all\n+select id, email from customers\n", reviewers, runner: piiRunner(["email"]) }), reviewers) + }) + + test("a later branch maps through the `*`'s columns: `select *, 'web' as channel from c`", async () => { + const b = `${cte}select *, 'web' as channel from c` + // Position 1 is `email` (the second column of `c`), not `channel`. + const same = `${b}\nunion all\nselect id, email, 'web' from customers` + for (const reviewers of REVIEWER_SETS) + expectQuiet(await run({ base: b, head: same, diff: "+union all\n+select id, email, 'web' from customers\n", reviewers, runner: piiRunner(["email"]) }), reviewers) + const computed = `${b}\nunion all\nselect id, lower(ssn), 'web' from secrets` + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks(await run({ base: b, head: computed, diff: "+union all\n+select id, lower(ssn), 'web' from secrets\n", reviewers, runner: piiRunner(["email"]) }), reviewers) + }) + + test("after a `*` over a table, a later branch keeps its position mapping", async () => { + // The table's columns are unknown, so `lower(ssn)` is placed at its position + // among the select items (under `email`), as before: never attached to every + // output, so an identical branch stays quiet. + const b = "select c.*, 'internal' as email from customers c" + const h = `${b}\nunion all\nselect id, lower(ssn) from secrets` + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks(await run({ base: b, head: h, diff: "+union all\n+select id, lower(ssn) from secrets\n", reviewers, runner: piiRunner(["email"]) }), reviewers) + const star = "select * from customers" + const same = `${star}\nunion all\nselect * from customers` + for (const reviewers of REVIEWER_SETS) + expectQuiet(await run({ base: star, head: same, diff: "+union all\n+select * from customers\n", reviewers, runner: piiRunner(["email"]) }), reviewers) + }) + + test("swapping which table each computation reads is new exposure", async () => { + // `email` stays raw from `customers`; `a`'s email is no longer hashed. + const sql = (fa: string, fb: string) => + `select email from customers\nunion all\nselect ${fa}(email) as email from a\nunion all\nselect ${fb}(email) as email from b` + const diff = "-select md5(email) as email from a\n+select lower(email) as email from a\n-select lower(email) as email from b\n+select md5(email) as email from b\n" + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks(await run({ base: sql("md5", "lower"), head: sql("lower", "md5"), diff, reviewers, runner: piiRunner(["email"]) }), reviewers) + // The same branches compiled into another environment are not. + const compiled = (side: "old" | "new") => + sql("md5", "lower").replace(/from (customers|a|b)\b/g, `from ${side === "old" ? "dbt_prod" : "dbt_ci_42"}.$1`) + const raw = sql("md5", "lower").replace(/from (customers|a|b)\b/g, "from {{ ref('$1') }}") + const head = raw.replace("select email from", "select email\nfrom") + for (const reviewers of REVIEWER_SETS) + expectQuiet(await run({ base: raw, head, diff: "-select email from\n+select email\n+from\n", reviewers, runner: piiRunner(["email"]), compiled }), reviewers) + }) +}) + +describe("the same table across environments when the compiled name is tied to no `ref` call", () => { + const runner = () => piiRunner(["ssn"]) + // `customers` compiles to `customers_v2` (a version), so no raw call names it. + const joined = "select c.id, c.ssn, r.region\nfrom {{ ref('customers', v=2) }} c\njoin {{ ref('regions') }} r on r.id = c.region_id" + const compiled = (b: string, h: string) => (side: "old" | "new") => + (side === "old" ? b : h) + .replace("{{ ref('customers', v=2) }}", side === "old" ? "analytics.dbt_prod.customers_v2" : "analytics.dbt_ci_42.customers_v2") + .replace(/\{\{ ref\('(\w+)'\) \}\}/g, `analytics.${side === "old" ? "dbt_prod" : "dbt_ci_42"}.$1`) + + test("removing a join is not a swap", async () => { + const h = "select c.id, c.ssn\nfrom {{ ref('customers', v=2) }} c" + for (const reviewers of REVIEWER_SETS) + expectQuiet( + await run({ base: joined, head: h, diff: "-select c.id, c.ssn, r.region\n+select c.id, c.ssn\n-join {{ ref('regions') }} r on r.id = c.region_id\n", reviewers, runner: runner(), compiled: compiled(joined, h) }), + reviewers, + ) + expect(rawRelationsMatch(joined, h)("customers_v2")).toBe("same") + }) + + test("replacing an unrelated join still blocks (the documented trade-off)", async () => { + // The `customers_v2` read cannot be told from the replaced relation, so the + // one-sided answer is a different table. + const h = joined.replace("{{ ref('regions') }} r", "{{ ref('regions_v3') }} r") + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks( + await run({ base: joined, head: h, diff: "-join {{ ref('regions') }} r on r.id = c.region_id\n+join {{ ref('regions_v3') }} r on r.id = c.region_id\n", reviewers, runner: runner(), compiled: compiled(joined, h) }), + reviewers, + ) + }) + + test("a `config()` or select-list Jinja edit on an incomplete parse is no evidence of a swap", () => { + const alt = (cfg: string, col: string) => + `{{ config(materialized='${cfg}') }}\n{% if var('full', false) %}\nselect id, ${col}\nfrom {{ ref('customers', v=2) }}\n{% else %}\nselect id, ${col}\nfrom {{ ref('customers', v=2) }}\nwhere active\n{% endif %}` + expect(rawRelationsMatch(alt("view", "ssn"), alt("table", "ssn"))("customers_v2")).toBe("unknown") + // A Jinja relation that is not a `ref`/`source` leaves the parse incomplete. + const joined = (col: string) => `select c.id, ${col}\nfrom {{ ref('customers', v=2) }} c\njoin {{ lookup_table() }} l on l.id = c.id` + expect(rawRelationsMatch(joined("c.ssn"), joined("{{ mask('c.ssn') }} as ssn"))("customers_v2")).toBe("unknown") + // A whole-query macro whose arguments changed is still a swap. + expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('raw') }}")("customers")).toBe("different") + }) + + test("two different relations with one unqualified table name are undecided", async () => { + const sql = (q: string) => + `select ${q}.id, ${q}.ssn\nfrom {{ source('crm', 'customers') }} a\njoin {{ source('erp', 'customers') }} b on a.id = b.id` + expect(rawRelationsMatch(sql("a"), sql("b"))("customers")).toBe("unknown") + const compiledSide = (side: "old" | "new") => + side === "old" + ? "select a.id, a.ssn\nfrom analytics.crm_prod.customers a\njoin analytics.erp_prod.customers b on a.id = b.id" + : "select b.id, b.ssn\nfrom analytics.crm_ci.customers a\njoin analytics.erp_ci.customers b on a.id = b.id" + for (const reviewers of REVIEWER_SETS) + expectUndecided( + await run({ base: sql("a"), head: sql("b"), diff: "-select a.id, a.ssn\n+select b.id, b.ssn\n", reviewers, runner: runner(), compiled: compiledSide }), + reviewers, + ) + }) +}) + +describe("a source YAML edit that may move a `source()`", () => { + const runner = () => piiRunner(["ssn"]) + const b = "select customer_id,\n ssn\nfrom {{ source('crm', 'customers') }}" + const h = b.replace("select customer_id,", "select customer_id, region,") + const compiled = (side: "old" | "new") => + (side === "old" ? b : h).replace("{{ source('crm', 'customers') }}", `analytics.${side === "old" ? "dbt_prod" : "dbt_ci_42"}.customers`) + const diff = "-select customer_id,\n+select customer_id, region,\n" + const sourcesYml = "version: 2\nsources:\n - name: crm\n schema: raw\n tables:\n - name: customers\n" + const yml = (path: string, ydiff: string | undefined, content?: { old?: string; new?: string }, status = "modified") => + [{ path, status, diff: ydiff, content } as ChangedFile & { content?: { old?: string; new?: string } }] + + test("a quoted or flow-style key, or a column-0 list item, counts as an edit", async () => { + const edits = { + quoted: '- "schema": masked\n+ "schema": raw\n', + single: "- 'database': masked\n+ 'database': raw\n", + flow: "- - {name: crm, schema: masked}\n+ - {name: crm, schema: raw}\n", + column0: "-- schema: masked\n+- schema: raw\n", + } + for (const [label, ydiff] of Object.entries(edits)) + for (const reviewers of REVIEWER_SETS) + expectUndecided( + await run({ base: b, head: h, diff, reviewers, runner: runner(), compiled, others: yml("models/staging/_sources.yml", ydiff, { old: sourcesYml, new: sourcesYml }) }), + { label, reviewers }, + ) + }) + + test("a `schema:` edit outside a source YAML does not", async () => { + const files = { + project: yml("dbt_project.yml", "- +schema: masked\n+ +schema: raw\n- schema: a\n+ schema: b\n", { old: "name: p\n", new: "name: p\n" }), + ci: yml(".github/workflows/ci.yml", "- schema: dbt_prod\n+ schema: dbt_ci\n", { old: "jobs:\n", new: "jobs:\n" }), + schemaYml: yml("models/marts/_models.yml", "- schema: a\n+ schema: b\n", { old: "version: 2\nmodels:\n", new: "version: 2\nmodels:\n" }), + } + for (const [label, others] of Object.entries(files)) + for (const reviewers of REVIEWER_SETS) expectQuiet(await run({ base: b, head: h, diff, reviewers, runner: runner(), compiled, others }), { label, reviewers }) + }) + + test("a deleted source YAML, or one whose diff is missing, counts as an edit", async () => { + const cases = { + deleted: yml("models/staging/_sources.yml", undefined, { old: sourcesYml }, "deleted"), + "no diff": yml("models/staging/_sources.yml", undefined, { old: sourcesYml, new: sourcesYml }), + } + for (const [label, others] of Object.entries(cases)) + for (const reviewers of REVIEWER_SETS) expectUndecided(await run({ base: b, head: h, diff, reviewers, runner: runner(), compiled, others }), { label, reviewers }) + }) +}) + +describe("absence proof from a raw base", () => { + test("a Unicode-escaped identifier (`U&\"…\"`) leaves the column undecided", async () => { + const ref = "{{ ref('stg_customers') }}" + const h = `select customer_id,\n email\nfrom ${ref}` + const b = `select customer_id,\n value as U&"e\\006Dail"\nfrom ${ref}` + const compiledHead = (side: "old" | "new") => (side === "new" ? h.replace(ref, "analytics.stg_customers") : undefined) + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []]) + expectUndecided( + await run({ base: b, head: h, diff: '- value as U&"e\\006Dail"\n+ email\n', reviewers, runner: piiRunner(["email"], classifyAll(/email/)), compiled: compiledHead }), + reviewers, + ) + }) }) diff --git a/packages/opencode/test/altimate/review-pii-no-change-edits.test.ts b/packages/opencode/test/altimate/review-pii-no-change-edits.test.ts new file mode 100644 index 0000000000..88e96f49cd --- /dev/null +++ b/packages/opencode/test/altimate/review-pii-no-change-edits.test.ts @@ -0,0 +1,178 @@ +import { describe, test, expect } from "bun:test" +import { runReview, DEFAULT_RUBRIC, DEFAULT_REVIEW_CONFIG, type ReviewRunner, type ChangedFile } from "../../src/altimate/review" + +// Property: an edit that cannot change which PII a model exposes never gets a +// blocking PII finding, whatever the lanes, with the base and the head compiled +// into different schemas (prod vs a CI schema) or with no compiled base. The +// exposure edits at the end are the controls: they must still be reported, so +// the property cannot hold by the check going silent. + +const PII = ["email", "ssn"] +// Output names a PII column reaches: its aliases, else the column itself. +const outputNames = (sql: string, col: string): string[] => { + const aliases = [...sql.matchAll(new RegExp(`\\b${col}\\s+as\\s+(\\w+)`, "gi"))].map((m) => m[1]) + if (aliases.length) return aliases + return new RegExp(`\\b${col}\\b`, "i").test(sql) ? [col] : [] +} +const runnerFor = (classify: boolean): ReviewRunner => + ({ + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [] } + }, + async equivalence() { + return { decided: false } + }, + async detectPii(sql: string) { + return { columns: [...new Set(PII.flatMap((c) => outputNames(sql, c)))] } + }, + async columnLineage(sql: string) { + return ["customer_id", ...PII].flatMap((c) => outputNames(sql, c).map((target) => ({ source: `customers.${c}`, target }))) + }, + async classifyPii(cols: string[]) { + if (!classify) return [] + return cols.map((c) => ({ column: c, classification: /email|ssn/.test(c) ? "PII" : "none", confidence: /email|ssn/.test(c) ? 0.95 : 0.1 })) + }, + }) as any + +// dbt compile into one environment: a `ref` to `analytics..` (a +// version to `_v`), a `source` to `analytics._.`. +const compile = (raw: string, env: string) => + raw + .replace(/\{\{-?\s*config\([^}]*\)\s*-?\}\}\n?/g, "") + .replace(/\{\{\s*ref\(\s*(['"])(\w+)\1\s*,\s*v(?:ersion)?\s*=\s*(\d+)\s*\)\s*\}\}/g, (_m, _q, m, v) => `analytics.${env}.${m}_v${v}`) + .replace(/\{\{\s*ref\(\s*(['"])(\w+)\1\s*\)\s*\}\}/g, (_m, _q, m) => `analytics.${env}.${m}`) + .replace(/\{\{\s*source\(\s*(['"])(\w+)\1\s*,\s*(['"])(\w+)\3\s*\)\s*\}\}/g, (_m, _q, s, _q2, t) => `analytics.${env}_${s}.${t}`) + +const STG = "{{ ref('stg_customers') }}" +const BASES: Record = { + single: `select customer_id, email, ssn\nfrom ${STG}`, + cteChain: `with base as (\n select customer_id, email from ${STG}\n),\nfiltered as (\n select customer_id, email from base where email is not null\n)\nselect customer_id, email\nfrom filtered`, + joinRefs: `select c.customer_id, c.email, o.order_total\nfrom ${STG} c\njoin {{ ref('stg_orders') }} o on o.customer_id = c.customer_id`, + versioned: `select customer_id, ssn\nfrom {{ ref('customers', v=2) }}`, + versionedJoin: `select c.customer_id, c.ssn, r.region\nfrom {{ ref('customers', v=2) }} c\njoin {{ ref('regions') }} r on r.id = c.region_id`, + source: `select customer_id, email\nfrom {{ source('crm', 'customers') }}`, + maskedSource: `select customer_id, ssn\nfrom {{ source('masked', 'customers') }}`, + union: `select customer_id, email\nfrom ${STG}\nunion all\nselect customer_id, email\nfrom {{ ref('stg_leads') }}`, + starCteUnion: `with c as (\n select customer_id, email from ${STG}\n)\nselect * from c\nunion all\nselect customer_id, email\nfrom {{ ref('stg_leads') }}`, + passthrough: `select *\nfrom ${STG}`, + masked: `select customer_id, md5(ssn) as ssn\nfrom ${STG}`, + config: `{{ config(materialized='table') }}\nselect customer_id, email\nfrom ${STG}`, + twoCtes: `with cust as (\n select customer_id, email from ${STG}\n),\nord as (\n select customer_id, count(*) as n from {{ ref('stg_orders') }} group by 1\n)\nselect cust.customer_id, cust.email, ord.n\nfrom cust\nleft join ord on ord.customer_id = cust.customer_id`, +} + +// Model-specific no-change edits, where a generic rewrite does not apply. +const SPECIFIC: Record> = { + cteChain: { "filter in a CTE": BASES.cteChain.replace(`email from ${STG}\n`, `email from ${STG} where customer_id > 0\n`) }, + joinRefs: { + "remove a join without PII": `select c.customer_id, c.email\nfrom ${STG} c`, + "filter on the joined table": `${BASES.joinRefs}\nwhere o.order_total > 0`, + }, + versionedJoin: { "remove a join without PII": `select c.customer_id, c.ssn\nfrom {{ ref('customers', v=2) }} c` }, + twoCtes: { + "non-PII column in an unrelated CTE": BASES.twoCtes.replace("count(*) as n", "count(*) as n, max(order_total) as top"), + "filter in an unrelated CTE": BASES.twoCtes.replace(" group by 1", " where order_total > 0 group by 1"), + "reorder CTE definitions": `with ord as (\n select customer_id, count(*) as n from {{ ref('stg_orders') }} group by 1\n),\ncust as (\n select customer_id, email from ${STG}\n)\nselect cust.customer_id, cust.email, ord.n\nfrom cust\nleft join ord on ord.customer_id = cust.customer_id`, + }, + starCteUnion: { + "identical branch over the CTE's table": `${BASES.starCteUnion}\nunion all\nselect customer_id, email from ${STG}`, + }, + config: { "change materialized": BASES.config.replace("'table'", "'view'") }, +} + +// The last select of the model to the end: its final query or last branch. +const lastSelect = (sql: string) => sql.slice(sql.toLowerCase().lastIndexOf("select ")) +const GENERIC: Record string | undefined> = { + reformat: (sql) => sql.replace(/,\s*/g, ",\n ").replace(/\s+(from|join|where|union all)\s+/gi, "\n $1 "), + "quote style in ref": (sql) => (sql.includes("ref('") ? sql.replace(/ref\('(\w+)'/g, 'ref("$1"') : undefined), + "add a non-PII column": (sql) => { + if (/union|\*/i.test(sql)) return undefined + const at = sql.toLowerCase().lastIndexOf("select ") + "select ".length + return `${sql.slice(0, at)}1 as one, ${sql.slice(at)}` + }, + "identical UNION branch": (sql) => `${sql}\nunion all\n${lastSelect(sql)}`, + "add a config block": (sql) => (sql.includes("config(") ? undefined : `{{ config(materialized='view') }}\n${sql}`), + "add comments": (sql) => `-- reviewed\n${sql}\n/* end of model */`, +} + +// Exposure edits: [base, head]. +const CONTROLS: Record = { + "ssn from a new table": [ + BASES.joinRefs, + `select c.customer_id, c.email, o.order_total, s.ssn\nfrom ${STG} c\njoin {{ ref('stg_orders') }} o on o.customer_id = c.customer_id\njoin {{ ref('secrets') }} s on s.customer_id = c.customer_id`, + ], + "masked column made raw": [BASES.masked, `select customer_id, ssn\nfrom ${STG}`], + "masked source swapped for raw": [BASES.maskedSource, BASES.maskedSource.replace("'masked'", "'raw'")], + "computed branch after a CTE `*`": [BASES.starCteUnion, `${BASES.starCteUnion}\nunion all\nselect customer_id, lower(ssn) as email\nfrom {{ ref('secrets') }}`], + "computed branch after explicit columns": [BASES.union, `${BASES.union}\nunion all\nselect customer_id, lower(ssn) as email\nfrom {{ ref('secrets') }}`], +} + +const P = "models/marts/m.sql" +const LANES = [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []] +// A line diff: enough for the lanes that read the added lines. +const lineDiff = (a: string, b: string) => { + const old = new Set(a.split("\n")) + const neu = new Set(b.split("\n")) + return [...a.split("\n").filter((l) => !neu.has(l)).map((l) => `-${l}`), ...b.split("\n").filter((l) => !old.has(l)).map((l) => `+${l}`)].join("\n") + "\n" +} +const review = async (base: string, head: string, reviewers: string[], compiledBase: boolean, classify: boolean) => { + const env = await runReview({ + changedFiles: [{ path: P, status: "modified", diff: lineDiff(base, head) } as ChangedFile], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: runnerFor(classify), + getContent: async (_f: string, side: "old" | "new") => (side === "new" ? head : base), + getCompiled: async (_f: string, side: "old" | "new") => + side === "new" ? compile(head, "dbt_ci_42") : compiledBase ? compile(base, "dbt_prod") : undefined, + }) + const pii = env.findings.filter((f) => f.category === "pii_exposure") + return { + blocks: pii.some((f) => f.severity === "critical") || (env.verdict === "REQUEST_CHANGES" && pii.length > 0), + pii: pii.map((f) => `${f.severity}/${f.confidence}/${f.evidence?.tool}: ${f.title}`), + } +} + +describe("an edit that cannot change which PII is exposed", () => { + test("never gets a blocking PII finding", async () => { + const cases: Array<{ base: string; edit: string; head: string }> = [] + for (const [name, sql] of Object.entries(BASES)) { + for (const [edit, fn] of Object.entries(GENERIC)) { + const head = fn(sql) + if (head !== undefined && head !== sql) cases.push({ base: name, edit, head }) + } + for (const [edit, head] of Object.entries(SPECIFIC[name] ?? {})) cases.push({ base: name, edit, head }) + } + expect(cases.length).toBeGreaterThanOrEqual(80) + const failures: unknown[] = [] + for (const c of cases) + for (const reviewers of LANES) + for (const compiledBase of [true, false]) + for (const classify of [false, true]) { + const r = await review(BASES[c.base], c.head, reviewers, compiledBase, classify) + if (r.blocks) + failures.push({ base: c.base, edit: c.edit, lanes: reviewers, compiledBase, classify, baseSql: BASES[c.base], head: c.head, findings: r.pii }) + } + expect(failures).toEqual([]) + }) + + test("while an exposure edit is still reported", async () => { + const failures: unknown[] = [] + for (const [label, [base, head]] of Object.entries(CONTROLS)) + for (const reviewers of LANES.slice(0, 2)) + for (const classify of [false, true]) { + // Proven new with a compiled base: blocks. + const compiled = await review(base, head, reviewers, true, classify) + if (!compiled.blocks) failures.push({ label, lanes: reviewers, compiledBase: true, classify, head, findings: compiled.pii }) + // Without one: at least reported. + const raw = await review(base, head, reviewers, false, classify) + if (!raw.pii.length) failures.push({ label, lanes: reviewers, compiledBase: false, classify, head, findings: raw.pii }) + } + expect(failures).toEqual([]) + }) +}) From e61fbdd91254351f6141a417544e733e3b4f05c9 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 2 Dec 2026 16:40:20 +0530 Subject: [PATCH 6/7] fix(review): renaming a CTE no longer blocks, and a commented base keeps its proof The lineage record holds no CTE or alias names. An added or removed same-named relation, or a package argument, is undecided, not a swap. The absence proof reads the base without its comments. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 4 +- docs/docs/usage/dbt-pr-review.md | 45 +++-- .../src/altimate/review/orchestrate.ts | 31 +++- .../src/altimate/review/rule-catalog.ts | 173 ++++++++++++------ .../altimate/review-pii-new-exposure.test.ts | 106 ++++++++++- .../review-pii-no-change-edits.test.ts | 68 ++++++- 6 files changed, 334 insertions(+), 93 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 75af656c6b..60594d545e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,13 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 **Breaking: `dbt_cost_estimate` is BigQuery only, so Snowflake and Databricks are no longer gated by `maxScanBytes`.** The tool used to give a scan figure on Snowflake and Databricks from the warehouse planner's EXPLAIN (bytes assigned there count partitions before runtime pruning and usually overstate what runs). It now answers `supported: false` on every warehouse but BigQuery and compiles nothing, so the Claude plugin's scan check (`maxScanBytes`, 10 GiB by default) no longer holds a `dbt run`, `build` or `show` on those two warehouses; the command runs with a line saying why. On BigQuery the scan figure is unchanged, and `history: true` now also reads what a model's earlier runs cost (billed `INFORMATION_SCHEMA.JOBS` queries; see the dbt tools page). -**Breaking: in `gate` mode, `altimate review` blocks only on engine findings, on pattern rules named in `rubric.blockingRules`, and on one proven-new PII pattern finding.** Before, any critical finding in a `blockOn` category could block, including pattern rules such as the regex PII check. Now pattern-rule findings comment but don't block unless their id is named in `rubric.blockingRules`; the AI lane never blocks. One pattern finding still blocks without being named: a highly sensitive PII column (SSN, passport or card number, date of birth) proven new when the base or the head can't be compiled. To keep another pattern rule blocking, add its id to `rubric.blockingRules`. (#1722) +**Breaking: in `gate` mode, `altimate review` blocks only on engine findings, on pattern rules named in `rubric.blockingRules`, and on one proven-new PII pattern finding.** Before, any critical finding in a `blockOn` category could block, including pattern rules such as the regex PII check. Now pattern-rule findings comment but don't block unless their id is named in `rubric.blockingRules`; the AI lane never blocks. One pattern finding still blocks without being named: a highly sensitive PII column (SSN, passport or card number, date of birth) proven new when the base or the head can't be compiled (proven only when the review reads the base file's SQL fully). To keep another pattern rule blocking, add its id to `rubric.blockingRules`. (#1722) ### Changed - **`altimate review` reads `.altimate/review.yml` from the base branch.** A PR can no longer relax the policy it is reviewed under; settings it changes are listed in the comment and take effect after merge. The `--mode` and `--severity` flags (the action's `mode` and `severity_threshold`) can only tighten a base policy, and `allowForceTier: false` rejects `--force-tier`. (#1722) - **`altimate review` flags PII only for columns the change newly exposes**, not for PII columns the base already surfaced. Without a compiled base, a PII column is a non-blocking warning that may predate the PR, unless the base SQL cannot have exposed it (see the next entry). (#1721) -- **`altimate review` reports three PII exposures it used to call pre-existing.** Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, its final query names every column in its own select list (no `*`, `COLUMNS(…)`, whole-row reference, struct expansion or Unicode-escaped name such as `U&"…"`), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. A renamed PII output (`email as contact`) is then new. A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name; the quote style and spacing inside a `ref` or `source` call do not count, a quoted SQL name is compared as written), or, for a model compiled under a name its `ref` does not show (an alias, a version or a source `identifier:`), when no relation in the model's code was added or replaced; a schema, `source` or `var` swapped in the model's code is reported. Where the code cannot decide (such a model only gained a relation, the SQL is a shape the review does not fully parse, or two different relations share one table name), the column is a non-blocking warning that may predate the PR. A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported, also after a first branch that selects `*` from a CTE or subquery whose columns are all known, and so is a swap of which table each branch's computation reads (`md5(email)` from `a` and `lower(email)` from `b` reversed). Now reported that was not before: qualifying a raw table name (`from customers` → `from analytics.customers`), and replacing any relation, even an unrelated join, in a model compiled under a name its `ref` does not show. Not reliably detected yet: a computed UNION branch after a `*` over a table, a `ref()` or a CTE that itself selects `*` (its columns are matched only by their position among the select items). A source schema changed in YAML is a non-blocking warning, for every `source()` in the reviewed models, when the same PR edits a `schema:`, `database:` or `identifier:` key in a source YAML (or deletes one) and also changes a model that reads a source; a PR that edits only the YAML gets no finding, and a `+schema` for sources in `dbt_project.yml`, a schema from `var()` or `env_var()`, and changes made outside the PR are not detected. (#1875) +- **`altimate review` reports three PII exposures it used to call pre-existing.** Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, its final query names every column in its own select list (no `*`, `COLUMNS(…)`, whole-row reference, struct expansion or Unicode-escaped name such as `U&"…"`), the review reads that query fully (a CTE column list, a parenthesised UNION, an integer division `//` or a column named like an unaliased `ref` leave it undecided), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. A renamed PII output (`email as contact`) is then new. A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name; the quote style and spacing inside a `ref` or `source` call do not count, a quoted SQL name is compared as written), or, for a model compiled under a name its `ref` does not show (an alias, a version or a source `identifier:`), when no relation in the model's code was added or replaced (a table read through an ephemeral model counts the same way); a schema, `source`, `var`, package or `{% set %}` variable a relation is built from, swapped in the model's code, is reported. Where the code cannot decide (such a model only gained a relation, the SQL is a shape the review does not fully parse, two different relations share one table name or one was added or removed beside an unchanged one, or a `ref` gained or lost a package argument), the column is a non-blocking warning that may predate the PR. Renaming a CTE or subquery alias, or turning a CTE into a subquery, is not a change for a computed PII column (`lower(email) as email`). A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported, also after a first branch that selects `*` from a CTE or subquery whose columns are all known, and so is a swap of which table each branch's computation reads (`md5(email)` from `a` and `lower(email)` from `b` reversed). Now reported that was not before: qualifying a raw table name (`from customers` → `from analytics.customers`), and replacing any relation, even an unrelated join, in a model compiled under a name its `ref` does not show. Not reliably detected yet: a computed UNION branch after a `*` over a table, a `ref()`, a CTE that itself selects `*` or a `using`/`natural` join (its columns are matched only by their position among the select items; a new column past the last of them is a non-blocking warning), and any column of a later branch that itself selects `*`. A source schema changed in YAML is a non-blocking warning, for every `source()` in the reviewed models, when the same PR edits a `schema:`, `database:` or `identifier:` key in a source YAML (or deletes one) and also changes a model that reads a source; a PR that edits only the YAML gets no finding, and a `+schema` for sources in `dbt_project.yml`, a schema from `var()` or `env_var()` or set through a YAML anchor or folded value, and changes made outside the PR are not detected. (#1875) ## [0.12.12] - 2026-11-20 diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index ce90179557..1ee86690e7 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -354,17 +354,26 @@ rubric: relation in the model's code was added or replaced (removing a join is fine). When a relation was replaced, even an unrelated join, the compiled name cannot be tied to the unchanged call, so it counts as a different table - and can block. A changed schema, `source`, `var` or package argument in the - code is a different table, and so, under another schema, is a quoted name - whose case changed. When the code cannot decide (such a model only gained a - relation; its SQL is a shape the review does not fully parse and no relation - in it was replaced, where a `config()` or select-list Jinja edit does not - count; or it reads two different relations with one table name, such as two - `source()` calls for `customers`), the column is reported as a non-blocking - warning that may predate the PR. A source whose schema changes only in YAML + and can block; this also holds for a table read through an ephemeral model + (its compiled CTE reads a table the model's code never names). A changed + schema, `source`, `var`, package (`ref('a', 'm')` → `ref('b', 'm')`) or + `{% set %}` variable a relation is built from (`{{ s }}.customers`) is a + different table, and so, under another schema, is a quoted name whose case + changed. When the code cannot decide (such a model only gained a relation; + its SQL is a shape the review does not fully parse and no relation in it was + replaced, where a `config()` or select-list Jinja edit does not count; it + reads two different relations with one table name, such as two `source()` + calls for `customers`, or a second one was added or removed beside an + unchanged one; a `ref` gained or lost a package argument; or another + `{% set %}` variable changed while a relation is built from Jinja), the + column is reported as a non-blocking warning that may predate the PR. + Renaming a CTE or a subquery alias, or turning a CTE into a subquery, is not + a change: a computed PII column (`lower(email) as email`) is compared by how + it is computed from the source columns, not by what its CTEs are called. A source whose schema changes only in YAML is flagged the same way when the same PR edits a `schema:`, `database:` or `identifier:` key in a source YAML (a YAML file that declares `sources:`; a - deleted one counts) and also changes a model that reads a source; the warning + deleted one counts; a schema set through a YAML anchor or a folded + multi-line value is not recognised) and also changes a model that reads a source; the warning then covers every `source()` the reviewed models read, not only the edited source. A PR that edits only the YAML gets no PII finding, and a `+schema` set for sources in `dbt_project.yml`, a schema from `var()` or `env_var()`, @@ -373,11 +382,14 @@ rubric: reported. After a first branch that selects `*` from a CTE or subquery whose columns are all known, each later-branch column is matched to the output column it lands in (`select *, 'web' as channel from c` puts `channel` after - all of `c`'s columns). After a `*` over a table, a `ref()` or a CTE that - itself selects `*`, the columns are unknown: a later-branch column is matched - only by its position among the first branch's select items, which the `*` - throws off, so a computed PII read at or after that `*` is not reliably - detected yet. That + all of `c`'s columns). After a `*` over a table, a `ref()`, a CTE that + itself selects `*`, or a `using`/`natural` join (which outputs each merged + column once), the columns are unknown: a later-branch column is matched only + by its position among the first branch's select items, which the `*` throws + off. A new later-branch column past the last of those items is reported as a + non-blocking warning; one that lands on another item's name, and any column + of a later branch that itself selects `*` (`… union all select * from s`), + is not reliably detected yet. That comparison needs the base version's SQL; when it can't be compiled, a PII column is reported as a non-blocking warning that may predate the PR, unless the base file's own SQL cannot have exposed that output column name: then it @@ -388,7 +400,10 @@ rubric: selected as a whole row such as `select c` or `to_json(c)`, no struct or array expansion such as `unnest(payload)`, no Unicode-escaped name such as `U&"e\006Dail"`; a final `table c` or `from c` selects - every column), and it holds no Jinja but `ref`, `source`, `config`, `this` and + every column), the review reads that base query fully (comments, string + literals and quoted names aside; a CTE column list such as `with x(a, b) as`, + a parenthesised UNION, an integer division `//` or a column named like an + unaliased `ref` leave it undecided), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags (a macro call, a variable or an `{% include %}` could emit any column). The proof is about the output name, so a renamed PII output (`email as contact`) is reported as new. The pattern check also blocks diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index ba6a987826..76fafffc63 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1173,20 +1173,30 @@ function rawBaseCode(oldSql: string | undefined): string | undefined { if (!oldSql) return undefined if (!(oldSql.match(/\{\{[\s\S]*?\}\}/g) ?? []).every((e) => RAW_BASE_PLAIN_EXPR.test(e))) return undefined if (!(oldSql.match(/\{%[\s\S]*?%\}/g) ?? []).every((t) => SILENT_JINJA_TAG.test(t))) return undefined + // Comments out (a Snowflake `//` one only at the start of a line: elsewhere it + // may divide), literals and quoted identifiers kept (one pass, so `--` inside + // `'…'`, `"…"`, `` `…` `` or `$$…$$` is not a comment). + const code = oldSql + .replace( + /\{#[\s\S]*?#\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"|`(?:[^`]|``)*`|\$([A-Za-z_]\w*)?\$[\s\S]*?\$\1\$/g, + (m) => (/^['"`$]/.test(m) ? m : " "), + ) + .replace(/^[ \t]*\/\/[^\n]*/gm, " ") // Only the final query's own select lists can prove a column absent: a CTE's // list does not (`with u as (select id from c) table c`), nor a final query // without one, nor a whole row or a struct expansion (`select c`, `unnest(s)`). - if (!explicitProjection(oldSql)) return undefined + // Read with literals outside Jinja emptied and parentheses in quoted names + // blanked, so `'it\'s'`, `$$x$$` and `"total (usd)"` parse; the base must be + // read fully. + const readable = code.replace(/\{\{[\s\S]*?\}\}|'(?:[^'\\]|''|\\.)*'|\$([A-Za-z_]\w*)?\$[\s\S]*?\$\1\$|"(?:[^"]|"")*"|`(?:[^`]|``)*`/g, (m) => + m.startsWith("{{") ? m : /^['$]/.test(m) ? "''" : m.replace(/[()]/g, "_"), + ) + if (!explicitProjection(readable)) return undefined // A Unicode-escaped name (`U&"e\006Dail"` is `email`) is not searched as written. if (/(? RAW_BASE_STAR.test(i.text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ")))) return undefined - // Comments out, literals and quoted identifiers kept (one pass, so `--` inside - // `'…'`, `"…"`, `` `…` `` or `$$…$$` is not a comment). - return oldSql.replace( - /\{#[\s\S]*?#\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"|`(?:[^`]|``)*`|\$([A-Za-z_]\w*)?\$[\s\S]*?\$\1\$/g, - (m) => (/^['"`$]/.test(m) ? m : " "), - ) + return code } function rawBaseLacks(code: string | undefined, names: string[]): boolean { if (code === undefined || !names.length) return false @@ -1505,7 +1515,12 @@ export async function runReview(input: OrchestrateInput): Promise) => { const unknownAsked = { value: false } - if (isBaseExposedOutput(file, name, basePii, envOf(file, { unknownAsked }))) return "exposed" + if (isBaseExposedOutput(file, name, basePii, envOf(file, { unknownAsked }))) { + // A new UNION branch item whose output name cannot be told may compute this one. + const unmapped = outputs(file, "old").unmapped + const env = envOf(file) + return [...outputs(file, "new").unmapped].every((r) => lineageCovered(r, unmapped, env)) ? "exposed" : "undecided" + } if (!unknownAsked.value) return "new" return isBaseExposedOutput(file, name, basePii, envOf(file, { unknownAsSame: true })) ? "undecided" : "new" } diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 192cc41db2..64b76dea13 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -976,18 +976,22 @@ export interface FinalOutputs { * full text of every CTE or subquery its select reads. Equal signatures on two sides mean the name is computed the same way. */ signatures: Map> /** Per output name, as `signatures` but following columns, not whole bodies, - * one record per item: the item text plus, per CTE or subquery it reads, that - * scope's `lineage` of each column the item names (the scope's whole body - * when a `*` there may pass the column on), paired with the `source.column` - * refs the item reads (`lineageCovered` compares them). Another column or a - * filter added to that CTE leaves it unchanged; unmasking the column there - * (`md5(ssn) as ssn` → `ssn`), or moving `md5(…)` to another table's column, - * does not. */ + * and never naming a CTE, subquery or alias: per computed item, its text plus + * the `lineage` of each CTE or subquery column it reads (through a plain `*`, + * the source column the `*` passes on), paired with the `source.column` refs + * it reads (`lineageCovered` compares them); a column read as is keeps the + * records of what it reads. Another column, a filter or a new name for that + * CTE leaves it unchanged; unmasking the column there (`md5(ssn) as ssn` → + * `ssn`), or moving `md5(…)` to another table's column, does not. */ lineage: Map> /** Per output name, every `source.column` ref its value is computed from, raw * or not, resolved like `raw` (`lower(s.ssn) as email` with `spouses s` → * `email: {spouses.ssn}`; through a CTE, what that CTE's column reads). */ reads: Map> + /** The `lineage` records of later UNION branch items whose output name cannot + * be told (past a `*` whose columns are unknown): such an item may compute + * any output. */ + unmapped: Set } interface ScopeOutputs extends Omit { @@ -1098,10 +1102,13 @@ function relationTexts(sql: string): { byName: Map>; all: Se /** Whether a compiled table's unqualified name may differ by prefix between * base and head as an environment change, judged from the raw model code. A * name the raw code reads (`ref('customers')`, `analytics.customers`) is - * `same` when the same relation texts read it on both sides, `different` when - * they differ, and `unknown` when it is read by two different texts (two - * `source()` calls or package `ref`s for `customers`: which one the compiled - * table is cannot be told). A name it never writes (a model with an `alias`, + * `same` when the same single relation text reads it on both sides, + * `different` only when every text for it was replaced (none shared, a + * package argument aside: `ref('core', 'customers')` may be what + * `ref('customers')` resolves to), and `unknown` otherwise: two texts for it + * (two `source()` calls for `customers`: which one the compiled table is + * cannot be told), one added or removed beside an unchanged one, or a side + * that does not read it. A name it never writes (a model with an `alias`, * a version, a source `identifier:`: `ref('customers', v=2)` compiles to * `customers_v2`) cannot be tied to one call. Only relations are evidence * (the FROM/JOIN texts, or, when the parser lists none, the query's Jinja @@ -1119,14 +1126,35 @@ export function rawRelationsMatch( if (!oldSql || !newSql) return () => "different" const base = relationTexts(oldSql) const head = relationTexts(newSql) - const sameSet = (a: Set | undefined, b: Set | undefined) => - !!a && !!b && a.size === b.size && [...a].every((t) => b.has(t)) + // A package argument (`ref('core', 'm')`) may name the model an unqualified + // `ref('m')` resolves to, so the two only overlap (two packages do not). + const unpackaged = (t: string) => t.replace(/^\{\{ref\('[^']*',('[^']*'.*)\)\}\}$/, "{{ref($1)}}") + const overlaps = (a: Set, b: Set) => [...a].some((t) => [...b].some((u) => t === u || unpackaged(t) === u || t === unpackaged(u))) const unchangedMatch = (texts: Set): RelationMatch => sourcesEdited && [...texts].some((t) => t.startsWith("{{source(")) ? "unknown" : "same" const evidence = (side: typeof base, sql: string) => side.all.size || side.complete ? side.all : new Set((sql.match(/\{\{[\s\S]*?\}\}/g) ?? []).map(normalizeRelation).filter((t) => !t.startsWith("{{config("))) + // A relation built from a `{% set %}` variable (`{{ s }}.customers`) reads + // the same text whatever the variable holds: a changed variable it names + // makes it a swap, any other changed `set` leaves its Jinja undecided. + const sets = (sql: string) => + new Map( + [...sql.matchAll(/\{%-?\s*set\s+([A-Za-z_]\w*)\s*(?:=([\s\S]*?)-?%\}|-?%\}([\s\S]*?)\{%-?\s*endset)/g)].map((m) => [ + m[1], + (m[2] ?? m[3]).replace(/\s+/g, ""), + ]), + ) + const setsWas = sets(oldSql) + const setsNow = sets(newSql) + const changedSets = [...new Set([...setsWas.keys(), ...setsNow.keys()])].filter((n) => setsWas.get(n) !== setsNow.get(n)) + const setJinja = (texts: Iterable): RelationMatch | undefined => { + if (!changedSets.length) return undefined + const exprs = [...texts].flatMap((t) => [...t.matchAll(/\{\{([\s\S]*?)\}\}/g)].map((m) => m[1])).filter((e) => !/^(?:ref|source)\(/.test(e)) + if (exprs.some((e) => changedSets.some((n) => new RegExp(`(? !now.has(t)) @@ -1134,12 +1162,19 @@ export function rawRelationsMatch( let untied: RelationMatch = "unknown" if (removed && added) untied = "different" else if (base.complete && head.complete && !added) untied = unchangedMatch(base.all) + const untiedSet = setJinja([...base.all, ...head.all]) return (table) => { const a = base.byName.get(table) const b = head.byName.get(table) - if (!a && !b) return untied - if (!sameSet(a, b)) return "different" - return a!.size > 1 ? "unknown" : unchangedMatch(a!) + if (!a && !b) return untiedSet && untied !== "different" ? untiedSet : untied + const set = setJinja([...(a ?? []), ...(b ?? [])]) + if (set === "different") return set + // Only a replacement (every text for the name changed) is a swap. + if (!a || !b || overlaps(a, b)) { + const same = !!a && !!b && a.size === b.size && [...a].every((t) => b.has(t)) + return same && a!.size === 1 && !set ? unchangedMatch(a!) : "unknown" + } + return "different" } } @@ -1315,12 +1350,14 @@ export function finalOutputs(sql: string): FinalOutputs { // An item's text for signatures: lowercased outside literals, with each // FROM/JOIN alias replaced by the source it names (a table by its unqualified name, // without database/schema, which `refCovered` compares environment-aware via - // `reads`; a CTE or subquery by its scope), so renaming an alias - // (`md5(c.ssn)` → `md5(cu.ssn)` on one table) keeps the signature. - const signatureText = (item: SelectItem, scope: string) => { + // `reads`; a CTE or subquery by its scope, or by nothing for `lineage`, which + // follows the scope's columns instead), so renaming an alias (`md5(c.ssn)` → + // `md5(cu.ssn)` on one table) keeps the signature. + const signatureText = (item: SelectItem, scope: string, scopeNames = true) => { const named = new Map() for (const src of sources.get(`${scope}#${item.branch}`) ?? []) - if (src.alias && src.alias !== src.name) named.set(src.alias, byScope.has(src.name) ? src.name : splitTable(src.name).name) + if (!scopeNames && byScope.has(src.name)) named.set(src.alias ?? src.name, "") + else if (src.alias && src.alias !== src.name) named.set(src.alias, byScope.has(src.name) ? src.name : splitTable(src.name).name) const text = lowerOutsideLiterals(item.exact) if (!named.size) return text return text.replace(/'(?:[^']|'')*'|[^']+/g, (part) => @@ -1332,6 +1369,30 @@ export function finalOutputs(sql: string): FinalOutputs { }), ) } + // A `lineage` record: a digest of the computation (its text, the records of + // each CTE or subquery column it reads, the unqualified table of each source + // column it reads, which an environment change keeps), then its full refs. A + // digest, so a column computed from several upstream columns at every level + // of a CTE chain does not grow its key exponentially. A column read as is has + // the empty computation over its source column. + const lineageRecord = (text: string, upstream: string[], reads: Set) => { + const known = [...reads].filter((r) => !r.startsWith("?")).sort() + const tables = known.map((r) => { + const split = splitRef(r) + return `${split.tables.map((t) => splitTable(t).name).join("|")}.${split.column}` + }) + const digest = createHash("sha256").update(`${text}\u0001${upstream.join("\u0002")}\u0001${tables.join("\u0002")}`).digest("base64") + return `${digest}${LINEAGE_REFS}${known.join("\u0007")}` + } + const lineageDigest = (record: string) => record.split(LINEAGE_REFS)[0] + // The records of `column` as the CTE or subquery `src` outputs it: its own, + // or, for a column one of its plain `*` items passes on, the source column + // that `*` reads, as if named. + const passedOn = (src: Source, column: string, seen: Set): string[] => { + const out = resolve(src.name, seen) + if (out.names.has(column)) return [...(out.lineage.get(column) ?? [])] + return out.stars.map((st) => lineageRecord("", [], resolveRef(src.name, st.branch, st.qualifier, column, seen).reads)) + } const resolve = (scope: string, seen: Set): ScopeOutputs => { const cached = memo.get(scope) if (cached) return cached @@ -1342,6 +1403,7 @@ export function finalOutputs(sql: string): FinalOutputs { const lineage = new Map>() const reads = new Map>() const stars: ScopeOutputs["stars"] = [] + const unmapped = new Set() const addTo = (map: Map>, name: string, values: Iterable) => { const set = map.get(name) ?? new Set() for (const v of values) set.add(v) @@ -1351,9 +1413,11 @@ export function finalOutputs(sql: string): FinalOutputs { const firstNames = new Map(scopeItems.filter((i) => i.branch === 0).map((i) => [i.position, i.name])) // The columns an item outputs, in order: one; for a `*` over CTEs or // subqueries whose columns are all known, theirs; else unknown (a `*` over - // a table, `* exclude (…)`, `unnest(…)`). + // a table, `* exclude (…)`, `unnest(…)`, or over a `using`/`natural` join, + // which outputs each merged column once). const columnsOf = (item: SelectItem): Array | undefined => { if (!STAR.test(item.text)) return STAR_PREFIX.test(item.text) || UNNAMED_COLUMNS.test(item.text) ? undefined : [item.name] + if (merged.has(`${scope}#${item.branch}`)) return undefined const q = /([^.]+)\.\*$/.exec(item.text)?.[1] const srcs = (sources.get(`${scope}#${item.branch}`) ?? []).filter((src) => !q || src.alias === unquote(q) || src.name === unquote(q)) const parts = srcs.map((src) => (isDerived(src, scope, seen) ? resolve(src.name, inner).layout : undefined)) @@ -1389,8 +1453,9 @@ export function finalOutputs(sql: string): FinalOutputs { for (const n of out.names) names.add(n) for (const [n, cols] of out.raw) addTo(raw, n, cols) for (const [n, sigs] of out.signatures) addTo(signatures, n, [...sigs].map((sig) => `*${sig}`)) - for (const [n, sigs] of out.lineage) addTo(lineage, n, [...sigs].map((sig) => `*${src.name}:${sig}`)) + for (const [n, sigs] of out.lineage) addTo(lineage, n, sigs) for (const [n, cols] of out.reads) addTo(reads, n, cols) + for (const r of out.unmapped) unmapped.add(r) } continue } @@ -1403,29 +1468,16 @@ export function finalOutputs(sql: string): FinalOutputs { const at = ordinal.get(item) name = at !== undefined && at < firstColumns.length ? firstColumns[at] : firstNames.get(item.position) } - if (!name) continue - names.add(name) + if (!name && item.branch === 0) continue const text = signatureText(item, scope) // Each read follows only the CTE or subquery it comes from: a qualifier // names one source; an unqualified read may come from any that has it. const srcs = sources.get(`${scope}#${item.branch}`) ?? [] - const itemReads = item.rawColumn ? [{ qualifier: item.rawQualifier, column: item.rawColumn }] : (item.reads ?? []) - const upstream = itemReads - .flatMap(({ qualifier, column }) => { - const named = qualifier ? sourceNamed(srcs, qualifier) : undefined - const from = named ? [named].filter((src) => derived.includes(src)) : derived - return from - .map((src) => ({ src, out: resolve(src.name, inner) })) - .filter(({ out }) => named || out.names.has(column) || out.stars.length) - .map(({ src, out }) => { - let of = "" - if (out.names.has(column)) - of = [...(out.lineage.get(column) ?? [])].map((sig) => sig.split(LINEAGE_REFS)[0]).sort().join("\u0005") - else if (out.stars.length) of = out.body - return `${src.name}.${column}:${of}` - }) - }) - .sort() + const fromScopes = (qualifier: string | undefined, column: string) => { + const named = qualifier ? sourceNamed(srcs, qualifier) : undefined + const from = named ? [named].filter((src) => derived.includes(src)) : derived + return from.filter((src) => named || resolve(src.name, inner).names.has(column) || resolve(src.name, inner).stars.length) + } const refs = item.rawColumn ? resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen) : { @@ -1435,31 +1487,36 @@ export function finalOutputs(sql: string): FinalOutputs { // An expression whose column reads parse to nothing is not known to read // nothing: it is never "already exposed" by its reads (the signature may // still match). Only a constant reads nothing. - if (!item.rawColumn && !item.reads?.length && !item.constant) refs.reads = unresolved(name) - // The computation paired with what it reads: its digest holds each read's - // unqualified table name (an environment change keeps it), the record its - // full refs. A digest, so a column computed from several upstream columns - // at every level of a CTE chain does not grow its key exponentially. - const known = [...refs.reads].filter((r) => !r.startsWith("?")).sort() - const tables = known.map((r) => { - const split = splitRef(r) - return `${split.tables.map((t) => splitTable(t).name).join("|")}.${split.column}` - }) - const digest = createHash("sha256") - .update(`${text}\u0001${upstream.join("\u0002")}\u0001${tables.join("\u0002")}`) - .digest("base64") + if (!item.rawColumn && !item.reads?.length && !item.constant) refs.reads = unresolved(name ?? "") + // A column read as is keeps the records of the column it reads; a computed + // one gets one record over the records of each column it reads. Neither + // depends on what a CTE, subquery or alias is called. + let records: string[] = [] + if (item.rawColumn) records = fromScopes(item.rawQualifier, item.rawColumn).flatMap((src) => passedOn(src, item.rawColumn!, inner)) + else { + const upstream = (item.reads ?? []).flatMap(({ qualifier, column }) => + fromScopes(qualifier, column).map((src) => `${column}:${passedOn(src, column, inner).map(lineageDigest).sort().join("\u0005")}`), + ) + records = [lineageRecord(signatureText(item, scope, false), upstream.sort(), refs.reads)] + } + if (!records.length) records = [lineageRecord("", [], refs.reads)] + if (!name) { + for (const r of records) unmapped.add(r) + continue + } + names.add(name) addTo(signatures, name, [`${text}\u0001${bodies.join("\u0002")}`]) - addTo(lineage, name, [`${digest}${LINEAGE_REFS}${known.join("\u0007")}`]) + addTo(lineage, name, records) addTo(raw, name, refs.raw) addTo(reads, name, refs.reads) } for (const [n, cols] of raw) if (!cols.size) raw.delete(n) const body = [scopeItems.map((i) => signatureText(i, scope)).join(","), ...[...readBodies].sort()].join("\u0003") - const result = { raw, names, signatures, lineage, reads, stars, body, layout } + const result = { raw, names, signatures, lineage, reads, unmapped, stars, body, layout } memo.set(scope, result) return result } - const { raw, names, signatures, lineage, reads, stars } = resolve(ROOT_SCOPE, new Set()) + const { raw, names, signatures, lineage, reads, unmapped, stars } = resolve(ROOT_SCOPE, new Set()) // The raw refs a `*` passes `col` through as. Unlike an unqualified column // read over several sources (one combined ref: it comes from exactly one of // them), a `*` passes every source's columns through, so each source is @@ -1509,7 +1566,7 @@ export function finalOutputs(sql: string): FinalOutputs { union(stars.map((st) => starRefs(ROOT_SCOPE, st.branch, st.qualifier, column, new Set()))) const prefixes = new Set() for (const list of sources.values()) for (const src of list) if (!byScope.has(src.name)) prefixes.add(splitTable(src.name).prefix) - return { raw, names, signatures, lineage, reads, passthrough: stars.length > 0, starRaw, prefixes } + return { raw, names, signatures, lineage, reads, unmapped, passthrough: stars.length > 0, starRaw, prefixes } } /** A Jinja statement tag that emits no text of its own: control flow and `set`. */ diff --git a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts index e2c106c14a..358ad22d8c 100644 --- a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts +++ b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts @@ -575,7 +575,8 @@ describe("the same table across environments when the compiled name is tied to n // A Jinja relation that is not a `ref`/`source` leaves the parse incomplete. const joined = (col: string) => `select c.id, ${col}\nfrom {{ ref('customers', v=2) }} c\njoin {{ lookup_table() }} l on l.id = c.id` expect(rawRelationsMatch(joined("c.ssn"), joined("{{ mask('c.ssn') }} as ssn"))("customers_v2")).toBe("unknown") - // A whole-query macro whose arguments changed is still a swap. + // A whole-query macro: a changed `config()` beside it is no evidence, changed arguments are a swap. + expect(rawRelationsMatch("{{ config(materialized='view') }}\n{{ customer_rows('masked') }}", "{{ config(materialized='table') }}\n{{ customer_rows('masked') }}")("customers")).toBe("unknown") expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('raw') }}")("customers")).toBe("different") }) @@ -623,7 +624,8 @@ describe("a source YAML edit that may move a `source()`", () => { test("a `schema:` edit outside a source YAML does not", async () => { const files = { - project: yml("dbt_project.yml", "- +schema: masked\n+ +schema: raw\n- schema: a\n+ schema: b\n", { old: "name: p\n", new: "name: p\n" }), + // `dbt_project.yml`'s `sources:` block holds configs, not sources. + project: yml("dbt_project.yml", "- +schema: masked\n+ +schema: raw\n- schema: a\n+ schema: b\n", { old: "name: p\nsources:\n p:\n +schema: a\n", new: "name: p\nsources:\n p:\n +schema: b\n" }), ci: yml(".github/workflows/ci.yml", "- schema: dbt_prod\n+ schema: dbt_ci\n", { old: "jobs:\n", new: "jobs:\n" }), schemaYml: yml("models/marts/_models.yml", "- schema: a\n+ schema: b\n", { old: "version: 2\nmodels:\n", new: "version: 2\nmodels:\n" }), } @@ -654,3 +656,103 @@ describe("absence proof from a raw base", () => { ) }) }) + +describe("a raw base read through comments and literals", () => { + const ref = "{{ ref('stg_customers') }}" + const go = (b: string, h: string, reviewers: string[]) => + run({ base: b, head: h, diff: "+ ssn\n", reviewers, runner: piiRunner(["ssn"], classifyAll(/ssn/)), compiled: (side) => (side === "new" ? h.replace(ref, "analytics.stg_customers") : undefined) }) + const shape = (prefix: string, item: string) => [`${prefix}select customer_id,\n ${item}\nfrom ${ref}`, `${prefix}select customer_id,\n ${item},\n ssn\nfrom ${ref}`] + + test("a commented-out line, a block comment with Jinja, a quoted literal or name: a column the base lacks blocks", async () => { + const cases = { + "commented-out config": shape("-- {{ config(materialized='table') }}\n", "region"), + "block comment with a ref": shape("/* depends on {{ ref('x') }} */\n", "region"), + "Snowflake `//` comment line": shape("// legacy\n", "region"), + "dollar-quoted literal": shape("", "$$x$$ as tag"), + "backslash-escaped quote": shape("", "'it\\'s' as tag"), + "parentheses in a quoted name": shape("", '"total (usd)"'), + } + for (const [label, [b, h]] of Object.entries(cases)) + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []]) expectBlocks(await go(b, h, reviewers), { label, reviewers }) + }) + + test("a base the parser does not read fully stays undecided", async () => { + const cases = { + "CTE column list": [`with x(customer_id, region) as (select customer_id, region from ${ref})\nselect customer_id,\n region\nfrom x`, `with x(customer_id, region) as (select customer_id, region from ${ref})\nselect customer_id,\n region,\n ssn\nfrom x`], + "integer division `//`": shape("", "age // 10 as decade"), + "parenthesised union": [`(select customer_id,\n region\nfrom ${ref})\nunion all\n(select customer_id, region from {{ ref('leads') }})`, `(select customer_id,\n region,\n ssn\nfrom ${ref})\nunion all\n(select customer_id, region, ssn from {{ ref('leads') }})`], + // `region` may be the whole row of the model `region`. + "column named like its unaliased ref": [`select customer_id,\n region\nfrom {{ ref('region') }}`, `select customer_id,\n region,\n ssn\nfrom {{ ref('region') }}`], + } + for (const [label, [b, h]] of Object.entries(cases)) + for (const reviewers of [["pii_exposure"], []]) expectUndecided(await go(b, h, reviewers), { label, reviewers }) + }) +}) + +describe("relation texts: only a replacement is a swap", () => { + const STG = "{{ ref('stg_customers') }}" + const one = `select c.customer_id, c.email\nfrom ${STG} c` + const two = `${one}\nleft join {{ source('crm', 'stg_customers') }} s on s.customer_id = c.customer_id` + + test("adding or removing a second relation with the same table name is undecided", () => { + expect(rawRelationsMatch(one, two)("stg_customers")).toBe("unknown") + expect(rawRelationsMatch(two, one)("stg_customers")).toBe("unknown") + // Every text replaced is a swap. + expect(rawRelationsMatch(one, `select c.customer_id, c.email\nfrom {{ source('crm', 'stg_customers') }} c`)("stg_customers")).toBe("different") + }) + + test("a package argument on a ref is undecided, a version change is a swap", () => { + const pkg = one.replace(STG, "{{ ref('core', 'stg_customers') }}") + expect(rawRelationsMatch(one, pkg)("stg_customers")).toBe("unknown") + expect(rawRelationsMatch(pkg, one)("stg_customers")).toBe("unknown") + expect(rawRelationsMatch(pkg, pkg.replace("'core'", "'raw_pkg'"))("stg_customers")).toBe("different") + expect(rawRelationsMatch("select id from {{ ref('customers', v=1) }}", "select id from {{ ref('customers', v=2) }}")("customers")).toBe("different") + }) + + test("a relation built from a changed `{% set %}` variable is a swap", async () => { + const sql = (v: string) => `{% set s = '${v}' %}\nselect customer_id,\n ssn\nfrom {{ s }}.customers` + expect(rawRelationsMatch(sql("masked"), sql("raw"))("customers")).toBe("different") + expect(rawRelationsMatch(sql("masked"), sql("masked"))("customers")).toBe("same") + // Another changed variable leaves the relation's Jinja undecided. + const other = (v: string) => `{% set t = '${v}' %}\n${sql("masked")}` + expect(rawRelationsMatch(other("a"), other("b"))("customers")).toBe("unknown") + const compiled = (side: "old" | "new") => `select customer_id,\n ssn\nfrom analytics.${side === "old" ? "masked" : "raw"}.customers` + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks(await run({ base: sql("masked"), head: sql("raw"), diff: "-{% set s = 'masked' %}\n+{% set s = 'raw' %}\n", reviewers, runner: piiRunner(["ssn"]), compiled }), reviewers) + }) +}) + +describe("a first-branch `*` over a `using` or `natural` join", () => { + const ctes = "with a as (select customer_id, region from x), b as (select customer_id, email from y)\n" + const go = (join: string, branch: string, reviewers: string[]) => { + const b = `${ctes}select * from a ${join}\nunion all\nselect ${branch.replace("lower(ssn)", "email")} from leads` + const h = `${ctes}select * from a ${join}\nunion all\nselect ${branch} from secrets` + return run({ base: b, head: h, diff: `-select ${branch.replace("lower(ssn)", "email")} from leads\n+select ${branch} from secrets\n`, reviewers, runner: piiRunner(["email"]) }) + } + + test("outputs a merged column once, so a later computed branch is undecided", async () => { + for (const join of ["join b using (customer_id)", "natural join b"]) + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) expectUndecided(await go(join, "customer_id, region, lower(ssn)", reviewers), { join, reviewers }) + }) + + test("an `on` join keeps both columns and still blocks", async () => { + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks(await go("join b on a.customer_id = b.customer_id", "customer_id, region, customer_id, lower(ssn)", reviewers), reviewers) + }) +}) + +describe("an ephemeral upstream model (a known false block)", () => { + test("replacing an unrelated ref beside it still blocks: the compiled table is tied to no raw call", async () => { + // `ref('eph_customers')` compiles to a `__dbt__cte__` CTE reading `raw_customers`, a + // name the raw code never writes; like an aliased model, it cannot be told from a swap. + const raw = (orders: string) => `select\n c.customer_id,\n c.ssn,\n o.order_total\nfrom {{ ref('eph_customers') }} c\njoin {{ ref('${orders}') }} o using (customer_id)` + const compiled = (side: "old" | "new") => { + const env = side === "old" ? "dbt_prod" : "dbt_ci_42" + return `with __dbt__cte__eph_customers as (\n select * from analytics.${env}.raw_customers\n)\n${raw(side === "old" ? "stg_orders" : "int_orders").replace("{{ ref('eph_customers') }}", "__dbt__cte__eph_customers").replace(/\{\{ ref\('(\w+)'\) \}\}/, `analytics.${env}.$1`)}` + } + expectBlocks( + await run({ base: raw("stg_orders"), head: raw("int_orders"), diff: "-join {{ ref('stg_orders') }} o using (customer_id)\n+join {{ ref('int_orders') }} o using (customer_id)\n", reviewers: ["pii_exposure"], runner: piiRunner(["ssn"]), compiled }), + "ephemeral", + ) + }) +}) diff --git a/packages/opencode/test/altimate/review-pii-no-change-edits.test.ts b/packages/opencode/test/altimate/review-pii-no-change-edits.test.ts index 88e96f49cd..ff85dbd760 100644 --- a/packages/opencode/test/altimate/review-pii-no-change-edits.test.ts +++ b/packages/opencode/test/altimate/review-pii-no-change-edits.test.ts @@ -46,7 +46,7 @@ const compile = (raw: string, env: string) => raw .replace(/\{\{-?\s*config\([^}]*\)\s*-?\}\}\n?/g, "") .replace(/\{\{\s*ref\(\s*(['"])(\w+)\1\s*,\s*v(?:ersion)?\s*=\s*(\d+)\s*\)\s*\}\}/g, (_m, _q, m, v) => `analytics.${env}.${m}_v${v}`) - .replace(/\{\{\s*ref\(\s*(['"])(\w+)\1\s*\)\s*\}\}/g, (_m, _q, m) => `analytics.${env}.${m}`) + .replace(/\{\{\s*ref\(\s*(?:(['"])\w+\1\s*,\s*)?(['"])(\w+)\2\s*\)\s*\}\}/g, (_m, _p, _q, m) => `analytics.${env}.${m}`) .replace(/\{\{\s*source\(\s*(['"])(\w+)\1\s*,\s*(['"])(\w+)\3\s*\)\s*\}\}/g, (_m, _q, s, _q2, t) => `analytics.${env}_${s}.${t}`) const STG = "{{ ref('stg_customers') }}" @@ -63,6 +63,14 @@ const BASES: Record = { passthrough: `select *\nfrom ${STG}`, masked: `select customer_id, md5(ssn) as ssn\nfrom ${STG}`, config: `{{ config(materialized='table') }}\nselect customer_id, email\nfrom ${STG}`, + // A PII column COMPUTED, in the shapes dbt projects use every day. + stagingRenamed: `with source as (\n select * from {{ source('jaffle', 'customers') }}\n),\nrenamed as (\n select\n id as customer_id,\n lower(email) as email,\n first_name\n from source\n)\nselect * from renamed`, + trimCte: `with customers as (\n select customer_id, email, order_total from ${STG}\n)\nselect customer_id, trim(email) as email, order_total from customers`, + coalesceCte: `with c as (\n select * from ${STG}\n)\nselect customer_id, coalesce(email, 'n/a') as email from c`, + lowerSubquery: `select customer_id, lower(email) as email from (\n select customer_id, email from ${STG}\n) customers`, + computedUnionStar: `with leads as (\n select * from {{ ref('stg_leads') }}\n)\nselect customer_id, email from ${STG}\nunion all\nselect customer_id, lower(email) as email from leads`, + computedUnionExplicit: `with leads as (\n select customer_id, email from {{ ref('stg_leads') }}\n)\nselect customer_id, email from ${STG}\nunion all\nselect customer_id, trim(email) as email from leads`, + sameNamedJoin: `select c.customer_id, lower(c.email) as email, s.signup_channel\nfrom ${STG} c\nleft join {{ source('crm', 'stg_customers') }} s on s.customer_id = c.customer_id`, twoCtes: `with cust as (\n select customer_id, email from ${STG}\n),\nord as (\n select customer_id, count(*) as n from {{ ref('stg_orders') }} group by 1\n)\nselect cust.customer_id, cust.email, ord.n\nfrom cust\nleft join ord on ord.customer_id = cust.customer_id`, } @@ -83,19 +91,54 @@ const SPECIFIC: Record> = { "identical branch over the CTE's table": `${BASES.starCteUnion}\nunion all\nselect customer_id, email from ${STG}`, }, config: { "change materialized": BASES.config.replace("'table'", "'view'") }, + stagingRenamed: { + "rename the final CTE": BASES.stagingRenamed.replace(/\brenamed\b/g, "final"), + "rename the import CTE": BASES.stagingRenamed.replace("source as (", "src as (").replace("from source\n", "from src\n"), + }, + trimCte: { + "rename the CTE": BASES.trimCte.replace(/\bcustomers\b/g, "src"), + "CTE to a subquery": `select customer_id, trim(email) as email, order_total from (\n select customer_id, email, order_total from ${STG}\n) customers`, + }, + coalesceCte: { "rename the CTE": BASES.coalesceCte.replace(/\bc\b/g, "cust") }, + lowerSubquery: { + "rename the subquery alias": BASES.lowerSubquery.replace(") customers", ") c"), + "subquery to a CTE": `with customers as (\n select customer_id, email from ${STG}\n)\nselect customer_id, lower(email) as email from customers`, + }, + computedUnionStar: { + "rename the CTE": BASES.computedUnionStar.replace(/\bleads\b/g, "lead_rows"), + "non-PII column in the `*` CTE": BASES.computedUnionStar.replace("select * from", "select *, current_date as loaded_at from"), + "`*` CTE to explicit columns": BASES.computedUnionStar.replace("select * from {{ ref('stg_leads') }}", "select customer_id, email from {{ ref('stg_leads') }}"), + "qualified `*` in the CTE": BASES.computedUnionStar.replace("select * from {{ ref('stg_leads') }}", "select l.* from {{ ref('stg_leads') }} l"), + }, + computedUnionExplicit: { + "rename the CTE": BASES.computedUnionExplicit.replace(/\bleads\b/g, "lead_rows"), + "CTE to a subquery": `select customer_id, email from ${STG}\nunion all\nselect customer_id, trim(email) as email from (\n select customer_id, email from {{ ref('stg_leads') }}\n) leads`, + }, + sameNamedJoin: { + "remove the same-named relation": `select c.customer_id, lower(c.email) as email\nfrom ${STG} c`, + }, + single: { + "add a same-named relation": `select c.customer_id, c.email, c.ssn, s.signup_channel\nfrom ${STG} c\nleft join {{ source('crm', 'stg_customers') }} s on s.customer_id = c.customer_id`, + "package argument on the ref": BASES.single.replace(STG, "{{ ref('core', 'stg_customers') }}"), + }, } // The last select of the model to the end: its final query or last branch. const lastSelect = (sql: string) => sql.slice(sql.toLowerCase().lastIndexOf("select ")) +// The last select is a subquery's (it closes more parentheses than it opens), not the final query's. +const lastSelectNested = (sql: string) => { + const t = lastSelect(sql) + return (t.match(/\)/g) ?? []).length > (t.match(/\(/g) ?? []).length +} const GENERIC: Record string | undefined> = { reformat: (sql) => sql.replace(/,\s*/g, ",\n ").replace(/\s+(from|join|where|union all)\s+/gi, "\n $1 "), "quote style in ref": (sql) => (sql.includes("ref('") ? sql.replace(/ref\('(\w+)'/g, 'ref("$1"') : undefined), "add a non-PII column": (sql) => { - if (/union|\*/i.test(sql)) return undefined + if (/union|\*/i.test(sql) || lastSelectNested(sql)) return undefined const at = sql.toLowerCase().lastIndexOf("select ") + "select ".length return `${sql.slice(0, at)}1 as one, ${sql.slice(at)}` }, - "identical UNION branch": (sql) => `${sql}\nunion all\n${lastSelect(sql)}`, + "identical UNION branch": (sql) => (lastSelectNested(sql) ? undefined : `${sql}\nunion all\n${lastSelect(sql)}`), "add a config block": (sql) => (sql.includes("config(") ? undefined : `{{ config(materialized='view') }}\n${sql}`), "add comments": (sql) => `-- reviewed\n${sql}\n/* end of model */`, } @@ -109,6 +152,11 @@ const CONTROLS: Record = { "masked column made raw": [BASES.masked, `select customer_id, ssn\nfrom ${STG}`], "masked source swapped for raw": [BASES.maskedSource, BASES.maskedSource.replace("'masked'", "'raw'")], "computed branch after a CTE `*`": [BASES.starCteUnion, `${BASES.starCteUnion}\nunion all\nselect customer_id, lower(ssn) as email\nfrom {{ ref('secrets') }}`], + "computed name now reads another column": [BASES.stagingRenamed, BASES.stagingRenamed.replace(/\brenamed\b/g, "final").replace("lower(email)", "lower(ssn)")], + "computed branch's CTE unmasked": [ + BASES.computedUnionExplicit.replace("select customer_id, email from {{ ref('stg_leads') }}", "select customer_id, md5(email) as email from {{ ref('stg_leads') }}"), + BASES.computedUnionExplicit.replace(/\bleads\b/g, "lead_rows"), + ], "computed branch after explicit columns": [BASES.union, `${BASES.union}\nunion all\nselect customer_id, lower(ssn) as email\nfrom {{ ref('secrets') }}`], } @@ -120,7 +168,9 @@ const lineDiff = (a: string, b: string) => { const neu = new Set(b.split("\n")) return [...a.split("\n").filter((l) => !neu.has(l)).map((l) => `-${l}`), ...b.split("\n").filter((l) => !old.has(l)).map((l) => `+${l}`)].join("\n") + "\n" } -const review = async (base: string, head: string, reviewers: string[], compiledBase: boolean, classify: boolean) => { +// The compiled base: in prod while the head is in a CI schema, in the head's schema, or none. +type CompiledBase = "prod" | "same" | false +const review = async (base: string, head: string, reviewers: string[], compiledBase: CompiledBase, classify: boolean) => { const env = await runReview({ changedFiles: [{ path: P, status: "modified", diff: lineDiff(base, head) } as ChangedFile], config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, @@ -129,7 +179,7 @@ const review = async (base: string, head: string, reviewers: string[], compiledB runner: runnerFor(classify), getContent: async (_f: string, side: "old" | "new") => (side === "new" ? head : base), getCompiled: async (_f: string, side: "old" | "new") => - side === "new" ? compile(head, "dbt_ci_42") : compiledBase ? compile(base, "dbt_prod") : undefined, + side === "new" ? compile(head, "dbt_ci_42") : compiledBase ? compile(base, compiledBase === "prod" ? "dbt_prod" : "dbt_ci_42") : undefined, }) const pii = env.findings.filter((f) => f.category === "pii_exposure") return { @@ -152,7 +202,7 @@ describe("an edit that cannot change which PII is exposed", () => { const failures: unknown[] = [] for (const c of cases) for (const reviewers of LANES) - for (const compiledBase of [true, false]) + for (const compiledBase of ["prod", "same", false] as const) for (const classify of [false, true]) { const r = await review(BASES[c.base], c.head, reviewers, compiledBase, classify) if (r.blocks) @@ -167,8 +217,10 @@ describe("an edit that cannot change which PII is exposed", () => { for (const reviewers of LANES.slice(0, 2)) for (const classify of [false, true]) { // Proven new with a compiled base: blocks. - const compiled = await review(base, head, reviewers, true, classify) - if (!compiled.blocks) failures.push({ label, lanes: reviewers, compiledBase: true, classify, head, findings: compiled.pii }) + for (const compiledBase of ["prod", "same"] as const) { + const compiled = await review(base, head, reviewers, compiledBase, classify) + if (!compiled.blocks) failures.push({ label, lanes: reviewers, compiledBase, classify, head, findings: compiled.pii }) + } // Without one: at least reported. const raw = await review(base, head, reviewers, false, classify) if (!raw.pii.length) failures.push({ label, lanes: reviewers, compiledBase: false, classify, head, findings: raw.pii }) From 58e92d9b69babf908634c0207b1d0038c2c9c37c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 2 Dec 2026 17:26:33 +0530 Subject: [PATCH 7/7] fix(review): a computation is compared by what it reads, not how it is written The signature check is gone; lineage alone decides, and it ignores qualifier spelling, CTE names, `*` wrappers and schema order. An undecided warning no longer drops a pattern finding. A harmless `{% set %}` edit is not a swap. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- docs/docs/usage/dbt-pr-review.md | 57 ++-- .../src/altimate/review/orchestrate.ts | 85 ++++-- .../src/altimate/review/rule-catalog.ts | 287 ++++++++++-------- .../altimate/review-pii-new-exposure.test.ts | 223 +++++++++++++- .../review-pii-no-change-edits.test.ts | 107 ++++++- 6 files changed, 555 insertions(+), 206 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 60594d545e..22b8c27944 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`altimate review` reads `.altimate/review.yml` from the base branch.** A PR can no longer relax the policy it is reviewed under; settings it changes are listed in the comment and take effect after merge. The `--mode` and `--severity` flags (the action's `mode` and `severity_threshold`) can only tighten a base policy, and `allowForceTier: false` rejects `--force-tier`. (#1722) - **`altimate review` flags PII only for columns the change newly exposes**, not for PII columns the base already surfaced. Without a compiled base, a PII column is a non-blocking warning that may predate the PR, unless the base SQL cannot have exposed it (see the next entry). (#1721) -- **`altimate review` reports three PII exposures it used to call pre-existing.** Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, its final query names every column in its own select list (no `*`, `COLUMNS(…)`, whole-row reference, struct expansion or Unicode-escaped name such as `U&"…"`), the review reads that query fully (a CTE column list, a parenthesised UNION, an integer division `//` or a column named like an unaliased `ref` leave it undecided), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. A renamed PII output (`email as contact`) is then new. A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name; the quote style and spacing inside a `ref` or `source` call do not count, a quoted SQL name is compared as written), or, for a model compiled under a name its `ref` does not show (an alias, a version or a source `identifier:`), when no relation in the model's code was added or replaced (a table read through an ephemeral model counts the same way); a schema, `source`, `var`, package or `{% set %}` variable a relation is built from, swapped in the model's code, is reported. Where the code cannot decide (such a model only gained a relation, the SQL is a shape the review does not fully parse, two different relations share one table name or one was added or removed beside an unchanged one, or a `ref` gained or lost a package argument), the column is a non-blocking warning that may predate the PR. Renaming a CTE or subquery alias, or turning a CTE into a subquery, is not a change for a computed PII column (`lower(email) as email`). A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported, also after a first branch that selects `*` from a CTE or subquery whose columns are all known, and so is a swap of which table each branch's computation reads (`md5(email)` from `a` and `lower(email)` from `b` reversed). Now reported that was not before: qualifying a raw table name (`from customers` → `from analytics.customers`), and replacing any relation, even an unrelated join, in a model compiled under a name its `ref` does not show. Not reliably detected yet: a computed UNION branch after a `*` over a table, a `ref()`, a CTE that itself selects `*` or a `using`/`natural` join (its columns are matched only by their position among the select items; a new column past the last of them is a non-blocking warning), and any column of a later branch that itself selects `*`. A source schema changed in YAML is a non-blocking warning, for every `source()` in the reviewed models, when the same PR edits a `schema:`, `database:` or `identifier:` key in a source YAML (or deletes one) and also changes a model that reads a source; a PR that edits only the YAML gets no finding, and a `+schema` for sources in `dbt_project.yml`, a schema from `var()` or `env_var()` or set through a YAML anchor or folded value, and changes made outside the PR are not detected. (#1875) +- **`altimate review` reports three PII exposures it used to call pre-existing.** Without a compiled base, a PII output column is reported as new, and can block, when the base file's own SQL cannot have exposed that output column name: it does not name it outside comments, its final query names every column in its own select list (no `*`, `COLUMNS(…)`, whole-row reference, struct expansion or Unicode-escaped name such as `U&"…"`), the review reads that query fully (a CTE column list, a parenthesised UNION, an integer division `//` or a column named like an unaliased `ref` leave it undecided), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags. A renamed PII output (`email as contact`) is then new. A table compiled under another schema is the same table only when the model's code reads it the same way on both sides (the same `ref`, `source` or table name; the quote style and spacing inside a `ref` or `source` call do not count, a quoted SQL name is compared as written), or, for a model compiled under a name its `ref` does not show (an alias, a version or a source `identifier:`), when no relation in the model's code was added or replaced (a table read through an ephemeral model counts the same way); a schema, `source`, `var` or package a relation is built from, swapped in the model's code, is reported, and so is a `{% set %}` variable it is built from whose plain string value was replaced (`'masked'` → `'raw'`; the quote style and `{# … #}` comments do not count). Where the code cannot decide (such a model only gained a relation, the SQL is a shape the review does not fully parse or lists no relation, as when a macro emits the query, two different relations share one table name or one was added or removed beside an unchanged one, a `ref` gained or lost a package argument, or such a `{% set %}` changed in another way), the column is a non-blocking warning that may predate the PR, and such a warning never hides another PII finding. Renaming a CTE or subquery alias, turning a CTE into a subquery, qualifying a column, adding a join, or reading a CTE through `select *` instead of naming its columns, is not a change for a computed PII column (`lower(email) as email`), nor is an environment whose schemas sort differently. A UNION branch that computes PII under a name the base already exposed (`lower(ssn) as email`) is reported, also after a first branch that selects `*` from a CTE or subquery whose columns are all known, and so is a swap of which table each branch's computation reads (`md5(email)` from `a` and `lower(email)` from `b` reversed) or of which column sits in which argument (`coalesce(m.email, r.email)` reversed, where `m` masks it). Now reported that was not before: qualifying a raw table name (`from customers` → `from analytics.customers`), and replacing any relation, even an unrelated join, in a model compiled under a name its `ref` does not show. Not reliably detected yet: any later-branch column, raw or computed, at or after a `*` over a table, a `ref()`, a CTE that itself selects `*` or a `using`/`natural` join (its columns are matched only by their position among the select items; a new column past the last of them is a non-blocking warning), and any column of a later branch that itself selects `*`. A source schema changed in YAML is a non-blocking warning, for every `source()` in the reviewed models, when the same PR edits a `schema:`, `database:` or `identifier:` key in a source YAML (or deletes one) and also changes a model that reads a source; a PR that edits only the YAML gets no finding, and a `+schema` for sources in `dbt_project.yml`, a schema from `var()` or `env_var()` or set through a YAML anchor or folded value, and changes made outside the PR are not detected. Comparing source YAML per source and table (so a moved source or an edit to an unrelated source no longer turns every `source()` read into a warning) moved to a follow-up. (#1875) ## [0.12.12] - 2026-11-20 diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 1ee86690e7..7b29b6e9b2 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -351,25 +351,33 @@ rubric: name may be another table. A model whose compiled table name is not the name in its `ref` (an `alias`, a version such as `ref('customers', v=2)`, a custom alias macro, a source `identifier:`) counts as the same table when no - relation in the model's code was added or replaced (removing a join is - fine). When a relation was replaced, even an unrelated join, the compiled + relation in the model's code was added or replaced (removing a join to a + table with another name is fine). When a relation was replaced, even an unrelated join, the compiled name cannot be tied to the unchanged call, so it counts as a different table and can block; this also holds for a table read through an ephemeral model (its compiled CTE reads a table the model's code never names). A changed - schema, `source`, `var`, package (`ref('a', 'm')` → `ref('b', 'm')`) or - `{% set %}` variable a relation is built from (`{{ s }}.customers`) is a - different table, and so, under another schema, is a quoted name whose case - changed. When the code cannot decide (such a model only gained a relation; - its SQL is a shape the review does not fully parse and no relation in it was - replaced, where a `config()` or select-list Jinja edit does not count; it - reads two different relations with one table name, such as two `source()` - calls for `customers`, or a second one was added or removed beside an - unchanged one; a `ref` gained or lost a package argument; or another - `{% set %}` variable changed while a relation is built from Jinja), the - column is reported as a non-blocking warning that may predate the PR. - Renaming a CTE or a subquery alias, or turning a CTE into a subquery, is not - a change: a computed PII column (`lower(email) as email`) is compared by how - it is computed from the source columns, not by what its CTEs are called. A source whose schema changes only in YAML + schema, `source`, `var` or package (`ref('a', 'm')` → `ref('b', 'm')`) a + relation is built from is a different table, and so is one built from a + `{% set %}` variable (`{{ s }}.customers`) when a plain string value of that + variable was replaced by another (`'masked'` → `"raw"`, in any of its + assignments; the quote style and `{# … #}` comments do not count), and, + under another schema, a quoted name whose case changed. When the code cannot + decide (such a model only gained a relation; its SQL is a shape the review + does not fully parse and no relation it lists was replaced, or it lists none, + as when a macro emits the query; it reads two different relations with one + table name, such as two `source()` calls for `customers`, or a second one was + added or removed beside an unchanged one; a `ref` gained or lost a package + argument; a `{% set %}` the relation names changed in another way, such as an + expression, a block or an added assignment; or another `{% set %}` variable + changed while a relation is built from Jinja), the column is reported as a + non-blocking warning that may predate the PR. Renaming a CTE or a subquery + alias, turning a CTE into a subquery, qualifying a column (`email`, + `l.email`, `leads.email`), adding a join, or reading a CTE through `select *` + instead of naming its columns, is not a change: a computed PII column + (`lower(email) as email`) is compared by how it is computed from the source + columns, not by how they are written or what its CTEs are called. Which + column sits in which argument does count (`coalesce(m.email, r.email)` + reversed, where `m` masks the column, is reported). A source whose schema changes only in YAML is flagged the same way when the same PR edits a `schema:`, `database:` or `identifier:` key in a source YAML (a YAML file that declares `sources:`; a deleted one counts; a schema set through a YAML anchor or a folded @@ -384,12 +392,12 @@ rubric: column it lands in (`select *, 'web' as channel from c` puts `channel` after all of `c`'s columns). After a `*` over a table, a `ref()`, a CTE that itself selects `*`, or a `using`/`natural` join (which outputs each merged - column once), the columns are unknown: a later-branch column is matched only - by its position among the first branch's select items, which the `*` throws - off. A new later-branch column past the last of those items is reported as a - non-blocking warning; one that lands on another item's name, and any column - of a later branch that itself selects `*` (`… union all select * from s`), - is not reliably detected yet. That + column once), the columns are unknown, so any later-branch column (raw or + computed) at or after that `*`'s position may go unreported: it is matched + only by its position among the first branch's select items, which the `*` + throws off (one past the last of them is a non-blocking warning). Any column + of a later branch that itself selects `*` (`… union all select * from s`) + is not reliably detected yet either. That comparison needs the base version's SQL; when it can't be compiled, a PII column is reported as a non-blocking warning that may predate the PR, unless the base file's own SQL cannot have exposed that output column name: then it @@ -402,8 +410,9 @@ rubric: `U&"e\006Dail"`; a final `table c` or `from c` selects every column), the review reads that base query fully (comments, string literals and quoted names aside; a CTE column list such as `with x(a, b) as`, - a parenthesised UNION, an integer division `//` or a column named like an - unaliased `ref` leave it undecided), and it holds no Jinja but `ref`, `source`, `config`, `this` and + a parenthesised UNION, an integer division `//`, a column named like an + unaliased `ref`, or a quote, block comment or dollar tag left unclosed leave + it undecided), and it holds no Jinja but `ref`, `source`, `config`, `this` and `if`/`for`/`set` tags (a macro call, a variable or an `{% include %}` could emit any column). The proof is about the output name, so a renamed PII output (`email as contact`) is reported as new. The pattern check also blocks diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 76fafffc63..880f2eebbc 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1167,30 +1167,53 @@ interface ModelContext { */ const RAW_BASE_PLAIN_EXPR = /^\{\{-?\s*(?:(?:ref|source|config)\s*\([^{}]*\)|this)\s*-?\}\}$/ const RAW_BASE_STAR = /(?:^|[\s.(])\*(?=\s|$|[a-z(),])|(? RAW_BASE_PLAIN_EXPR.test(e))) return undefined if (!(oldSql.match(/\{%[\s\S]*?%\}/g) ?? []).every((t) => SILENT_JINJA_TAG.test(t))) return undefined - // Comments out (a Snowflake `//` one only at the start of a line: elsewhere it - // may divide), literals and quoted identifiers kept (one pass, so `--` inside - // `'…'`, `"…"`, `` `…` `` or `$$…$$` is not a comment). - const code = oldSql - .replace( - /\{#[\s\S]*?#\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"|`(?:[^`]|``)*`|\$([A-Za-z_]\w*)?\$[\s\S]*?\$\1\$/g, - (m) => (/^['"`$]/.test(m) ? m : " "), - ) - .replace(/^[ \t]*\/\/[^\n]*/gm, " ") + const texts = rawBaseTexts(oldSql) + if (!texts) return undefined + const { code, readable } = texts // Only the final query's own select lists can prove a column absent: a CTE's // list does not (`with u as (select id from c) table c`), nor a final query // without one, nor a whole row or a struct expansion (`select c`, `unnest(s)`). - // Read with literals outside Jinja emptied and parentheses in quoted names - // blanked, so `'it\'s'`, `$$x$$` and `"total (usd)"` parse; the base must be - // read fully. - const readable = code.replace(/\{\{[\s\S]*?\}\}|'(?:[^'\\]|''|\\.)*'|\$([A-Za-z_]\w*)?\$[\s\S]*?\$\1\$|"(?:[^"]|"")*"|`(?:[^`]|``)*`/g, (m) => - m.startsWith("{{") ? m : /^['$]/.test(m) ? "''" : m.replace(/[()]/g, "_"), - ) + // The base must be read fully. if (!explicitProjection(readable)) return undefined // A Unicode-escaped name (`U&"e\006Dail"` is `email`) is not searched as written. if (/(? refCovered(ref, exposed, env))) return true - // The same computation counts only over the same source columns: the - // signature holds the item text and derived-query bodies, not the tables - // (`lower(email)` from `customers` → from `spouses` is new), and each - // lineage record pairs a computation with the columns it reads (`md5` - // and `lower` swapped between two tables' `email` is new). Refs no - // source explains are left to the signature. + // The same computation counts only over the same source columns: each + // lineage record pairs a computation with the columns it reads + // (`lower(email)` from `customers` → from `spouses` is new, and so is + // `md5` and `lower` swapped between two tables' `email`). A column read + // that no source explains keeps its text in the computation. const baseReads = base.reads.get(name) ?? new Set() const sameReads = [...(reads ?? [])] .filter((ref) => !ref.startsWith("?")) .every((ref) => refCovered(ref, baseReads, env)) - const baseSigs = base.signatures.get(name) const baseLineage = base.lineage.get(name) - return ( - sameReads && - !!baseSigs && - [...(head.signatures.get(name) ?? [])].every((sig) => baseSigs.has(sig)) && - [...(head.lineage.get(name) ?? [])].every((sig) => lineageCovered(sig, baseLineage, env)) - ) + return sameReads && [...(head.lineage.get(name) ?? [])].every((record) => lineageCovered(record, baseLineage, env)) } // Unresolved only through a plain `*`: a shape the parser does not model (a // parenthesised top-level union, `* except (…)`) is reported. A `*` the @@ -1572,7 +1589,7 @@ export async function runReview(input: OrchestrateInput): Promise 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())), @@ -1711,8 +1728,12 @@ export async function runReview(input: OrchestrateInput): Promise f.category === "pii_exposure" && f.evidence?.tool === "schema.detect_pii").map((f) => f.file), + flat + .filter((f) => f.category === "pii_exposure" && f.evidence?.tool === "schema.detect_pii" && f.confidence !== "unknown") + .map((f) => f.file), ) // Per file, the output columns an engine PII lane reported as new (not // undecided), at the highest severity it gave each. A regex twin for such a diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 64b76dea13..9127a2f6d2 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -331,30 +331,36 @@ const COLUMN_TOKEN = new RegExp(String.raw`(? { - let e = expr.replace(TYPED_LITERAL, " ").replace(/'(?:[^']|'')*'/g, " ") - // `f(…) over (…)` / `filter (…)` / `within group (…)`: cut each clause to its + * `time`, `row`) counts as a column unless it is in its keyword phrase. Each + * read carries its offsets in `expr` (`start` to `end`). */ +function columnReadSpans(expr: string): Array<{ qualifier?: string; column: string; start: number; end: number }> { + // Skipped text is blanked, not cut, so offsets stay those of `expr`. + const blank = (m: string) => " ".repeat(m.length) + let e = expr.replace(TYPED_LITERAL, blank).replace(/'(?:[^']|'')*'/g, blank) + // `f(…) over (…)` / `filter (…)` / `within group (…)`: blank each clause to its // `)`. `filter(arr, x -> …)` without a call before it is an array function. const clause = /\)\s*(?:over|filter|within\s+group)\s*\(/i for (let m = clause.exec(e); m; m = clause.exec(e)) { - const open = m.index + m[0].length - 1 - e = e.slice(0, m.index + 1) + " " + e.slice(closingParen(e, open) + 1) + const close = closingParen(e, m.index + m[0].length - 1) + e = e.slice(0, m.index + 1) + blank(e.slice(m.index + 1, close + 1)) + e.slice(close + 1) } e = e - .replace(/\bnulls\s+(?:first|last)\b|\bat\s+time\s+zone\b|\b(?:respect|ignore)\s+nulls\b/gi, " ") - .replace(/::\s*\w+(?:\s*\([\d\s,]*\))?/g, " ") - .replace(/\bas\s+\w+(?:\s+\w+)*?(?:\s*\([\d\s,]*\))?\s*(?=\))/gi, " ") - const out: Array<{ qualifier?: string; column: string }> = [] + .replace(/\bnulls\s+(?:first|last)\b|\bat\s+time\s+zone\b|\b(?:respect|ignore)\s+nulls\b/gi, blank) + .replace(/::\s*\w+(?:\s*\([\d\s,]*\))?/g, blank) + .replace(/\bas\s+\w+(?:\s+\w+)*?(?:\s*\([\d\s,]*\))?\s*(?=\))/gi, blank) + const out: Array<{ qualifier?: string; column: string; start: number; end: number }> = [] for (const m of e.matchAll(COLUMN_TOKEN)) { if (m[3]) continue // a function call const column = unquote(m[2]) // A bare keyword is syntax; a quoted or qualified one is a column. if (!m[1] && !/^["\x60]/.test(m[2]) && EXPR_KEYWORDS.has(column)) continue - out.push(m[1] ? { qualifier: unquote(m[1]), column } : { column }) + const span = { start: m.index, end: m.index + m[0].length } + out.push(m[1] ? { qualifier: unquote(m[1]), column, ...span } : { column, ...span }) } return out } +const columnReads = (expr: string) => + columnReadSpans(expr).map(({ qualifier, column }) => (qualifier === undefined ? { column } : { qualifier, column })) /** A select item's expression and its alias (`AS` or implicit), if any. */ function splitAlias(text: string): { expr: string; alias?: string } { @@ -971,18 +977,17 @@ export interface FinalOutputs { /** The database/schema prefix of every table the SQL reads (`""` for an * unqualified one), for `refCovered`'s environment check. */ prefixes: Set - /** Per output name, a signature of how it is computed: the item text (string - * literals as written, each FROM/JOIN alias named by its source) plus the - * full text of every CTE or subquery its select reads. Equal signatures on two sides mean the name is computed the same way. */ - signatures: Map> - /** Per output name, as `signatures` but following columns, not whole bodies, - * and never naming a CTE, subquery or alias: per computed item, its text plus - * the `lineage` of each CTE or subquery column it reads (through a plain `*`, - * the source column the `*` passes on), paired with the `source.column` refs + /** Per output name, how each item computing it is computed, following columns + * and never naming a CTE, subquery, alias or qualifier: per computed item, its + * expression (string literals as written) with each column it reads replaced + * by the records of that column (for a CTE or subquery column, its own + * `lineage`, through a plain `*` the source column the `*` passes on; for a + * table column, the column read as is), paired with the `source.column` refs * it reads (`lineageCovered` compares them); a column read as is keeps the - * records of what it reads. Another column, a filter or a new name for that - * CTE leaves it unchanged; unmasking the column there (`md5(ssn) as ssn` → - * `ssn`), or moving `md5(…)` to another table's column, does not. */ + * records of what it reads. Qualifying a column, another column, a filter, a + * `*` wrapper or a new name for that CTE leaves it unchanged; unmasking the + * column there (`md5(ssn) as ssn` → `ssn`), or moving `md5(…)` to another + * table's column, does not. */ lineage: Map> /** Per output name, every `source.column` ref its value is computed from, raw * or not, resolved like `raw` (`lower(s.ssn) as email` with `spouses s` → @@ -1001,8 +1006,6 @@ interface ScopeOutputs extends Omit - /** Every item's text, and that of every scope it reads. */ - body: string } let unresolvedRefs = 0 @@ -1088,11 +1091,11 @@ function relationTexts(sql: string): { byName: Map>; all: Se // The original text, not the parser's name: that masks Jinja to `_`, so two // prefixes of one length (`var('masked')`, `var('raw_db')`) would look alike. const text = normalizeRelation(src.text) - const own = relationTableName(text) + const tableName = relationTableName(text) all.add(text) - const texts = byName.get(own) + const texts = byName.get(tableName) if (texts) texts.add(text) - else byName.set(own, new Set([text])) + else byName.set(tableName, new Set([text])) } // A query the parser does not model (a macro that emits the whole query, say) may read // relations it never lists: the relation set then proves nothing. @@ -1110,14 +1113,19 @@ function relationTexts(sql: string): { byName: Map>; all: Se * cannot be told), one added or removed beside an unchanged one, or a side * that does not read it. A name it never writes (a model with an `alias`, * a version, a source `identifier:`: `ref('customers', v=2)` compiles to - * `customers_v2`) cannot be tied to one call. Only relations are evidence - * (the FROM/JOIN texts, or, when the parser lists none, the query's Jinja - * expressions but `config()`, as a macro that emits the whole query): a - * replacement (one removed and one added) is `different`; with a complete - * parse, relations only removed or none changed is `same`; anything else - * (relations only added, an incomplete parse) is `unknown`. A `source()` read - * while the pull request edits a source YAML (`sourcesEdited`) is at best - * `unknown`: the swap may be there. A missing side proves nothing. */ + * `customers_v2`) cannot be tied to one call. Only the FROM/JOIN relations + * are evidence: a replacement (one removed and one added) is `different`; + * with a complete parse, relations only removed or none changed is `same`; + * anything else (relations only added, an incomplete parse, a query whose + * relations the parser cannot list, such as a macro that emits it) is + * `unknown`. A `source()` read while the pull request edits a source YAML + * (`sourcesEdited`) is at best `unknown`: the swap may be there. A relation + * built from a `{% set %}` variable (`{{ s }}.customers`) reads the same text + * whatever the variable holds: it is `different` only when every assignment + * of a variable it names stayed in place and the changed ones replaced one + * plain string literal by another (`'masked'` → `"raw"`), and `unknown` when + * any other `set` changed (an expression, a block, an assignment added or + * removed, or a variable it does not name). A missing side proves nothing. */ export function rawRelationsMatch( oldSql: string | undefined, newSql: string | undefined, @@ -1129,45 +1137,43 @@ export function rawRelationsMatch( // A package argument (`ref('core', 'm')`) may name the model an unqualified // `ref('m')` resolves to, so the two only overlap (two packages do not). const unpackaged = (t: string) => t.replace(/^\{\{ref\('[^']*',('[^']*'.*)\)\}\}$/, "{{ref($1)}}") - const overlaps = (a: Set, b: Set) => [...a].some((t) => [...b].some((u) => t === u || unpackaged(t) === u || t === unpackaged(u))) + const overlaps = (a: Set, b: Set) => { + for (const t of a) for (const u of b) if (t === u || unpackaged(t) === u || t === unpackaged(u)) return true + return false + } const unchangedMatch = (texts: Set): RelationMatch => sourcesEdited && [...texts].some((t) => t.startsWith("{{source(")) ? "unknown" : "same" - const evidence = (side: typeof base, sql: string) => - side.all.size || side.complete - ? side.all - : new Set((sql.match(/\{\{[\s\S]*?\}\}/g) ?? []).map(normalizeRelation).filter((t) => !t.startsWith("{{config("))) - // A relation built from a `{% set %}` variable (`{{ s }}.customers`) reads - // the same text whatever the variable holds: a changed variable it names - // makes it a swap, any other changed `set` leaves its Jinja undecided. - const sets = (sql: string) => - new Map( - [...sql.matchAll(/\{%-?\s*set\s+([A-Za-z_]\w*)\s*(?:=([\s\S]*?)-?%\}|-?%\}([\s\S]*?)\{%-?\s*endset)/g)].map((m) => [ - m[1], - (m[2] ?? m[3]).replace(/\s+/g, ""), - ]), - ) - const setsWas = sets(oldSql) - const setsNow = sets(newSql) - const changedSets = [...new Set([...setsWas.keys(), ...setsNow.keys()])].filter((n) => setsWas.get(n) !== setsNow.get(n)) - const setJinja = (texts: Iterable): RelationMatch | undefined => { + const setsWas = setAssignments(oldSql) + const setsNow = setAssignments(newSql) + const changedSets = [...new Set([...setsWas.keys(), ...setsNow.keys()])].filter( + (n) => JSON.stringify(setsWas.get(n) ?? []) !== JSON.stringify(setsNow.get(n) ?? []), + ) + // Every assignment in place, each changed one a plain literal on both sides. + const literalReplaced = (n: string) => { + const was = setsWas.get(n) ?? [] + const now = setsNow.get(n) ?? [] + return was.length === now.length && was.every((v, i) => v === now[i] || (v.startsWith(SET_LITERAL) && now[i].startsWith(SET_LITERAL))) + } + const setChange = (texts: Iterable): RelationMatch | undefined => { if (!changedSets.length) return undefined const exprs = [...texts].flatMap((t) => [...t.matchAll(/\{\{([\s\S]*?)\}\}/g)].map((m) => m[1])).filter((e) => !/^(?:ref|source)\(/.test(e)) - if (exprs.some((e) => changedSets.some((n) => new RegExp(`(? exprs.some((e) => new RegExp(`(? !now.has(t)) - const added = [...now].some((t) => !was.has(t)) + const removed = [...base.all].some((t) => !head.all.has(t)) + const added = [...head.all].some((t) => !base.all.has(t)) let untied: RelationMatch = "unknown" if (removed && added) untied = "different" else if (base.complete && head.complete && !added) untied = unchangedMatch(base.all) - const untiedSet = setJinja([...base.all, ...head.all]) + // A name the code does not write is tied to no relation, so a changed `set` + // leaves it undecided at most. + if (untied !== "different" && setChange([...base.all, ...head.all])) untied = "unknown" return (table) => { const a = base.byName.get(table) const b = head.byName.get(table) - if (!a && !b) return untiedSet && untied !== "different" ? untiedSet : untied - const set = setJinja([...(a ?? []), ...(b ?? [])]) + if (!a && !b) return untied + const set = setChange([...(a ?? []), ...(b ?? [])]) if (set === "different") return set // Only a replacement (every text for the name changed) is a swap. if (!a || !b || overlaps(a, b)) { @@ -1178,6 +1184,29 @@ export function rawRelationsMatch( } } +/** Marks a `set` value that is one plain string literal (see `setAssignments`). */ +const SET_LITERAL = "\u0001" +// `{% set name = value %}` (whose string literals may hold `%}`) or +// `{% set name %}…{% endset %}`. +const SET_TAG = + /\{%-?\s*set\s+([A-Za-z_]\w*)\s*(?:=((?:'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|[^'"%]|%(?!\}))*?)-?%\}|-?%\}([\s\S]*?)\{%-?\s*endset)/g + +/** Per `{% set %}` variable, every value assigned to it, in order, outside + * `{# … #}`: a plain string literal as `SET_LITERAL` plus its text (the quote + * style aside), anything else with white space outside literals dropped and + * each literal in one quote style. */ +function setAssignments(sql: string): Map { + const out = new Map() + for (const m of sql.replace(/\{#[\s\S]*?#\}/g, " ").matchAll(SET_TAG)) { + const plain = m[2] === undefined ? undefined : /^\s*(?:'([^'\\]*)'|"([^"\\]*)")\s*$/.exec(m[2]) + const value = plain + ? `${SET_LITERAL}${plain[1] ?? plain[2]}` + : (m[2] ?? m[3]).replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|\s+/g, (t) => (/^['"]/.test(t) ? `'${t.slice(1, -1)}'` : "")) + out.set(m[1], [...(out.get(m[1]) ?? []), m[3] === undefined ? value : `{%set%}${value}`]) + } + return out +} + /** * Head table `h` and base table `b` are the same table. Equal names are. With * the same unqualified name, a prefix difference is an environment difference (a base @@ -1232,8 +1261,16 @@ export function refCovered(ref: string, exposed: Set, env?: RelationPref } /** A `lineage` record: a digest of the item's computation, including the - * unqualified table name of each column it reads, then its full refs. */ + * unqualified table name of each column it reads, then this separator, then + * its full refs, separated by `LINEAGE_REF`. */ const LINEAGE_REFS = "\u0006" +const LINEAGE_REF = "\u0007" +/** Between the parts hashed into a `lineage` digest. */ +const LINEAGE_PART = "\u0001" +/** Around the digests that stand for one column read in a computation's text, + * and between them. */ +const LINEAGE_READ = "\u0004" +const LINEAGE_READ_DIGEST = "\u0005" /** * The head `record` (see `FinalOutputs.lineage`) is computed as one of the base @@ -1244,11 +1281,13 @@ export function lineageCovered(record: string, base: Set | undefined, en if (!base) return false if (base.has(record)) return true const [digest, refs] = record.split(LINEAGE_REFS) - return [...base].some((b) => { + for (const b of base) { const [baseDigest, baseRefs] = b.split(LINEAGE_REFS) - const covered = new Set(baseRefs ? baseRefs.split("\u0007") : []) - return baseDigest === digest && (!refs || refs.split("\u0007").every((ref) => refCovered(ref, covered, env))) - }) + if (baseDigest !== digest) continue + const covered = new Set(baseRefs ? baseRefs.split(LINEAGE_REF) : []) + if (!refs || refs.split(LINEAGE_REF).every((ref) => refCovered(ref, covered, env))) return true + } + return false } /** `sql` lowercased except inside string literals, whose case can change what @@ -1347,42 +1386,23 @@ export function finalOutputs(sql: string): FinalOutputs { if (open.length > 1) return same(new Set([`${[...new Set(open.map((x) => x.name))].sort().join("|")}.${col}`])) return same(unresolved(col)) } - // An item's text for signatures: lowercased outside literals, with each - // FROM/JOIN alias replaced by the source it names (a table by its unqualified name, - // without database/schema, which `refCovered` compares environment-aware via - // `reads`; a CTE or subquery by its scope, or by nothing for `lineage`, which - // follows the scope's columns instead), so renaming an alias (`md5(c.ssn)` → - // `md5(cu.ssn)` on one table) keeps the signature. - const signatureText = (item: SelectItem, scope: string, scopeNames = true) => { - const named = new Map() - for (const src of sources.get(`${scope}#${item.branch}`) ?? []) - if (!scopeNames && byScope.has(src.name)) named.set(src.alias ?? src.name, "") - else if (src.alias && src.alias !== src.name) named.set(src.alias, byScope.has(src.name) ? src.name : splitTable(src.name).name) - const text = lowerOutsideLiterals(item.exact) - if (!named.size) return text - return text.replace(/'(?:[^']|'')*'|[^']+/g, (part) => - part.startsWith("'") - ? part - : part.replace(new RegExp(String.raw`(? { - const src = named.get(unquote(q)) - return src === undefined ? m : `\u0004${src}${dot}` - }), - ) - } - // A `lineage` record: a digest of the computation (its text, the records of - // each CTE or subquery column it reads, the unqualified table of each source - // column it reads, which an environment change keeps), then its full refs. A - // digest, so a column computed from several upstream columns at every level - // of a CTE chain does not grow its key exponentially. A column read as is has - // the empty computation over its source column. - const lineageRecord = (text: string, upstream: string[], reads: Set) => { - const known = [...reads].filter((r) => !r.startsWith("?")).sort() - const tables = known.map((r) => { - const split = splitRef(r) - return `${split.tables.map((t) => splitTable(t).name).join("|")}.${split.column}` - }) - const digest = createHash("sha256").update(`${text}\u0001${upstream.join("\u0002")}\u0001${tables.join("\u0002")}`).digest("base64") - return `${digest}${LINEAGE_REFS}${known.join("\u0007")}` + // A `lineage` record: a digest of the computation (its text, with each column + // read replaced by what it reads, and the unqualified table of each source + // column it reads, which an environment change keeps; sorted after the + // database/schema is dropped, so their order does not depend on it), then its + // full refs. A digest, so a column computed from several upstream columns at + // every level of a CTE chain does not grow its key exponentially. A column + // read as is has the empty computation over its source column. + const lineageRecord = (text: string, reads: Set) => { + const known = [...reads].filter((r) => !r.startsWith("?")) + const tables = known + .map((r) => { + const split = splitRef(r) + return `${split.tables.map((t) => splitTable(t).name).sort().join("|")}.${split.column}` + }) + .sort() + const digest = createHash("sha256").update([text, ...tables].join(LINEAGE_PART)).digest("base64") + return `${digest}${LINEAGE_REFS}${known.join(LINEAGE_REF)}` } const lineageDigest = (record: string) => record.split(LINEAGE_REFS)[0] // The records of `column` as the CTE or subquery `src` outputs it: its own, @@ -1391,7 +1411,7 @@ export function finalOutputs(sql: string): FinalOutputs { const passedOn = (src: Source, column: string, seen: Set): string[] => { const out = resolve(src.name, seen) if (out.names.has(column)) return [...(out.lineage.get(column) ?? [])] - return out.stars.map((st) => lineageRecord("", [], resolveRef(src.name, st.branch, st.qualifier, column, seen).reads)) + return out.stars.map((st) => lineageRecord("", resolveRef(src.name, st.branch, st.qualifier, column, seen).reads)) } const resolve = (scope: string, seen: Set): ScopeOutputs => { const cached = memo.get(scope) @@ -1399,7 +1419,6 @@ export function finalOutputs(sql: string): FinalOutputs { const inner = innerOf(seen, scope) const raw = new Map>() const names = new Set() - const signatures = new Map>() const lineage = new Map>() const reads = new Map>() const stars: ScopeOutputs["stars"] = [] @@ -1438,11 +1457,8 @@ export function finalOutputs(sql: string): FinalOutputs { if (columns) firstColumns.push(...columns) else layout = undefined } - const readBodies = new Set() for (const item of scopeItems) { const derived = (sources.get(`${scope}#${item.branch}`) ?? []).filter((src) => isDerived(src, scope, seen)) - const bodies = derived.map((src) => resolve(src.name, inner).body).sort() - for (const b of bodies) readBodies.add(b) if (STAR.test(item.text)) { const qualifier = /([^.]+)\.\*$/.exec(item.text)?.[1] const q = qualifier ? unquote(qualifier) : undefined @@ -1452,8 +1468,7 @@ export function finalOutputs(sql: string): FinalOutputs { const out = resolve(src.name, inner) for (const n of out.names) names.add(n) for (const [n, cols] of out.raw) addTo(raw, n, cols) - for (const [n, sigs] of out.signatures) addTo(signatures, n, [...sigs].map((sig) => `*${sig}`)) - for (const [n, sigs] of out.lineage) addTo(lineage, n, sigs) + for (const [n, records] of out.lineage) addTo(lineage, n, records) for (const [n, cols] of out.reads) addTo(reads, n, cols) for (const r of out.unmapped) unmapped.add(r) } @@ -1469,7 +1484,6 @@ export function finalOutputs(sql: string): FinalOutputs { name = at !== undefined && at < firstColumns.length ? firstColumns[at] : firstNames.get(item.position) } if (!name && item.branch === 0) continue - const text = signatureText(item, scope) // Each read follows only the CTE or subquery it comes from: a qualifier // names one source; an unqualified read may come from any that has it. const srcs = sources.get(`${scope}#${item.branch}`) ?? [] @@ -1478,6 +1492,14 @@ export function finalOutputs(sql: string): FinalOutputs { const from = named ? [named].filter((src) => derived.includes(src)) : derived return from.filter((src) => named || resolve(src.name, inner).names.has(column) || resolve(src.name, inner).stars.length) } + // The records of a column read: those of the CTE or subquery column it + // reads, else the table column read as is; none when no source explains it. + const recordsOf = (qualifier: string | undefined, column: string) => { + const passed = fromScopes(qualifier, column).flatMap((src) => passedOn(src, column, inner)) + if (passed.length) return passed + const read = resolveRef(scope, item.branch, qualifier, column, seen).reads + return [...read].some((r) => !r.startsWith("?")) ? [lineageRecord("", read)] : [] + } const refs = item.rawColumn ? resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen) : { @@ -1485,38 +1507,47 @@ export function finalOutputs(sql: string): FinalOutputs { reads: union((item.reads ?? []).map((r) => resolveRef(scope, item.branch, r.qualifier, r.column, seen).reads)), } // An expression whose column reads parse to nothing is not known to read - // nothing: it is never "already exposed" by its reads (the signature may + // nothing: it is never "already exposed" by its reads (its computation may // still match). Only a constant reads nothing. if (!item.rawColumn && !item.reads?.length && !item.constant) refs.reads = unresolved(name ?? "") - // A column read as is keeps the records of the column it reads; a computed - // one gets one record over the records of each column it reads. Neither - // depends on what a CTE, subquery or alias is called. - let records: string[] = [] - if (item.rawColumn) records = fromScopes(item.rawQualifier, item.rawColumn).flatMap((src) => passedOn(src, item.rawColumn!, inner)) + // A column read as is keeps the records of the column it reads. A computed + // one gets one record: its expression, lowercased outside literals, with + // each column read that a source explains replaced by that column's + // records, so neither the qualifier (`email`, `l.email`, `leads.email`) nor + // what a CTE, subquery or alias is called counts, while which column sits + // in which argument does (`coalesce(m.email, r.email)` reversed). + let records: string[] + if (item.rawColumn) records = recordsOf(item.rawQualifier, item.rawColumn) else { - const upstream = (item.reads ?? []).flatMap(({ qualifier, column }) => - fromScopes(qualifier, column).map((src) => `${column}:${passedOn(src, column, inner).map(lineageDigest).sort().join("\u0005")}`), - ) - records = [lineageRecord(signatureText(item, scope, false), upstream.sort(), refs.reads)] + const expr = splitAlias(item.text).expr + // `exact` is `text` with literal contents kept: the same offsets. + const aligned = item.exact.length === item.text.length + let text = aligned ? item.exact.slice(0, expr.length) : item.exact + if (aligned) + for (const read of columnReadSpans(expr).reverse()) { + const upstream = recordsOf(read.qualifier, read.column) + if (!upstream.length) continue + const digests = upstream.map(lineageDigest).sort().join(LINEAGE_READ_DIGEST) + text = `${text.slice(0, read.start)}${LINEAGE_READ}${digests}${LINEAGE_READ}${text.slice(read.end)}` + } + records = [lineageRecord(lowerOutsideLiterals(text), refs.reads)] } - if (!records.length) records = [lineageRecord("", [], refs.reads)] + if (!records.length) records = [lineageRecord("", refs.reads)] if (!name) { for (const r of records) unmapped.add(r) continue } names.add(name) - addTo(signatures, name, [`${text}\u0001${bodies.join("\u0002")}`]) addTo(lineage, name, records) addTo(raw, name, refs.raw) addTo(reads, name, refs.reads) } for (const [n, cols] of raw) if (!cols.size) raw.delete(n) - const body = [scopeItems.map((i) => signatureText(i, scope)).join(","), ...[...readBodies].sort()].join("\u0003") - const result = { raw, names, signatures, lineage, reads, unmapped, stars, body, layout } + const result = { raw, names, lineage, reads, unmapped, stars, layout } memo.set(scope, result) return result } - const { raw, names, signatures, lineage, reads, unmapped, stars } = resolve(ROOT_SCOPE, new Set()) + const { raw, names, lineage, reads, unmapped, stars } = resolve(ROOT_SCOPE, new Set()) // The raw refs a `*` passes `col` through as. Unlike an unqualified column // read over several sources (one combined ref: it comes from exactly one of // them), a `*` passes every source's columns through, so each source is @@ -1566,7 +1597,7 @@ export function finalOutputs(sql: string): FinalOutputs { union(stars.map((st) => starRefs(ROOT_SCOPE, st.branch, st.qualifier, column, new Set()))) const prefixes = new Set() for (const list of sources.values()) for (const src of list) if (!byScope.has(src.name)) prefixes.add(splitTable(src.name).prefix) - return { raw, names, signatures, lineage, reads, unmapped, passthrough: stars.length > 0, starRaw, prefixes } + return { raw, names, lineage, reads, unmapped, passthrough: stars.length > 0, starRaw, prefixes } } /** A Jinja statement tag that emits no text of its own: control flow and `set`. */ diff --git a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts index 358ad22d8c..b406151f7f 100644 --- a/packages/opencode/test/altimate/review-pii-new-exposure.test.ts +++ b/packages/opencode/test/altimate/review-pii-new-exposure.test.ts @@ -53,11 +53,12 @@ const run = async (o: { compiled?: (side: "old" | "new") => string | undefined /** Other files the pull request changes (a `sources.yml`, say), with their content. */ others?: Array + rubric?: typeof DEFAULT_RUBRIC }) => { const env = await runReview({ changedFiles: [{ path: P, status: "modified", diff: o.diff } as ChangedFile, ...(o.others ?? [])], config: { ...DEFAULT_REVIEW_CONFIG, reviewers: o.reviewers }, - rubric: DEFAULT_RUBRIC, + rubric: o.rubric ?? DEFAULT_RUBRIC, mode: "gate", runner: o.runner, getContent: async (f: string, side: "old" | "new") => @@ -224,10 +225,10 @@ describe("2: a schema-only source swap is a different table unless the raw code for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) expectBlocks(await run({ ...c, reviewers, runner: runner() }), { label, reviewers }) }) - test("a macro that emits the whole query proves no relation unchanged", () => { - // The parser lists no relation for either side, so "nothing changed" would be - // vacuous: changed arguments are a change, unchanged ones leave it unknown. - expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('raw') }}")("customers")).toBe("different") + test("a macro that emits the whole query proves no relation unchanged, or changed", () => { + // The parser lists no relation for either side: its Jinja may only emit the + // select list, so neither "nothing changed" nor "replaced" can be told. + expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('raw') }}")("customers")).toBe("unknown") expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('masked') }}")("customers")).toBe("unknown") // A fully read model whose calls are unchanged still explains an aliased name. const same = "select id from {{ ref('customers', v=2) }}" @@ -575,9 +576,9 @@ describe("the same table across environments when the compiled name is tied to n // A Jinja relation that is not a `ref`/`source` leaves the parse incomplete. const joined = (col: string) => `select c.id, ${col}\nfrom {{ ref('customers', v=2) }} c\njoin {{ lookup_table() }} l on l.id = c.id` expect(rawRelationsMatch(joined("c.ssn"), joined("{{ mask('c.ssn') }} as ssn"))("customers_v2")).toBe("unknown") - // A whole-query macro: a changed `config()` beside it is no evidence, changed arguments are a swap. + // A whole-query macro lists no relation: no edit beside or in it is evidence either way. expect(rawRelationsMatch("{{ config(materialized='view') }}\n{{ customer_rows('masked') }}", "{{ config(materialized='table') }}\n{{ customer_rows('masked') }}")("customers")).toBe("unknown") - expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('raw') }}")("customers")).toBe("different") + expect(rawRelationsMatch("{{ customer_rows('masked') }}", "{{ customer_rows('raw') }}")("customers")).toBe("unknown") }) test("two different relations with one unqualified table name are undecided", async () => { @@ -625,7 +626,7 @@ describe("a source YAML edit that may move a `source()`", () => { test("a `schema:` edit outside a source YAML does not", async () => { const files = { // `dbt_project.yml`'s `sources:` block holds configs, not sources. - project: yml("dbt_project.yml", "- +schema: masked\n+ +schema: raw\n- schema: a\n+ schema: b\n", { old: "name: p\nsources:\n p:\n +schema: a\n", new: "name: p\nsources:\n p:\n +schema: b\n" }), + project: yml("dbt_project.yml", "- +schema: masked\n+ +schema: raw\n- +schema: a\n+ +schema: b\n", { old: "name: p\nsources:\n p:\n +schema: a\n", new: "name: p\nsources:\n p:\n +schema: b\n" }), ci: yml(".github/workflows/ci.yml", "- schema: dbt_prod\n+ schema: dbt_ci\n", { old: "jobs:\n", new: "jobs:\n" }), schemaYml: yml("models/marts/_models.yml", "- schema: a\n+ schema: b\n", { old: "version: 2\nmodels:\n", new: "version: 2\nmodels:\n" }), } @@ -756,3 +757,209 @@ describe("an ephemeral upstream model (a known false block)", () => { ) }) }) + +describe("how a computation is written does not count, what it computes does", () => { + const leads = (branch: string) => `select id, email from customers\nunion all\n${branch}` + const computed = leads("select id, lower(email) as email from leads") + + test("qualifying a computed branch's columns, or adding a non-PII join to it, is not new exposure", async () => { + const heads = { + alias: leads("select l.id, lower(l.email) as email from leads l"), + "table name": leads("select leads.id, lower(leads.email) as email from leads"), + join: leads("select l.id, lower(l.email) as email from leads l\njoin regions r on r.id = l.region_id"), + } + for (const [label, h] of Object.entries(heads)) + for (const reviewers of REVIEWER_SETS) + expectQuiet(await run({ base: computed, head: h, diff: "-x\n+y\n", reviewers, runner: piiRunner(["email"]) }), { label, reviewers }) + }) + + test("re-reading a computed CTE column after `select *` from it is not new exposure", async () => { + const b = "with c as (select lower(email) as email from customers)\nselect * from c" + const heads = { + "raw re-read": `${b}\nunion all\nselect email from c`, + "same computation over the table": `${b}\nunion all\nselect lower(email) as email from customers`, + } + for (const [label, h] of Object.entries(heads)) + for (const reviewers of REVIEWER_SETS) + expectQuiet(await run({ base: b, head: h, diff: "+union all\n+select email from c\n", reviewers, runner: piiRunner(["email"]) }), { label, reviewers }) + }) + + test("a computation whose tables sort differently in another environment is the same", async () => { + const raw = `select lower(a.email || b.email) as email\nfrom {{ ref("a") }} a cross join {{ ref("b") }} b` + const head = `-- note\n${raw}` + // `x.a` < `y.b` in the base, `w.b` < `z.a` in the head. + const compiled = (side: "old" | "new") => + (side === "old" ? raw : head).replace('{{ ref("a") }}', side === "old" ? "x.a" : "z.a").replace('{{ ref("b") }}', side === "old" ? "y.b" : "w.b") + for (const reviewers of REVIEWER_SETS) + expectQuiet(await run({ base: raw, head, diff: "+-- note\n", reviewers, runner: piiRunner(["email"]), compiled }), reviewers) + }) + + test("swapping which CTE each argument reads is new exposure", async () => { + // `m` masks the column, `r` does not: `coalesce` now returns the raw value first. + const sql = (args: string) => + `with m as (select id, md5(email) as email from customers),\nr as (select id, email from customers)\nselect coalesce(${args}) as email\nfrom m join r on m.id = r.id` + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks( + await run({ base: sql("m.email, r.email"), head: sql("r.email, m.email"), diff: "-select coalesce(m.email, r.email) as email\n+select coalesce(r.email, m.email) as email\n", reviewers, runner: piiRunner(["email"]) }), + reviewers, + ) + }) + + test("unmasking is still new exposure however the branch is qualified", async () => { + const b = leads("select id, md5(email) as email from leads") + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) + expectBlocks(await run({ base: b, head: leads("select l.id, lower(l.email) as email from leads l"), diff: "-x\n+y\n", reviewers, runner: piiRunner(["email"]) }), reviewers) + }) +}) + +describe("an undecided finding never hides a blocking one", () => { + test("an undecided `email` beside a `passport` only the pattern check finds, with `blockingRules` set", async () => { + // `customers` compiles under another name (an alias), so `email` is undecided once a relation is added. + const b = "select c.id, c.email\nfrom {{ ref('customers') }} c" + const h = "select c.id, c.email,\n s.passport\nfrom {{ ref('customers') }} c\njoin {{ ref('secrets') }} s on s.id = c.id" + const compiled = (side: "old" | "new") => { + const env = side === "old" ? "dbt_prod" : "dbt_ci_42" + return (side === "old" ? b : h).replace("{{ ref('customers') }}", `analytics.${env}.dim_customers`).replace("{{ ref('secrets') }}", `analytics.${env}.secrets`) + } + const diff = "-select c.id, c.email\n+select c.id, c.email,\n+ s.passport\n+join {{ ref('secrets') }} s on s.id = c.id\n" + for (const reviewers of [["pii_exposure", "dbt_patterns"], []]) { + const r = await run({ base: b, head: h, diff, reviewers, runner: piiRunner(["email"], classifyAll(/email/)), compiled, rubric: { ...DEFAULT_RUBRIC, blockingRules: ["pii-into-mart"] } }) + expect({ reviewers, verdict: r.verdict, passport: r.pii.some((f) => f.severity === "critical" && /PII column added/.test(f.title)) }).toEqual({ reviewers, verdict: "REQUEST_CHANGES", passport: true }) + } + }) +}) + +describe("evidence the raw code cannot give is undecided, never a swap", () => { + test("a select-list macro edit in a query with no parsed relation is not a swap", async () => { + const b = "select {{ column_list('old_style') }} {{ from_customers() }}" + const h = b.replace("old_style", "new_style") + const compiled = (side: "old" | "new") => `select email from analytics.${side === "old" ? "dbt_prod" : "dbt_ci_42"}.customers` + expect(rawRelationsMatch(b, h)("customers")).toBe("unknown") + for (const reviewers of REVIEWER_SETS) { + const r = await run({ base: b, head: h, diff: `-${b}\n+${h}\n`, reviewers, runner: piiRunner(["email"]), compiled }) + expect({ reviewers, critical: r.critical, blocks: r.verdict === "REQUEST_CHANGES" }).toEqual({ reviewers, critical: false, blocks: false }) + } + }) + + const model = (set: string) => `${set}\nselect ssn from {{ s }}.customers` + const env = (side: "old" | "new") => `select ssn from ${side === "old" ? "prod_db" : "ci_db"}.analytics.customers` + const db = "{% set s = target.database ~ '.analytics' %}" + + test("a `{% set %}` edit that changes nothing is not a swap", async () => { + const edits: Record = { + "quote style": [db, `{% set s = target.database ~ ".analytics" %}`], + parentheses: ["{% set s = target.schema %}", "{% set s = (target.schema) %}"], + "commented-out assignment": [db, `${db}\n{# {% set s = 'raw' %} #}`], + "literal quote style": ["{% set s = 'analytics' %}", '{% set s = "analytics" %}'], + } + for (const [label, [b, h]] of Object.entries(edits)) { + expect({ label, match: rawRelationsMatch(model(b), model(h))("customers") }).not.toEqual({ label, match: "different" }) + for (const reviewers of REVIEWER_SETS) { + const r = await run({ base: model(b), head: model(h), diff: `-${b}\n+${h}\n`, reviewers, runner: piiRunner(["ssn"]), compiled: env }) + expect({ label, reviewers, critical: r.critical, blocks: r.verdict === "REQUEST_CHANGES" }).toEqual({ label, reviewers, critical: false, blocks: false }) + } + } + }) + + test("a `{% set %}` literal replaced is a swap, in any assignment and whatever its literals hold", () => { + const two = (first: string) => model(`{% set s = '${first}' %}\n{% if x %}{% set s = 'pii_masked' %}{% endif %}`) + expect(rawRelationsMatch(two("masked"), two("raw"))("customers")).toBe("different") + expect(rawRelationsMatch(model("{% set s = 'masked' %}"), model('{% set s = "raw" %}'))("customers")).toBe("different") + // A `%}` inside a literal does not end the tag. + expect(rawRelationsMatch(model("{% set s = 'a%}b' %}"), model("{% set s = 'a%}c' %}"))("customers")).toBe("different") + // Whitespace inside a literal counts. + expect(rawRelationsMatch(model("{% set s = 'raw db' %}"), model("{% set s = 'rawdb' %}"))("customers")).toBe("different") + // An expression, or an assignment added, is undecided. + expect(rawRelationsMatch(model(db), model("{% set s = target.schema %}"))("customers")).toBe("unknown") + expect(rawRelationsMatch(model("{% set s = 'masked' %}"), model("{% set s = 'masked' %}\n{% set s = 'raw' %}"))("customers")).toBe("unknown") + }) + + test("a changed `{% set %}` makes only the relation that names it a swap", () => { + const sql = (v: string) => `{% set s = '${v}' %}\nselect c.ssn, o.total\nfrom {{ ref('customers', v=2) }} c\njoin {{ s }}.orders o on o.id = c.id` + expect(rawRelationsMatch(sql("a"), sql("b"))("orders")).toBe("different") + // `customers_v2` is written by no relation: undecided, not a swap. + expect(rawRelationsMatch(sql("a"), sql("b"))("customers_v2")).toBe("unknown") + }) +}) + +describe("known gaps and warnings, pinned", () => { + test("a raw PII branch after a `*` over a table is not reliably detected (a known gap)", async () => { + // `customers` has `email`, so both sides expose it; the `*`'s columns are + // unknown, so `ssn as email` lands on no known output name. + const runner: ReviewRunner = { ...piiRunner(["email"]), detectPii: async () => ({ columns: ["email"] }) } + const b = "select * from customers" + const h = `${b}\nunion all\nselect id, ssn as email from secrets` + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"]]) { + const r = await run({ base: b, head: h, diff: "+union all\n+select id, ssn as email from secrets\n", reviewers, runner }) + // At most a non-blocking warning (here: the branch maps to no name, so it is undecided). + expect({ reviewers, blocks: r.verdict === "REQUEST_CHANGES", pii: r.pii.map((f) => `${f.severity}/${f.confidence}`) }).toEqual({ reviewers, blocks: false, pii: ["warning/unknown"] }) + } + }) + + test("removing one of two relations with the same table name is undecided", async () => { + const two = "select a.id, a.ssn\nfrom {{ source('crm', 'customers') }} a\njoin {{ source('erp', 'customers') }} b on a.id = b.id" + const one = "select a.id, a.ssn\nfrom {{ source('crm', 'customers') }} a" + const compiled = (side: "old" | "new") => + side === "old" + ? "select a.id, a.ssn\nfrom analytics.crm_prod.customers a\njoin analytics.erp_prod.customers b on a.id = b.id" + : "select a.id, a.ssn\nfrom analytics.crm_ci.customers a" + for (const reviewers of REVIEWER_SETS) + expectUndecided(await run({ base: two, head: one, diff: "-join {{ source('erp', 'customers') }} b on a.id = b.id\n", reviewers, runner: piiRunner(["ssn"]), compiled }), reviewers) + }) + + const b = "select customer_id,\n ssn\nfrom {{ source('crm', 'customers') }}" + const h = b.replace("select customer_id,", "select customer_id, region,") + const compiled = (side: "old" | "new") => + (side === "old" ? b : h).replace("{{ source('crm', 'customers') }}", `analytics.${side === "old" ? "dbt_prod" : "dbt_ci_42"}.customers`) + const diff = "-select customer_id,\n+select customer_id, region,\n" + const crm = "version: 2\nsources:\n - name: crm\n schema: raw\n tables:\n - name: customers\n" + const erp = "version: 2\nsources:\n - name: erp\n schema: erp_raw\n tables:\n - name: orders\n" + + test("a moved source, or an edit to an unrelated source's schema, is a warning for every `source()` (per-source comparison is a follow-up)", async () => { + const others = { + moved: [ + { path: "models/staging/_crm.yml", status: "added", diff: crm.split("\n").map((l) => `+${l}`).join("\n"), content: { new: crm } }, + { path: "models/staging/_sources.yml", status: "deleted", diff: crm.split("\n").map((l) => `-${l}`).join("\n"), content: { old: crm } }, + ], + unrelated: [{ path: "models/staging/_erp.yml", status: "modified", diff: "- schema: erp_raw\n+ schema: erp_v2\n", content: { old: erp, new: erp.replace("erp_raw", "erp_v2") } }], + } + for (const [label, files] of Object.entries(others)) + for (const reviewers of REVIEWER_SETS) + expectUndecided(await run({ base: b, head: h, diff, reviewers, runner: piiRunner(["ssn"]), compiled, others: files as any }), { label, reviewers }) + }) + + test("a comma-separated description is not a flow-mapping key", async () => { + const files = [{ path: "models/staging/_sources.yml", status: "modified", diff: "- description: raw rows\n+ description: raw rows, schema: x\n", content: { old: crm, new: crm } }] + for (const reviewers of REVIEWER_SETS) expectQuiet(await run({ base: b, head: h, diff, reviewers, runner: piiRunner(["ssn"]), compiled, others: files as any }), reviewers) + }) + + test("a pull request that edits only a source YAML gets no PII finding", async () => { + const env = await runReview({ + changedFiles: [{ path: "models/staging/_sources.yml", status: "modified", diff: "- schema: masked\n+ schema: raw\n" } as ChangedFile], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["pii_exposure", "dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: async (_f: string, side: "old" | "new") => (side === "old" ? crm.replace("raw", "masked") : crm), + }) + expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + }) +}) + +describe("a raw base read in one pass", () => { + const ref = "{{ ref('stg_customers') }}" + const go = (b: string, reviewers: string[]) => { + const h = `select customer_id,\n region,\n ssn\nfrom ${ref}` + return run({ base: b, head: h, diff: "+ ssn\n", reviewers, runner: piiRunner(["ssn"], classifyAll(/ssn/)), compiled: (side) => (side === "new" ? h.replace(ref, "analytics.stg_customers") : undefined) }) + } + + test("a mention inside a literal is kept, whatever the literal holds", async () => { + const bases = { + "backslash escape before `--`": `select customer_id,\n 'it\\'s -- ssn' as region\nfrom ${ref}`, + "`//` line inside a literal": `select customer_id,\n 'a\n// ssn\n' as region\nfrom ${ref}`, + "unclosed literal": `select customer_id,\n region -- it's\nfrom ${ref} where x = 'a`, + } + for (const [label, b] of Object.entries(bases)) + for (const reviewers of [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []]) expectUndecided(await go(b, reviewers), { label, reviewers }) + }) +}) diff --git a/packages/opencode/test/altimate/review-pii-no-change-edits.test.ts b/packages/opencode/test/altimate/review-pii-no-change-edits.test.ts index ff85dbd760..3f837b0f15 100644 --- a/packages/opencode/test/altimate/review-pii-no-change-edits.test.ts +++ b/packages/opencode/test/altimate/review-pii-no-change-edits.test.ts @@ -2,10 +2,12 @@ import { describe, test, expect } from "bun:test" import { runReview, DEFAULT_RUBRIC, DEFAULT_REVIEW_CONFIG, type ReviewRunner, type ChangedFile } from "../../src/altimate/review" // Property: an edit that cannot change which PII a model exposes never gets a -// blocking PII finding, whatever the lanes, with the base and the head compiled -// into different schemas (prod vs a CI schema) or with no compiled base. The -// exposure edits at the end are the controls: they must still be reported, so -// the property cannot hold by the check going silent. +// blocking PII finding, whatever the lanes, in each of three compile modes: the +// base compiled into another schema than the head (prod vs a CI schema, which +// also flips the sort order of a ref's and a source's schemas), the base +// compiled into the head's schema, and no compiled base. The exposure edits at +// the end are the controls: they must still be reported, so the property cannot +// hold by the check going silent. const PII = ["email", "ssn"] // Output names a PII column reaches: its aliases, else the column itself. @@ -41,13 +43,20 @@ const runnerFor = (classify: boolean): ReviewRunner => }) as any // dbt compile into one environment: a `ref` to `analytics..` (a -// version to `_v`), a `source` to `analytics._.
`. -const compile = (raw: string, env: string) => - raw +// version to `_v`), a `source` to `analytics._.
` +// (so `crm_prod` < `prod` but `ci` < `crm_ci`), and `{{ s }}` to the last +// `{% set s %}` literal, else `_db.analytics`. +const compile = (raw: string, env: string) => { + const code = raw.replace(/\{#[\s\S]*?#\}/g, "") + const literal = [...code.matchAll(/\{%\s*set\s+s\s*=\s*'([^']*)'\s*%\}/g)].pop()?.[1] + return code + .replace(/\{%[\s\S]*?%\}\n?/g, "") + .replace(/\{\{\s*s\s*\}\}/g, literal ?? `${env}_db.analytics`) .replace(/\{\{-?\s*config\([^}]*\)\s*-?\}\}\n?/g, "") .replace(/\{\{\s*ref\(\s*(['"])(\w+)\1\s*,\s*v(?:ersion)?\s*=\s*(\d+)\s*\)\s*\}\}/g, (_m, _q, m, v) => `analytics.${env}.${m}_v${v}`) .replace(/\{\{\s*ref\(\s*(?:(['"])\w+\1\s*,\s*)?(['"])(\w+)\2\s*\)\s*\}\}/g, (_m, _p, _q, m) => `analytics.${env}.${m}`) - .replace(/\{\{\s*source\(\s*(['"])(\w+)\1\s*,\s*(['"])(\w+)\3\s*\)\s*\}\}/g, (_m, _q, s, _q2, t) => `analytics.${env}_${s}.${t}`) + .replace(/\{\{\s*source\(\s*(['"])(\w+)\1\s*,\s*(['"])(\w+)\3\s*\)\s*\}\}/g, (_m, _q, s, _q2, t) => `analytics.${s}_${env}.${t}`) +} const STG = "{{ ref('stg_customers') }}" const BASES: Record = { @@ -71,6 +80,17 @@ const BASES: Record = { computedUnionStar: `with leads as (\n select * from {{ ref('stg_leads') }}\n)\nselect customer_id, email from ${STG}\nunion all\nselect customer_id, lower(email) as email from leads`, computedUnionExplicit: `with leads as (\n select customer_id, email from {{ ref('stg_leads') }}\n)\nselect customer_id, email from ${STG}\nunion all\nselect customer_id, trim(email) as email from leads`, sameNamedJoin: `select c.customer_id, lower(c.email) as email, s.signup_channel\nfrom ${STG} c\nleft join {{ source('crm', 'stg_customers') }} s on s.customer_id = c.customer_id`, + // A computed UNION branch over a table, a computed CTE column behind `*`, a + // computation qualified by its CTE's alias, one over a ref and a source, and + // a relation built from a `{% set %}` variable. + computedUnionPlain: `select customer_id, email from ${STG}\nunion all\nselect customer_id, lower(email) as email from {{ ref('stg_leads') }}`, + computedCteStar: `with c as (\n select customer_id, lower(email) as email from ${STG}\n)\nselect * from c`, + computedCteExplicit: `with c as (\n select customer_id, lower(email) as email from ${STG}\n)\nselect customer_id, email from c`, + qualifiedCte: `with customers as (\n select customer_id, email from ${STG}\n)\nselect c.customer_id, lower(c.email) as email from customers c`, + refAndSource: `select c.customer_id, lower(c.email || s.email) as email\nfrom ${STG} c\njoin {{ source('crm', 'contacts') }} s on s.customer_id = c.customer_id`, + setRelation: `{% set s = target.database ~ '.analytics' %}\nselect customer_id, ssn\nfrom {{ s }}.customers`, + // A later branch past a `*` whose columns are unknown maps to no output name. + starRefUnion: `select * from ${STG}\nunion all\nselect customer_id, email from {{ ref('stg_leads') }}`, twoCtes: `with cust as (\n select customer_id, email from ${STG}\n),\nord as (\n select customer_id, count(*) as n from {{ ref('stg_orders') }} group by 1\n)\nselect cust.customer_id, cust.email, ord.n\nfrom cust\nleft join ord on ord.customer_id = cust.customer_id`, } @@ -92,6 +112,8 @@ const SPECIFIC: Record> = { }, config: { "change materialized": BASES.config.replace("'table'", "'view'") }, stagingRenamed: { + "final `*` to explicit columns": BASES.stagingRenamed.replace("select * from renamed", "select customer_id, email, first_name from renamed"), + "add a `final as (select * from renamed)` layer": BASES.stagingRenamed.replace("\n)\nselect * from renamed", "\n),\nfinal as (\n select * from renamed\n)\nselect * from final"), "rename the final CTE": BASES.stagingRenamed.replace(/\brenamed\b/g, "final"), "rename the import CTE": BASES.stagingRenamed.replace("source as (", "src as (").replace("from source\n", "from src\n"), }, @@ -114,6 +136,30 @@ const SPECIFIC: Record> = { "rename the CTE": BASES.computedUnionExplicit.replace(/\bleads\b/g, "lead_rows"), "CTE to a subquery": `select customer_id, email from ${STG}\nunion all\nselect customer_id, trim(email) as email from (\n select customer_id, email from {{ ref('stg_leads') }}\n) leads`, }, + computedUnionPlain: { + "qualify the computed branch's columns": BASES.computedUnionPlain.replace("select customer_id, lower(email) as email from {{ ref('stg_leads') }}", "select l.customer_id, lower(l.email) as email from {{ ref('stg_leads') }} l"), + "add a non-PII join to the computed branch": BASES.computedUnionPlain.replace( + "select customer_id, lower(email) as email from {{ ref('stg_leads') }}", + "select l.customer_id, lower(l.email) as email from {{ ref('stg_leads') }} l\njoin {{ ref('regions') }} r on r.id = l.region_id", + ), + }, + computedCteStar: { + "repeat the computed CTE output explicitly after `*`": `${BASES.computedCteStar}\nunion all\nselect customer_id, email from c`, + "repeat its computation over the table after `*`": `${BASES.computedCteStar}\nunion all\nselect customer_id, lower(email) as email from ${STG}`, + "final `*` to explicit columns": BASES.computedCteExplicit, + "add a `final as (select * from c)` layer": BASES.computedCteStar.replace("\n)\nselect * from c", "\n),\nfinal as (\n select * from c\n)\nselect * from final"), + }, + computedCteExplicit: { "final explicit columns to `*`": BASES.computedCteStar }, + qualifiedCte: { + "rename the CTE, keeping the alias": BASES.qualifiedCte.replace(/\bcustomers\b/g, "src"), + "rename the alias": BASES.qualifiedCte.replace(/\bc\./g, "cu.").replace("customers c", "customers cu"), + "qualify by the CTE's name": BASES.qualifiedCte.replace(/\bc\./g, "customers.").replace("customers c", "customers"), + }, + setRelation: { + "quote style in the `{% set %}`": BASES.setRelation.replace("'.analytics'", '".analytics"'), + "parentheses in the `{% set %}`": BASES.setRelation.replace("target.database ~ '.analytics'", "(target.database ~ '.analytics')"), + "a commented-out `{% set %}`": BASES.setRelation.replace("%}\n", "%}\n{# {% set s = 'raw' %} #}\n"), + }, sameNamedJoin: { "remove the same-named relation": `select c.customer_id, lower(c.email) as email\nfrom ${STG} c`, }, @@ -158,15 +204,35 @@ const CONTROLS: Record = { BASES.computedUnionExplicit.replace(/\bleads\b/g, "lead_rows"), ], "computed branch after explicit columns": [BASES.union, `${BASES.union}\nunion all\nselect customer_id, lower(ssn) as email\nfrom {{ ref('secrets') }}`], + "computed branch unmasked while qualified": [ + BASES.computedUnionPlain.replace("lower(email)", "md5(email)"), + BASES.computedUnionPlain.replace("select customer_id, lower(email) as email from {{ ref('stg_leads') }}", "select l.customer_id, lower(l.email) as email from {{ ref('stg_leads') }} l"), + ], + "`{% set %}` literal swapped for raw": [ + "{% set s = 'masked' %}\nselect customer_id, ssn\nfrom {{ s }}.customers", + "{% set s = 'raw' %}\nselect customer_id, ssn\nfrom {{ s }}.customers", + ], } const P = "models/marts/m.sql" const LANES = [["pii_exposure", "dbt_patterns"], ["pii_exposure"], []] -// A line diff: enough for the lanes that read the added lines. +// The removed and added lines of a longest-common-subsequence line diff, in +// order: a reordered or repeated line counts. const lineDiff = (a: string, b: string) => { - const old = new Set(a.split("\n")) - const neu = new Set(b.split("\n")) - return [...a.split("\n").filter((l) => !neu.has(l)).map((l) => `-${l}`), ...b.split("\n").filter((l) => !old.has(l)).map((l) => `+${l}`)].join("\n") + "\n" + const x = a.split("\n") + const y = b.split("\n") + const lcs = Array.from({ length: x.length + 1 }, () => new Array(y.length + 1).fill(0)) + for (let i = x.length - 1; i >= 0; i--) + for (let j = y.length - 1; j >= 0; j--) lcs[i][j] = x[i] === y[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]) + const out: string[] = [] + let i = 0 + let j = 0 + while (i < x.length || j < y.length) { + if (i < x.length && j < y.length && x[i] === y[j]) (i++, j++) + else if (j < y.length && (i === x.length || lcs[i][j + 1] >= lcs[i + 1][j])) out.push(`+${y[j++]}`) + else out.push(`-${x[i++]}`) + } + return out.join("\n") + "\n" } // The compiled base: in prod while the head is in a CI schema, in the head's schema, or none. type CompiledBase = "prod" | "same" | false @@ -179,7 +245,7 @@ const review = async (base: string, head: string, reviewers: string[], compiledB runner: runnerFor(classify), getContent: async (_f: string, side: "old" | "new") => (side === "new" ? head : base), getCompiled: async (_f: string, side: "old" | "new") => - side === "new" ? compile(head, "dbt_ci_42") : compiledBase ? compile(base, compiledBase === "prod" ? "dbt_prod" : "dbt_ci_42") : undefined, + side === "new" ? compile(head, "ci") : compiledBase ? compile(base, compiledBase === "prod" ? "prod" : "ci") : undefined, }) const pii = env.findings.filter((f) => f.category === "pii_exposure") return { @@ -211,6 +277,21 @@ describe("an edit that cannot change which PII is exposed", () => { expect(failures).toEqual([]) }) + test("a reformatted or commented `*`-over-a-ref union gets no engine finding, not even a warning", async () => { + // Its later branch maps to no output name (an `unmapped` lineage record), + // which the base has too. The regex lanes, which read reformatted lines, + // are left out. + const found: unknown[] = [] + for (const edit of ["reformat", "add comments"]) + for (const reviewers of LANES.slice(0, 2)) + for (const compiledBase of ["prod", "same"] as const) { + const r = await review(BASES.starRefUnion, GENERIC[edit](BASES.starRefUnion)!, reviewers, compiledBase, true) + const engine = r.pii.filter((f) => !/\/(dbt-patterns|rule-catalog):/.test(f)) + if (engine.length) found.push({ edit, reviewers, compiledBase, findings: engine }) + } + expect(found).toEqual([]) + }) + test("while an exposure edit is still reported", async () => { const failures: unknown[] = [] for (const [label, [base, head]] of Object.entries(CONTROLS))