diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 6fdf3dd46f..a1375cb2a2 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -264,6 +264,9 @@ mode: comment # comment | gate severityThreshold: suggestion manifestPath: target/manifest.json dialect: snowflake +# portability: true # cross-engine advice. Unset: off once the engine is known + # (configured or detected). An explicit value applies even when + # the engine is unknown. Set true for multi-adapter packages. reviewers: [] # empty = risk-tier defaults; or pin lanes dataDiff: # OFF by default โ€” see "Data-diff in CI" below enabled: false @@ -283,6 +286,26 @@ rubric: skipNonProdModels: true ``` +### What the PR comment shows + +- **One summary comment**, updated in place on every push, capped at about + 5,000 characters. Critical findings come first; anything that does not fit is + counted, and the full list is always in the verdict envelope + (`altimate review --json`). Local CLI output is never truncated. +- **Repeated findings are grouped:** the same rule with the same message on + three or more models is one bullet listing the models. Local CLI output lists + every finding with its location. +- **Inline comments only on lines of the PR's diff.** Findings computed on + compiled SQL, or on unchanged lines, stay in the summary. +- **No re-posting on reruns:** each inline comment carries the finding's + fingerprint, so a push does not repeat findings already on the PR, and a + 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. + ### Risk-tier path tokens Named categories under `riskTierPathTokens` promote any diff touching a matching diff --git a/packages/opencode/src/altimate/review/config.ts b/packages/opencode/src/altimate/review/config.ts index 793121c510..9d370d8062 100644 --- a/packages/opencode/src/altimate/review/config.ts +++ b/packages/opencode/src/altimate/review/config.ts @@ -26,6 +26,14 @@ export const ReviewConfig = z.object({ dialect: z.string().default(""), /** Enable the advisory LLM reviewer lane (needs a configured model). */ ai: z.boolean().default(true), + /** + * Report cross-engine portability advice ("isn't portable across + * warehouses"). Off by default once the engine is known (from the manifest's + * adapter or `dialect`), because a project that runs on one engine gains + * nothing from it. Turn on for packages that support several adapters. + * Functions missing on the project's own engine are always reported. + */ + portability: z.boolean().optional(), /** * Data-diff: actually run base-vs-head against the warehouse (core DataParity) * and report row/value deltas. OPT-IN โ€” it costs warehouse compute and needs a diff --git a/packages/opencode/src/altimate/review/dbt-patterns.ts b/packages/opencode/src/altimate/review/dbt-patterns.ts index b9b99c1f8b..c05523fe1f 100644 --- a/packages/opencode/src/altimate/review/dbt-patterns.ts +++ b/packages/opencode/src/altimate/review/dbt-patterns.ts @@ -4,7 +4,7 @@ import { Log } from "@/altimate/util/log" import { type Finding, type Severity, type ReviewCategory, makeFinding } from "./finding" import { type ChangedFile, fileKind } from "./diff-filter" import { type Rubric, clampSeverity, exclusionReason } from "./rubric" -import { evaluateCatalog } from "./rule-catalog" +import { evaluateCatalog, selectItemColumns } from "./rule-catalog" /** Local copy to avoid a cycle with orchestrate.ts. */ function modelNameFromPath(p: string): string { @@ -109,7 +109,7 @@ interface Ctx { inMartOrReporting: boolean } -type Detector = (c: Ctx) => Finding | null +type Detector = (c: Ctx) => Finding | Finding[] | null // A line that is dbt Jinja / config rather than SQL โ€” e.g. the microbatch // `begin=(modules.datetime.datetime.now() - ...)` config kwarg, which is NOT a @@ -304,7 +304,7 @@ const PII_RE = /\b(email|ssn|social_security|phone_number|first_name|last_name|full_name|street_address|date_of_birth|dob|passport|credit_card)\b/i const detectPiiIntoMart: Detector = (c) => { if (!c.inMartOrReporting) return null - const hit = c.added.find((l) => { + const hits = c.added.filter((l) => { const s = stripComments(l) return ( PII_RE.test(s) && @@ -313,24 +313,29 @@ const detectPiiIntoMart: Detector = (c) => { ) ) }) - if (!hit) return null - // Highly-sensitive identifiers (SSN/financial/passport/DOB) into a broadly-read - // marts layer are critical; softer PII (email/phone/name) is a warning. - const sev: Severity = /\b(ssn|social_security|credit_card|passport|date_of_birth|dob)\b/i.test(hit) - ? "critical" - : "warning" - return makeFinding({ - severity: sev, - category: "pii_exposure", - title: `${c.model}: PII column added to a marts/reporting model`, - body: - "A PII-named column was added to a model in `marts/`/`reporting/`, widening PII exposure into a broadly-read " + - "layer. Confirm the column is needed here, that masking/access policy applies, and that the downstream grant is appropriate.", - file: c.file.path, - model: c.model, - confidence: "high", - evidence: { tool: "dbt-patterns", result: { rule: "pii_into_mart", line: hit.trim() } }, - ruleKey: "pii_exposure:into-mart", + // One finding per PII column token on each added line (`ssn, passport` is two): + // each carries its column, `AS` alias and line in `result` so the orchestrator + // can suppress a base-exposed column without hiding a new one beside it. They + // share a fingerprint, so dedupe keeps the most severe survivor. + return hits.flatMap((hit) => selectItemColumns(hit, PII_RE)).map(({ column, alias, line }) => { + // Highly-sensitive identifiers (SSN/financial/passport/DOB) into a broadly-read + // marts layer are critical; softer PII (email/phone/name) is a warning. + const sev: Severity = /^(ssn|social_security|credit_card|passport|date_of_birth|dob)$/i.test(column) + ? "critical" + : "warning" + return makeFinding({ + severity: sev, + category: "pii_exposure", + title: `${c.model}: PII column added to a marts/reporting model`, + body: + "A PII-named column was added to a model in `marts/`/`reporting/`, widening PII exposure into a broadly-read " + + "layer. Confirm the column is needed here, that masking/access policy applies, and that the downstream grant is appropriate.", + file: c.file.path, + model: c.model, + confidence: "high", + evidence: { tool: "dbt-patterns", result: { rule: "pii_into_mart", line, column, alias } }, + ruleKey: "pii_exposure:into-mart", + }) }) } @@ -780,8 +785,8 @@ export function detectModelPatterns(file: ChangedFile, newSql: string | undefine } const out: Finding[] = [] for (const d of MODEL_DETECTORS) { - const f = d(ctx) - if (f) out.push({ ...f, severity: clampSeverity(f.category, f.severity, f.confidence) }) + for (const f of [d(ctx) ?? []].flat()) + out.push({ ...f, severity: clampSeverity(f.category, f.severity, f.confidence) }) } // Declarative rule catalog (data-driven checks) complements the programmatic detectors. out.push(...evaluateCatalog(file, newSql, added, removed, rubric)) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 9c055e6a7b..0d73434108 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -36,8 +36,20 @@ export function verdictHeadline(env: VerdictEnvelope): string { return `${VERDICT_LABEL[env.verdict]} โ€” ${counts} (${tierLabel})` } +/** Default size budget for the posted PR comment (characters). */ +export const SUMMARY_BUDGET_CHARS = 5_000 +/** The same rule on this many models or more collapses into one bullet. */ +export const GROUP_MIN_MODELS = 3 + +export interface RenderOptions { + /** Character budget for the comment; findings beyond it are counted, not listed. + * `Infinity` renders everything (local CLI output). */ + maxChars?: number +} + /** Full PR/MR summary comment body (markdown), prefixed with the dedup marker. */ -export function renderSummary(env: VerdictEnvelope): string { +export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): string { + const maxChars = opts.maxChars ?? SUMMARY_BUDGET_CHARS const lines: string[] = [REVIEW_MARKER, "", `## ${verdictHeadline(env)}`, ""] if (env.summary.degraded) { @@ -80,33 +92,15 @@ export function renderSummary(env: VerdictEnvelope): string { lines.push(`> ๐Ÿงญ **Tier: ${env.tier}** โ€” ${shown}${overflow}`, "") } - if (!env.findings.length) { - lines.push("No issues found in the changed dbt models. ๐ŸŽ‰", "") - } else { - const grouped = groupBySeverity(env.findings) - for (const sev of ["critical", "warning", "suggestion"] as const) { - const items = grouped[sev] - if (!items.length) continue - lines.push(`### ${SEVERITY_EMOJI[sev]} ${capitalize(sev)} (${items.length})`, "") - for (const f of items) { - const loc = f.file + (f.startLine ? `:${f.startLine}` : "") - lines.push( - `- **${f.title}** \n ${oneLine(f.body)} \n \`${loc}\`${f.degraded ? " ยท _unverified_" : ""} ยท ${f.category}`, - ) - } - lines.push("") - } - } - + const tail: string[] = [] if (env.override) { - lines.push( + tail.push( `> ๐Ÿ”“ **Break-glass override** by @${env.override.by}: ${env.override.reason}`, `> (would have been \`${env.override.priorVerdict}\`)`, "", ) } - - lines.push( + tail.push( "---", `altimate dbt-pr-review ยท verdict \`${env.verdict}\`` + (env.signature ? ` ยท signed \`${env.signature.slice(0, 18)}โ€ฆ\`` : "") + @@ -115,7 +109,105 @@ export function renderSummary(env: VerdictEnvelope): string { (env.ai?.state === "ok" && env.ai.model ? ` ยท AI \`${env.ai.model}\`` : "") + "", ) - return lines.join("\n") + + if (!env.findings.length) { + lines.push("No issues found in the changed dbt models. ๐ŸŽ‰", "") + return [...lines, ...tail].join("\n") + } + + // Findings fill the budget left after the fixed parts, most severe first. + // What does not fit is counted, never silently dropped: the envelope keeps + // every finding. The reserve keeps room for the "โ€ฆ N more finding(s)" line. + const overflowReserve = 220 + let used = [...lines, ...tail].join("\n").length + overflowReserve + let hidden = 0 + const grouped = groupBySeverity(env.findings) + for (const sev of ["critical", "warning", "suggestion"] as const) { + const items = grouped[sev] + if (!items.length) continue + const heading = [`### ${SEVERITY_EMOJI[sev]} ${capitalize(sev)} (${items.length})`, ""] + // Uncapped (local) output lists every finding with its own location. + const bullets = bulletsFor(items, maxChars !== Infinity) + let headed = false + for (const b of bullets) { + const cost = b.text.length + 1 + (headed ? 0 : heading.join("\n").length + 2) + if (used + cost > maxChars) { + hidden += b.count + continue + } + if (!headed) { + lines.push(...heading) + headed = true + } + lines.push(b.text) + used += cost + } + if (headed) lines.push("") + } + if (hidden) { + lines.push( + `> โ€ฆ ${hidden} more finding(s) not shown to keep this comment short โ€” the full list is in the verdict envelope ` + + "(`altimate review --json`, or the action's `--output` artifact).", + "", + ) + } + return [...lines, ...tail].join("\n") +} + +/** Backticked names blanked, so the same rule on different models/columns + * normalizes to the same text. */ +function blankNames(s: string): string { + return s.replace(/`[^`]*`/g, "`โ€ฆ`") +} + +/** A finding's title without its leading `model: `, with backticked names + * blanked: the title half of the grouping key. */ +function groupKeyTitle(f: Finding): string { + return blankNames(f.model && f.title.startsWith(`${f.model}: `) ? f.title.slice(f.model.length + 2) : f.title) +} + +/** Render findings of one severity as bullets. With `group`, findings that say + * the same thing (same category, title and body once names are blanked) on + * GROUP_MIN_MODELS or more distinct models collapse into one bullet. */ +function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; count: number }> { + const groups = new Map() + for (const f of items) { + // The body is part of the key: one rule with different messages (e.g. a + // dialect check naming different functions) is different findings. + const key = group ? `${f.category}|${groupKeyTitle(f)}|${blankNames(oneLine(f.body))}` : f.id + const g = groups.get(key) + if (g) g.push(f) + else groups.set(key, [f]) + } + const out: Array<{ text: string; count: number }> = [] + for (const g of groups.values()) { + // Group by distinct models: several findings of one rule on the SAME model + // (e.g. two different columns) are distinct issues and stay separate bullets. + const names = [...new Set(g.map((f) => f.model ?? f.file))] + if (group && names.length >= GROUP_MIN_MODELS) { + const shown = names.slice(0, 8).map((n) => `\`${n}\``).join(", ") + const more = names.length > 8 ? ` (+${names.length - 8} more)` : "" + // Show a body verbatim only when every member says exactly that; + // otherwise its names belong to one model, so show the blanked form. + const body = g.every((f) => f.body === g[0].body) ? oneLine(g[0].body) : blankNames(oneLine(g[0].body)) + const unverified = g.some((f) => f.degraded) ? " ยท _unverified_" : "" + out.push({ + text: + `- **${groupKeyTitle(g[0])}** โ€” ${g.length} findings across ${names.length} model(s): ${shown}${more} \n` + + ` ${body} \n ${g[0].category}${unverified}`, + count: g.length, + }) + continue + } + for (const f of g) { + const loc = f.file + (f.startLine ? `:${f.startLine}` : "") + out.push({ + text: `- **${f.title}** \n ${oneLine(f.body)} \n \`${loc}\`${f.degraded ? " ยท _unverified_" : ""} ยท ${f.category}`, + count: 1, + }) + } + } + return out } /** @@ -142,6 +234,11 @@ export function coverageNotes(env: VerdictEnvelope): string[] { } if (env.scope?.outOfScopeFiles) notes.push(`${env.scope.outOfScopeFiles} changed file(s) outside the dbt project were not reviewed.`) + if (env.scope?.movedUnchangedFiles) + notes.push( + `${env.scope.movedUnchangedFiles} file(s) moved without edits; their SQL was not re-reviewed. ` + + "Folder-level config in `dbt_project.yml` (`+schema`, `+materialized`, `+tags`) can still change where and how a moved model builds.", + ) if (env.ai && env.ai.state !== "ok") { const what = { skipped: "skipped", timeout: "timed out", error: "failed" }[env.ai.state] notes.push(`Advisory AI review ${what}${env.ai.reason ? `: ${env.ai.reason}` : ""}.`) @@ -157,14 +254,70 @@ export interface InlineComment { body: string } -export function inlineComments(env: VerdictEnvelope): InlineComment[] { +/** Hidden per-finding marker on inline comments, keyed by the finding's stable + * fingerprint (rule, file, model, column โ€” not the line), so a rerun can tell + * which findings are already on the PR. */ +export function findingMarker(id: string): string { + return `` +} + +/** Finding ids already posted, read from existing inline comment bodies. */ +export function postedFindingIds(bodies: Array): Set { + const out = new Set() + for (const b of bodies) for (const m of (b ?? "").matchAll(//g)) out.add(m[1]) + return out +} + +/** Line numbers on the head side of a unified diff that GitHub accepts for an + * inline comment: added lines and context lines inside a hunk. */ +export function commentableLines(diff: string | undefined): Set { + const out = new Set() + if (!diff) return out + let right = 0 + let inHunk = false + const rows = diff.split("\n") + if (rows[rows.length - 1] === "") rows.pop() // the diff's trailing newline, not a line + for (const line of rows) { + const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line) + if (h) { + right = Number(h[1]) + inHunk = true + continue + } + // File headers (`--- a/โ€ฆ`, `+++ b/โ€ฆ`) only occur outside a hunk. + if (!inHunk || line.startsWith("\\")) continue + // A blank context line may have lost its leading space in transit. + if (line.startsWith("+") || line.startsWith(" ") || line === "") out.add(right++) + else if (!line.startsWith("-")) inHunk = false + } + return out +} + +/** + * Inline comments for findings with a line. With `commentable` (head-side + * commentable lines per file, see `commentableLines`), only lines inside the + * PR's diff hunks are kept: GitHub rejects the whole batch over one line + * outside the diff. A file with no entry has unknown hunks (GitHub omits the + * patch for large diffs): its lines are attempted, and the 422 fallback covers a + * miss. The finding keeps its line in the envelope and summary. + */ +export function inlineComments( + env: VerdictEnvelope, + alreadyPosted: Set = new Set(), + commentable?: Map>, +): InlineComment[] { return env.findings - .filter((f) => typeof f.startLine === "number") + .filter( + (f) => + typeof f.startLine === "number" && + !alreadyPosted.has(f.id) && + (!commentable?.has(f.file) || commentable.get(f.file)!.has(f.startLine)), + ) .map((f) => ({ path: f.file, line: f.startLine!, side: "RIGHT" as const, - body: `${SEVERITY_EMOJI[f.severity]} **${f.title}**\n\n${f.body}`, + body: `${SEVERITY_EMOJI[f.severity]} **${f.title}**\n\n${f.body}\n\n${findingMarker(f.id)}`, })) } diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 24cd1f92e1..1ceb9807f0 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -14,6 +14,7 @@ import { type Rubric, exclusionReason, clampSeverity } from "./rubric" import { type ReviewConfig } from "./config" import { type ReviewMode, type ReviewScope, type VerdictEnvelope, buildEnvelope, signEnvelope } from "./verdict" import { detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" +import { type SelectItemColumn, normalizeSelectLine } from "./rule-catalog" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult, safeReason } from "./ai-review" /** @@ -206,6 +207,24 @@ export interface OrchestrateInput { layout?: DbtProjectLayout /** What the review covered: base resolution and files left out of scope. */ scope?: Omit + /** Drop the regex catalog's cross-engine portability findings (single known engine). */ + suppressPortability?: boolean +} + +/** A catalog finding tagged as cross-engine portability advice. */ +export function isCatalogPortability(f: Finding): boolean { + return f.evidence?.tool === "rule-catalog" && (f.evidence.result as { portability?: boolean })?.portability === true +} + +/** + * Portability advice that is noise for a project on `dialect`: dropped unless + * the rule names the engines that support the construct and `dialect` isn't + * one of them โ€” then it is an error on this project's own engine. + */ +export function isSuppressiblePortability(f: Finding, dialect: string): boolean { + if (!isCatalogPortability(f)) return false + const worksOn = (f.evidence?.result as { worksOn?: string[] })?.worksOn + return !worksOn || worksOn.includes(dialect.toLowerCase()) } /** True when SQL text contains Jinja (`{{ }}`, `{% %}` or `{# #}`). */ @@ -395,6 +414,8 @@ async function qualityLane( sql: string | undefined, dialect: string, oldSql?: string, + /** True when `sql` is the raw file; compiled-SQL line numbers do not exist in the PR's file. */ + linesMatchFile = false, ): Promise { if (!sql || file.status === "deleted") return [] const model = modelNameFromPath(file.path) @@ -432,8 +453,8 @@ async function qualityLane( body: issue.message, file: file.path, model, - startLine: issue.line, - endLine: issue.line, + startLine: linesMatchFile ? issue.line : undefined, + endLine: linesMatchFile ? issue.line : undefined, evidence: { tool: "altimate_core.check", result: issue }, // Include the message so distinct instances of the same rule (e.g. two // different non-portable functions) don't collapse under one fingerprint. @@ -845,11 +866,6 @@ const STRUCTURAL_CATEGORY: Record = { const PII_LOW_RISK_CLASS = /^(name|address)$/i const PII_LOW_RISK_MIN_CONFIDENCE = 0.9 const PII_DEFAULT_MIN_CONFIDENCE = 0.7 -// Column-name tokens the regex PII twins (`pii_into_mart`) key off โ€” used to -// recover which column a coarse regex finding flagged so suppression can be -// column-aware (suppress only when core actually classified THAT column). -const PII_TOKEN_RE = - /\b(email|ssn|social_security|phone_number|first_name|last_name|full_name|street_address|date_of_birth|dob|passport|credit_card)\b/i async function structuralChangeLane(ctx: ModelContext, runner: ReviewRunner): Promise { if (!runner.structuralDiff) return [] @@ -1003,6 +1019,9 @@ async function piiClassifyLane( // apply (`missingGrainTestLane` also includes `intermediate`): an internal // intermediate model surfacing PII is a warning, not a hard block. const highExposureLayer = /(^|\/)(marts|reporting)\//.test(file.path) + // Without a compiled base, every head column counts as "introduced", so a + // pre-existing column can't be told apart: never escalate to critical then. + const baseUnknown = hasOldSide(file) && !ctx.engineOldSql for (const p of pii) { const classification = String(p.classification ?? "") const lowRiskClass = PII_LOW_RISK_CLASS.test(classification) @@ -1010,7 +1029,7 @@ async function piiClassifyLane( if (p.confidence < minConfidence || !p.column) continue const col = p.column.toLowerCase() const highConfidence = p.confidence >= 0.9 - const severity: Severity = highExposureLayer && highConfidence && !lowRiskClass ? "critical" : "warning" + const severity: Severity = highExposureLayer && highConfidence && !lowRiskClass && !baseUnknown ? "critical" : "warning" out.push( makeFinding({ severity: clampSeverity("pii_exposure", severity, highConfidence ? "high" : "medium"), @@ -1022,7 +1041,9 @@ async function piiClassifyLane( (p.masking ? `; suggested masking: \`${p.masking}\`.` : "."), file: file.path, model, - confidence: highConfidence ? "high" : "medium", + // 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", evidence: { tool: "altimate_core.classify_pii", result: p }, ruleKey: `pii_exposure:${col}`, }), @@ -1031,20 +1052,27 @@ async function piiClassifyLane( return { findings: out, classifiedColumns, completed: true } } -function piiLane(file: ChangedFile & { kind: string }, columns: string[]): Finding[] { +/** `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[] { if (file.status === "deleted" || !columns.length) return [] const model = modelNameFromPath(file.path) return [ makeFinding({ - severity: "critical", + severity: baseUnknown ? "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.`, + ` 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." + : ""), file: file.path, model, - confidence: "high", + // `unknown`: undecided exposure never counts toward the warning pattern. + confidence: baseUnknown ? "unknown" : "high", evidence: { tool: "schema.detect_pii", result: { columns } }, ruleKey: "pii:exposure", }), @@ -1117,7 +1145,8 @@ export async function runReview(input: OrchestrateInput): Promise 0 ? !anyManifest : reviewable.length === 0 + // Nothing to resolve (yml-only, pure moves) is not a lint-only run. + const runDegraded = modelFiles.length > 0 && !anyManifest // High-risk path tokens are user-configured (billing/pci/patient/etc.) โ€” // the reviewer core carries no default list. `undefined` when no @@ -1182,11 +1211,16 @@ export async function runReview(input: OrchestrateInput): Promise() const diffScopedPiiFindingFiles = new Set() const classifiedPiiColumnsByFile = new Map>() + // Per file: PII columns the compiled base already exposed. Neither the broad + // fallback nor the regex twins report these (this PR did not expose them). + const basePiiColumnsByFile = new Map>() for (const ctx of ctxByPath.values()) { const tasks: Promise[] = [] // Engine lanes consume COMPILED SQL (rendered by dbt) when available. if (lanes.has("sql_quality") || lanes.has("warehouse_cost")) - tasks.push(qualityLane(ctx.file, input.runner, ctx.engineNewSql, dialect, ctx.engineOldSql)) + tasks.push( + qualityLane(ctx.file, input.runner, ctx.engineNewSql, dialect, ctx.engineOldSql, ctx.engineNewSql === ctx.newSql), + ) if (lanes.has("semantic_change")) { tasks.push(dataDiffLane(ctx, input.runner, dialect, input.config.dataDiff)) tasks.push(grainMismatchLane(ctx, input.runner)) @@ -1223,15 +1257,29 @@ export async function runReview(input: OrchestrateInput): Promise() + if (hasOldSide(currentCtx.file) && currentCtx.engineOldSql) { + try { + basePii = new Set( + (await input.runner.detectPii(currentCtx.engineOldSql, dialect)).columns.map((c) => c.toLowerCase()), + ) + } catch { + /* unknown base exposure: report as if new */ + } + basePiiColumnsByFile.set(currentCtx.file.path, basePii) + } if (lanes.has("pii_exposure")) { // The broad fallback covers output PII columns the precise lane did NOT // classify (pre-existing columns, or ones core's classifier missed) โ€” // dedup against the columns core actually CONSIDERED, never all // introduced columns, so a missed column still surfaces here. - const fallbackPii = diffScopedPii.completed + let fallbackPii = diffScopedPii.completed ? currentCtx.pii.filter((col) => !diffScopedPii.classifiedColumns.has(col.toLowerCase())) : currentCtx.pii - findings.push(...piiLane(currentCtx.file, fallbackPii)) + // The fallback reports only columns the base did not already expose. + fallbackPii = fallbackPii.filter((col) => !basePii.has(col.toLowerCase())) + const baseUnknown = hasOldSide(currentCtx.file) && !currentCtx.engineOldSql + findings.push(...piiLane(currentCtx.file, fallbackPii, baseUnknown)) } return findings })(), @@ -1353,6 +1401,25 @@ export async function runReview(input: OrchestrateInput): Promise>() + const isReindented = (file: string, line: string) => { + let removed = removedLinesByFile.get(file) + if (!removed) { + removed = new Set(splitDiff(ctxByPath.get(file)?.file.diff).removed.map(normalizeSelectLine).filter(Boolean)) + removedLinesByFile.set(file, removed) + } + const normalized = normalizeSelectLine(line) + return !!normalized && removed.has(normalized) + } + // `detectPii` reports OUTPUT names (`c.ssn as tax_ref` โ†’ `tax_ref`): a column is + // already exposed when the base output holds its alias, or the source column + // itself (a rename of an exposed column re-exposes nothing new). + const isBaseExposed = (file: string, item: { column: string; alias?: string }) => { + const basePii = basePiiColumnsByFile.get(file) + return !!basePii && (basePii.has(item.column) || (!!item.alias && basePii.has(item.alias))) + } const merged = flat.filter((f) => { const tool = f.evidence?.tool const fallbackRule = String((f.evidence?.result as any)?.rule ?? "").replace(/_/g, "-") @@ -1368,20 +1435,32 @@ export async function runReview(input: OrchestrateInput): Promise isReindented(f.file, i.line) || isBaseExposed(f.file, i))) return false + // Otherwise suppress only when a precise detector actually EMITTED a PII + // finding for the file (so the exposure is reported by the better source, + // not silently dropped). if (diffScopedPiiFindingFiles.has(f.file)) return false return true } @@ -1408,6 +1487,16 @@ export async function runReview(input: OrchestrateInput): Promise !exclusionReason(f, input.rubric)) + // Cross-engine portability advice from the regex catalog is noise for a + // project that runs on one known engine. Core's dialect-aware check (a + // function missing on THIS engine) is a real error and is kept. + if (input.suppressPortability) findings = findings.filter((f) => !isSuppressiblePortability(f, dialect)) const minSev = SEVERITY_ORDER[input.config.severityThreshold] findings = findings.filter((f) => SEVERITY_ORDER[f.severity] >= minSev) // Sort by severity desc, then file. diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index 9ef43286f5..fb3010d8c1 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -1,7 +1,14 @@ import { Octokit } from "@octokit/rest" import { promises as fs } from "node:fs" import { type VerdictEnvelope, VCS_EVENT } from "./verdict" -import { renderSummary, inlineComments, REVIEW_MARKER, verdictHeadline } from "./format" +import { + commentableLines, + inlineComments, + postedFindingIds, + renderSummary, + REVIEW_MARKER, + verdictHeadline, +} from "./format" /** * Post a verdict envelope to a GitHub pull request: an upserted summary comment @@ -50,14 +57,26 @@ export async function resolveGitHubTarget(): Promise { export interface PostResult { summaryCommentId?: number reviewId?: number - /** True when inline comments were dropped due to a 422 positioning error. */ + /** True when some or all inline comments were dropped due to a 422 positioning error. */ inlineFellBack: boolean /** Set when the review event could not be posted for a non-positioning reason. */ postError?: string + /** Inline comments not re-posted because the same finding is already on the PR. */ + inlineSkippedAsPosted?: number + /** True when no review was submitted: nothing new inline, the verdict is not + * blocking, and this bot's latest review already carries the same headline + * (the summary comment was updated). */ + reviewSkipped?: boolean } -export async function postGitHubReview(env: VerdictEnvelope, target: GitHubTarget): Promise { - const octo = new Octokit({ auth: target.token }) +/** Headline of a review this bot posted (see verdictHeadline). */ +const BOT_REVIEW_RE = /(Approved|Reviewed with comments|Changes requested)\b.*\((trivial|lite|full) tier/ + +export async function postGitHubReview( + env: VerdictEnvelope, + target: GitHubTarget, + octo: Octokit = new Octokit({ auth: target.token }), +): Promise { const { owner, repo, prNumber } = target const result: PostResult = { inlineFellBack: false } @@ -72,22 +91,61 @@ export async function postGitHubReview(env: VerdictEnvelope, target: GitHubTarge per_page: 100, }) const prior = existing.find((c) => c.body?.includes(REVIEW_MARKER)) - if (prior) { - const r = await octo.rest.issues.updateComment({ owner, repo, comment_id: prior.id, body: summary }) - result.summaryCommentId = r.data.id - } else { - const r = await octo.rest.issues.createComment({ owner, repo, issue_number: prNumber, body: summary }) - result.summaryCommentId = r.data.id - } + const upserted = prior + ? await octo.rest.issues.updateComment({ owner, repo, comment_id: prior.id, body: summary }) + : await octo.rest.issues.createComment({ owner, repo, issue_number: prNumber, body: summary }) + result.summaryCommentId = upserted.data.id + // The account this token posts as: the summary comment's author. + const botLogin = upserted.data.user?.login // 2. Post a review. `env.verdict` arrives already mode-gated from // buildEnvelope (comment mode softened REQUEST_CHANGES โ†’ COMMENT upstream); // this map only translates verdict โ†’ GitHub event. APPROVE always maps to a // COMMENT event โ€” the bot must never submit a formal GitHub approval. const event = VCS_EVENT[env.verdict] - const comments = inlineComments(env) const reviewBody = verdictHeadline(env) + // Rerun dedup: a finding already commented inline (same fingerprint, which + // ignores line numbers) is not posted again on the next push. + let posted = new Set() + let lastBotHeadline: string | undefined + try { + const [reviewComments, reviews] = await Promise.all([ + octo.paginate(octo.rest.pulls.listReviewComments, { owner, repo, pull_number: prNumber, per_page: 100 }), + octo.paginate(octo.rest.pulls.listReviews, { owner, repo, pull_number: prNumber, per_page: 100 }), + ]) + posted = postedFindingIds(reviewComments.map((c) => c.body)) + // Reviews are listed oldest first; only this bot's own latest review counts. + const mine = botLogin + ? reviews.filter((r) => r.user?.login === botLogin && BOT_REVIEW_RE.test(r.body ?? "")) + : [] + lastBotHeadline = mine.at(-1)?.body?.trim() + } catch { + /* listing failed: post everything rather than nothing */ + } + + // Inline comments only on lines GitHub accepts (inside the PR's diff hunks). + // If the file list can't be read, or a file has no `patch` (GitHub omits it + // for large diffs), post those lines and rely on the 422 fallback. + let commentable: Map> | undefined + try { + const files = await octo.paginate(octo.rest.pulls.listFiles, { owner, repo, pull_number: prNumber, per_page: 100 }) + commentable = new Map(files.filter((f) => f.patch).map((f) => [f.filename, commentableLines(f.patch)])) + } catch { + /* fall back to the positioning retry below */ + } + const comments = inlineComments(env, posted, commentable) + result.inlineSkippedAsPosted = inlineComments(env, new Set(), commentable).length - comments.length + + // Nothing new inline, not blocking, and this bot's latest review already says + // the same thing: the updated summary comment covers it; another identical + // timeline entry per push is noise. A blocking verdict always posts, and a + // changed headline (e.g. after "Changes requested") posts a new review. + if (!comments.length && event === "COMMENT" && lastBotHeadline === reviewBody) { + result.reviewSkipped = true + return result + } + // Anchor inline comments to the PR head commit. Without commit_id, GitHub's // line-positioning is fragile and can 422 even on valid lines. let commitId: string | undefined @@ -122,6 +180,27 @@ export async function postGitHubReview(env: VerdictEnvelope, target: GitHubTarge const isPositioning = status === 422 && /(position|\bline\b|diff|commit)/.test(detail) result.inlineFellBack = isPositioning result.postError = isPositioning ? undefined : `${status ?? ""} ${e?.message ?? e}`.trim() + // Lines on files without a known hunk (no `patch`) are the likely cause of a + // positioning 422: retry once with only the comments on verified files + // before dropping every inline comment. + const verified = isPositioning && commentable ? comments.filter((c) => commentable!.has(c.path)) : [] + if (verified.length && verified.length < comments.length) { + try { + const r = await octo.rest.pulls.createReview({ + owner, + repo, + pull_number: prNumber, + commit_id: commitId, + event, + body: reviewBody, + comments: verified, + }) + result.reviewId = r.data.id + return result + } catch { + /* fall through to the event-only review */ + } + } try { const r = await octo.rest.pulls.createReview({ owner, diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 0d8313c458..4d3ef71a89 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -44,6 +44,17 @@ export interface Rule { unless?: RegExp kind?: RuleKind pathGlob?: RegExp + /** + * Cross-engine portability advice: dropped for a project on one known + * engine, unless that engine is missing from `worksOn` (then it is a real + * error there and is kept). Omit `worksOn` when support isn't established. + */ + portability?: { worksOn?: string[] } + /** Column-token pattern (first capture group is the column name) collected on + * every line `added` matches โ€” every token, not just the first โ€” and kept on + * `evidence.result.columns` / `items` so the orchestrator can reconcile each + * column (and its `AS` alias) with the base. */ + capturesColumns?: RegExp example: RuleExample counter?: RuleExample } @@ -101,6 +112,77 @@ export function ruleMatches(rule: Rule, input: RuleInput): boolean { return relevant } +/** A column token found in a select item, with the item's `AS` alias (the + * output name) when it has one, and the trimmed line it came from. */ +export interface SelectItemColumn { + column: string + alias?: string + line: string +} + +/** Split on commas outside parentheses (one entry per select item). */ +function topLevelItems(s: string): string[] { + const items: string[] = [] + let depth = 0 + let start = 0 + for (let i = 0; i < s.length; i++) { + if (s[i] === "(") depth++ + else if (s[i] === ")") depth = Math.max(0, depth - 1) + else if (s[i] === "," && depth === 0) { + items.push(s.slice(start, i)) + start = i + 1 + } + } + items.push(s.slice(start)) + return items +} + +/** + * Every column token `tokenRe` finds on a select line (all of them, not just + * the first), each paired with its item's `AS` alias. The pair matters because + * PII detection reports OUTPUT names: `c.ssn as tax_ref` exposes `tax_ref`. + */ +export function selectItemColumns(line: string, tokenRe: RegExp): SelectItemColumn[] { + const global = new RegExp(tokenRe.source, tokenRe.flags.includes("g") ? tokenRe.flags : `${tokenRe.flags}g`) + const out: SelectItemColumn[] = [] + const seen = new Set() + for (const item of topLevelItems(stripComments(line))) { + // The item's alias is its first `AS` outside parentheses (`cast(x as int) as y` + // โ†’ `y`), which also holds when the line runs on into `from โ€ฆ`. + let flat = item + while (/\([^()]*\)/.test(flat)) flat = flat.replace(/\([^()]*\)/g, " ") + const alias = /\bas\s+["`]?([A-Za-z_][\w$]*)/i.exec(flat)?.[1]?.toLowerCase() + for (const m of item.matchAll(global)) { + const column = m[1]?.toLowerCase() + if (!column || seen.has(`${column} ${alias ?? ""}`)) continue + seen.add(`${column} ${alias ?? ""}`) + out.push({ column, alias, line: line.trim() }) + } + } + return out +} + +/** A diff line with comments and whitespace normalised (and a leading/trailing + * select-list comma dropped), so a reindented line compares equal to its base. */ +export function normalizeSelectLine(line: string): string { + return stripComments(line) + .replace(/\s+/g, " ") + .replace(/\s*([(),])\s*/g, "$1") + .trim() + .replace(/^,|,$/g, "") +} + +/** Column tokens (with aliases) of `rule.capturesColumns` over the added lines `rule.added` matches. */ +function capturedColumns(rule: Rule, added: string[]): SelectItemColumn[] { + const out: SelectItemColumn[] = [] + for (const l of added) { + const s = stripComments(l) + if (!rule.capturesColumns || !rule.added?.test(s) || rule.unless?.test(s)) continue + out.push(...selectItemColumns(l, rule.capturesColumns)) + } + return out +} + /** Evaluate the catalog against a changed file. */ export function evaluateCatalog( file: ChangedFile, @@ -122,7 +204,17 @@ export function evaluateCatalog( file: file.path, model, confidence: "high", - evidence: { tool: "rule-catalog", result: { rule: rule.id } }, + evidence: { + tool: "rule-catalog", + result: rule.portability + ? { rule: rule.id, portability: true, worksOn: rule.portability.worksOn } + : rule.capturesColumns + ? (() => { + const items = capturedColumns(rule, added) + return { rule: rule.id, columns: [...new Set(items.map((i) => i.column))], items } + })() + : { rule: rule.id }, + }, ruleKey: `${rule.category}:${rule.id}`, }) if (!exclusionReason(f, rubric)) matched.push({ rule, finding: f }) @@ -167,7 +259,7 @@ const r = ( severity: Severity, title: string, body: string, - match: Pick, + match: Pick, example: RuleExample, counter?: RuleExample, ): Rule => ({ id, category, severity, title, body, ...match, example, counter }) @@ -585,7 +677,7 @@ const AGG: Rule[] = [ "suggestion", "COUNT(DISTINCT a, b) portability", "Multi-column COUNT(DISTINCT) isn't supported on all warehouses; concat or use a subquery.", - { added: /count\s*\(\s*distinct\s+[^),]+,/i }, + { added: /count\s*\(\s*distinct\s+[^),]+,/i, portability: { worksOn: ["mysql", "snowflake", "databricks"] } }, { add: "count(distinct a, b)" }, { add: "count(distinct a)" }, ), @@ -1193,7 +1285,10 @@ const SECURITY_PII: Rule[] = [ "warning", "PII columns selected", "Email/SSN/phone/DOB pulled into a model widens PII exposure; confirm it's needed and masked.", - { added: /^\s*[\w.]*\b(ssn|social_security|email|phone_number|date_of_birth|passport)\b/i }, + { + added: /^\s*[\w.]*\b(ssn|social_security|email|phone_number|date_of_birth|passport)\b/i, + capturesColumns: /\b(ssn|social_security|email|phone_number|date_of_birth|passport)\b/i, + }, { add: " c.ssn," }, { add: " c.country," }, ), @@ -1703,7 +1798,7 @@ const STYLE: Rule[] = [ "suggestion", "PIVOT/UNPIVOT is dialect-specific", "`PIVOT`/`UNPIVOT` syntax varies by warehouse and is hard to test; consider conditional aggregation.", - { added: /\b(pivot|unpivot)\s*\(/i }, + { added: /\b(pivot|unpivot)\s*\(/i, portability: {} }, { add: "from t pivot(sum(x) for k in ('a'))" }, { add: "sum(case when k='a' then x end)" }, ), @@ -1723,7 +1818,7 @@ const STYLE: Rule[] = [ "suggestion", "GROUP BY on a SELECT alias", "Grouping by a select-list alias isn't portable (errors on some warehouses); repeat the expression.", - { added: /\bgroup\s+by\s+\w+_(amt|amount|total|cnt|count)\b/i }, + { added: /\bgroup\s+by\s+\w+_(amt|amount|total|cnt|count)\b/i, portability: { worksOn: ["snowflake", "bigquery", "postgres", "redshift", "databricks", "duckdb", "mysql", "clickhouse"] } }, { add: "group by total_amount" }, { add: "group by customer_id" }, ), @@ -1733,7 +1828,7 @@ const STYLE: Rule[] = [ "suggestion", "string interval literal portability", "`interval '1 day'` literal syntax differs across warehouses; prefer dateadd/date_add functions.", - { added: /interval\s+'\d+\s*\w+'/i }, + { added: /interval\s+'\d+\s*\w+'/i, portability: {} }, { add: "d + interval '1 day'" }, { add: "dateadd(day, 1, d)" }, ), @@ -1743,10 +1838,22 @@ const STYLE: Rule[] = [ "suggestion", "integer arithmetic on a date", "`date + 7` (bare int) isn't portable and is ambiguous (days? seconds?); use dateadd/interval.", - { added: /\b\w*(date|_at|_dt)\b\s*[+\-]\s*\d+\b/i }, + { added: /\b\w*(date|_dt)\b\s*[+\-]\s*\d+\b/i, portability: { worksOn: ["postgres", "redshift", "snowflake", "duckdb", "oracle"] } }, { add: "select order_date + 7" }, { add: "select dateadd(day, 7, order_date)" }, ), + // Split from date-plus-int: `timestamp + integer` has no operator on most + // engines that accept `date + integer` (Postgres, Snowflake, DuckDB). + r( + "timestamp-plus-int", + "sql_correctness", + "suggestion", + "integer arithmetic on a timestamp", + "`updated_at + 1` (bare int on a timestamp) fails on most warehouses and is ambiguous (days? seconds?); use dateadd/interval.", + { added: /\b\w*_at\b\s*[+\-]\s*\d+\b/i, portability: { worksOn: ["oracle"] } }, + { add: "select updated_at + 1" }, + { add: "select dateadd(day, 1, updated_at)" }, + ), ] const MISC: Rule[] = [ @@ -1866,7 +1973,7 @@ const MISC: Rule[] = [ "suggestion", "DISTINCT ON is Postgres-specific", "`DISTINCT ON (โ€ฆ)` isn't portable; use `qualify row_number()` for first-row-per-group.", - { added: /distinct\s+on\s*\(/i }, + { added: /distinct\s+on\s*\(/i, portability: { worksOn: ["postgres", "duckdb"] } }, { add: "select distinct on (id) * from t" }, { add: "qualify row_number() over (partition by id order by d) = 1" }, ), @@ -1876,7 +1983,7 @@ const MISC: Rule[] = [ "suggestion", "FETCH FIRST portability", "`FETCH FIRST n ROWS` isn't supported everywhere; `LIMIT` (with ORDER BY) is more portable.", - { added: /fetch\s+first\s+\d+/i }, + { added: /fetch\s+first\s+\d+/i, portability: { worksOn: ["postgres", "snowflake", "oracle", "trino"] } }, { add: "fetch first 10 rows only" }, { add: "limit 10" }, ), @@ -2299,7 +2406,7 @@ const MISC2: Rule[] = [ "suggestion", "non-portable type name (TEXT)", "`cast(x as text)` isn't supported on all warehouses; use `string`/`varchar`.", - { added: /\bas\s+text\b/i }, + { added: /\bas\s+text\b/i, portability: { worksOn: ["postgres", "redshift", "duckdb", "snowflake"] } }, { add: "cast(x as text)" }, { add: "cast(x as string)" }, ), diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 508f4108b6..f2d68f39ca 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -318,7 +318,9 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise // Resolve the SQL dialect: explicit config wins; otherwise auto-detect from // the dbt manifest's `adapter_type` (so a BigQuery/Redshift project isn't // analyzed as the snowflake default โ€” wrong-dialect portability suppression). - if (!config.dialect) config.dialect = (await detectDialect(manifestAbs)) ?? "snowflake" + const detectedDialect = config.dialect ? undefined : await detectDialect(manifestAbs) + const dialectKnown = !!config.dialect || !!detectedDialect + if (!config.dialect) config.dialect = detectedDialect ?? "snowflake" // Prefer dbt's catalog.json (real warehouse columns from `dbt docs generate`) // for the schema context โ€” complete columns are what make column-lineage @@ -393,6 +395,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise forceTier: opts.forceTier, staleManifest, layout, + suppressPortability: shouldSuppressPortability(config.portability, dialectKnown), scope: { baseRef: resolved?.ref ?? opts.base, baseSha: resolved?.sha, @@ -404,6 +407,13 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise }) } +/** Drop cross-engine portability advice? An explicit `portability` setting + * wins (even when the engine is unknown); unset, drop it once the engine is + * known (configured or detected from the manifest). */ +export function shouldSuppressPortability(portability: boolean | undefined, dialectKnown: boolean): boolean { + return portability === undefined ? dialectKnown : !portability +} + /** * The pull/merge request's title and description from the CI environment, so * the AI lane can check the change against its stated intent. GitHub: the diff --git a/packages/opencode/src/altimate/review/telemetry.ts b/packages/opencode/src/altimate/review/telemetry.ts index 34016e8a50..3fbe4af1bb 100644 --- a/packages/opencode/src/altimate/review/telemetry.ts +++ b/packages/opencode/src/altimate/review/telemetry.ts @@ -71,7 +71,8 @@ export function classifyReviewFailure(err: unknown): "config_error" | "git_error * caller reports `summary_failed` for that. */ export function classifyPostOutcome(result: PostResult): "full" | "partial" { - if (result.inlineFellBack || result.postError || result.reviewId === undefined) return "partial" + if (result.inlineFellBack || result.postError) return "partial" + if (result.reviewId === undefined && !result.reviewSkipped) return "partial" return "full" } diff --git a/packages/opencode/src/altimate/tools/dbt-pr-review.ts b/packages/opencode/src/altimate/tools/dbt-pr-review.ts index ab3ceab013..47d68a6549 100644 --- a/packages/opencode/src/altimate/tools/dbt-pr-review.ts +++ b/packages/opencode/src/altimate/tools/dbt-pr-review.ts @@ -77,7 +77,7 @@ export const DbtPrReviewTool = Tool.define("dbt_pr_review", { signature: env.signature, findingCount: env.findings.length, }, - output: renderSummary(env), + output: renderSummary(env, { maxChars: Infinity }), } }, }) diff --git a/packages/opencode/src/cli/cmd/review.ts b/packages/opencode/src/cli/cmd/review.ts index e35556aa0b..cef6942c20 100644 --- a/packages/opencode/src/cli/cmd/review.ts +++ b/packages/opencode/src/cli/cmd/review.ts @@ -153,7 +153,8 @@ export const ReviewCommand = cmd({ if (args.json) { process.stdout.write(JSON.stringify(env, null, 2) + "\n") } else { - process.stdout.write(renderSummary(env) + "\n") + // Local output is complete; the size budget applies to the posted comment. + process.stdout.write(renderSummary(env, { maxChars: Infinity }) + "\n") } if (args.post) { @@ -191,7 +192,9 @@ export const ReviewCommand = cmd({ } else { UI.println( `Posted review to ${where}` + - (r.inlineFellBack ? " (inline comments fell back to summary-only)" : ""), + (r.inlineFellBack ? " (inline comments fell back to summary-only)" : "") + + (r.inlineSkippedAsPosted ? ` (${r.inlineSkippedAsPosted} inline already on the PR)` : "") + + (r.reviewSkipped ? " (summary updated; no new review needed)" : ""), ) } } diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts new file mode 100644 index 0000000000..fe111bc0a3 --- /dev/null +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -0,0 +1,557 @@ +import { describe, test, expect } from "bun:test" +import { + isCatalogPortability, + isSuppressiblePortability, + runReview, + type ReviewRunner, +} from "../../src/altimate/review/orchestrate" +import { DEFAULT_REVIEW_CONFIG } from "../../src/altimate/review/config" +import { DEFAULT_RUBRIC } from "../../src/altimate/review/rubric" +import { makeFinding, type Finding } from "../../src/altimate/review/finding" +import { + commentableLines, + findingMarker, + inlineComments, + postedFindingIds, + renderSummary, + SUMMARY_BUDGET_CHARS, +} from "../../src/altimate/review/format" +import { buildEnvelope } from "../../src/altimate/review/verdict" +import { verdictHeadline } from "../../src/altimate/review/format" +import { evaluateCatalog } from "../../src/altimate/review/rule-catalog" +import { classifyPostOutcome } from "../../src/altimate/review/telemetry" +import { postGitHubReview } from "../../src/altimate/review/post-github" +import { shouldSuppressPortability } from "../../src/altimate/review/run" + +/** + * The PR comment must stay readable: inline comments land on real lines of the + * PR's file and are not re-posted on every push, a rule repeated across many + * models is one bullet, the comment has a size budget, and cross-engine + * portability advice is dropped for a single-engine project. + */ + +function finding(over: Partial[0]> = {}): Finding { + return makeFinding({ + severity: "suggestion", + category: "test_coverage", + title: "m: new model has no uniqueness/grain test", + body: "Add a unique or unique_combination_of_columns test.", + file: "models/m.sql", + model: "m", + confidence: "high", + evidence: { tool: "test-coverage", result: {} }, + ...over, + }) +} + +const DIFF = [ + "diff --git a/models/m.sql b/models/m.sql", + "--- a/models/m.sql", + "+++ b/models/m.sql", + "@@ -1,4 +1,5 @@", + " select", + " id", + "- , old_col", + "+ , new_col", + "+ , other_col", + "", + " from src", +].join("\n") + +describe("inline anchors", () => { + test("commentable lines are the head-side added and context lines inside hunks", () => { + // 1 select, 2 id, 3 new_col, 4 other_col, 5 blank context, 6 from src + expect([...commentableLines(DIFF)].sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 6]) + expect(commentableLines(undefined).size).toBe(0) + }) + + test("an added SQL line starting with `++` still counts; headers outside hunks do not", () => { + const d = "--- a/x.sql\n+++ b/x.sql\n@@ -0,0 +1,2 @@\n+select 1\n++ 1 as weird\n" + expect([...commentableLines(d)].sort()).toEqual([1, 2]) + }) + + test("a line outside the diff is not posted inline but keeps its location in the envelope", () => { + const inDiff = finding({ startLine: 3, endLine: 3, title: "m: a" }) + const outside = finding({ startLine: 40, endLine: 40, title: "m: b" }) + const env = buildEnvelope({ findings: [inDiff, outside], tier: "lite", mode: "comment" }) + const commentable = new Map([["models/m.sql", commentableLines(DIFF)]]) + expect(inlineComments(env, new Set(), commentable).map((c) => c.line)).toEqual([3]) + // Without diff information every line is attempted (the 422 fallback covers it). + expect(inlineComments(env).map((c) => c.line)).toEqual([3, 40]) + expect(env.findings.find((f) => f.title === "m: b")!.startLine).toBe(40) + expect(renderSummary(env, { maxChars: Infinity })).toContain("`models/m.sql:40`") + }) + + test("engine lint on compiled SQL never anchors to the raw file", async () => { + const runner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [{ rule: "select-star", message: "avoid select *", severity: "warning", line: 2 }], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, + } as ReviewRunner + const env = await runReview({ + changedFiles: [{ path: "models/m.sql", status: "added", diff: "@@ -0,0 +1,3 @@\n+{{ config() }}\n+select *\n+from {{ ref('a') }}\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["sql_quality"] }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + getContent: async () => "{{ config() }}\nselect *\nfrom {{ ref('a') }}\n", + getCompiled: async () => "\n\n\nselect *\nfrom db.a\n", + }) + const f = env.findings.find((x) => x.evidence?.tool === "altimate_core.check") + expect(f).toBeDefined() + expect(f!.startLine).toBeUndefined() + }) +}) + +describe("inline dedup across pushes", () => { + test("inline bodies carry the finding fingerprint, which ignores the line", () => { + const a = finding({ startLine: 3 }) + const moved = finding({ startLine: 9 }) + expect(a.id).toBe(moved.id) + const env = buildEnvelope({ findings: [a], tier: "lite", mode: "comment" }) + expect(inlineComments(env)[0].body).toContain(findingMarker(a.id)) + }) + + test("findings already commented on the PR are not posted again", () => { + const a = finding({ startLine: 3, title: "m: a" }) + const b = finding({ startLine: 4, title: "m: b" }) + const env = buildEnvelope({ findings: [a, b], tier: "lite", mode: "comment" }) + const posted = postedFindingIds(["๐Ÿ›‘ old\n\n" + findingMarker(a.id), null, "human comment"]) + expect([...posted]).toEqual([a.id]) + expect(inlineComments(env, posted).map((c) => c.line)).toEqual([4]) + }) + + test("a skipped repeat review counts as a full post in telemetry", () => { + expect(classifyPostOutcome({ inlineFellBack: false, reviewSkipped: true })).toBe("full") + expect(classifyPostOutcome({ inlineFellBack: false })).toBe("partial") + }) +}) + +describe("summary grouping and budget", () => { + test("the same rule on three or more models is one bullet listing the models", () => { + const fs = ["a", "b", "c", "d"].map((m) => + finding({ model: m, file: `models/${m}.sql`, title: `${m}: new model has no uniqueness/grain test` }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md.match(/no uniqueness\/grain test/g)?.length).toBe(1) + expect(md).toContain("4 findings across 4 model(s): `a`, `b`, `c`, `d`") + }) + + test("two occurrences stay as separate bullets", () => { + const fs = ["a", "b"].map((m) => finding({ model: m, file: `models/${m}.sql`, title: `${m}: new model has no uniqueness/grain test` })) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md.match(/no uniqueness\/grain test/g)?.length).toBe(2) + }) + + test("several findings of one rule on the same model are not collapsed", () => { + const fs = ["a_id", "b_id", "c_id"].map((c) => + finding({ model: "m", file: "models/m.sql", title: `m: grain column \`${c}\` lacks not_null`, category: "test_coverage" }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).not.toContain("findings across") + for (const c of ["a_id", "b_id", "c_id"]) expect(md).toContain(c) + }) + + test("backticked column names do not split a group", () => { + const fs = ["a", "b", "c"].map((m) => + finding({ model: m, file: `models/${m}.sql`, title: `${m}: grain column \`${m}_id\` lacks not_null`, category: "test_coverage" }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).toContain("3 findings across 3 model(s)") + }) + + test("one rule with different messages per model is not merged into the first message", () => { + const fs = [ + ["a", "ILIKE"], + ["b", "QUALIFY"], + ["c", "IFF"], + ].map(([m, fn], i) => + finding({ + severity: "warning", + category: "sql_quality", + model: m, + file: `models/${m}.sql`, + startLine: i + 1, + title: `${m}: dialect-unsupported-function`, + body: `${fn} is not supported on the target dialect.`, + degraded: m === "c", + }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).not.toContain("findings across") + for (const fn of ["ILIKE", "QUALIFY", "IFF"]) expect(md).toContain(`${fn} is not supported`) + for (const loc of ["models/a.sql:1", "models/b.sql:2", "models/c.sql:3"]) expect(md).toContain(loc) + expect(md).toContain("_unverified_") + }) + + test("a grouped bullet keeps _unverified_ when any member is degraded", () => { + const fs = ["a", "b", "c"].map((m) => + finding({ model: m, file: `models/${m}.sql`, title: `${m}: new model has no uniqueness/grain test`, degraded: m === "b" }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).toContain("3 findings across 3 model(s)") + expect(md).toMatch(/findings across[^\n]*\n[^\n]*\n\s*test_coverage ยท _unverified_<\/sub>/) + }) + + test("a grouped body that names one model's column shows the names blanked", () => { + const fs = ["a", "b", "c"].map((m) => + finding({ + model: m, + file: `models/${m}.sql`, + title: `${m}: grain column lacks not_null`, + body: `Column \`${m}_id\` has no not_null test.`, + }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).toContain("3 findings across 3 model(s)") + expect(md).toContain("Column `โ€ฆ` has no not_null test.") + expect(md).not.toContain("`a_id`") + }) + + test("more than eight models: the posted comment lists eight, local output lists every finding", () => { + const ms = Array.from({ length: 11 }, (_, i) => `m${i}`) + const fs = ms.map((m) => finding({ model: m, file: `models/${m}.sql`, title: `${m}: new model has no uniqueness/grain test` })) + const env = buildEnvelope({ findings: fs, tier: "lite", mode: "comment" }) + const md = renderSummary(env) + expect(md).toContain("11 findings across 11 model(s)") + expect(md).toContain("(+3 more)") + expect(md).not.toContain("`m8`") + const local = renderSummary(env, { maxChars: Infinity }) + expect(local).not.toContain("findings across") + for (const m of ms) expect(local).toContain(`\`models/${m}.sql\``) + }) + + test("the posted comment stays within budget, most severe first, and counts what it hides", () => { + const many: Finding[] = [] + for (let i = 0; i < 200; i++) + many.push( + finding({ + severity: i < 3 ? "critical" : "suggestion", + category: i < 3 ? "lineage_breakage" : "sql_quality", + model: `m${i}`, + file: `models/m${i}.sql`, + title: `m${i}: distinct issue number ${i}`, + body: "x".repeat(120), + }), + ) + const env = buildEnvelope({ findings: many, tier: "full", mode: "comment" }) + const md = renderSummary(env) + expect(md.length).toBeLessThanOrEqual(SUMMARY_BUDGET_CHARS) + expect(md).toContain("m0: distinct issue number 0") + expect(md).toMatch(/โ€ฆ \d+ more finding\(s\) not shown/) + // Local output is complete. + expect(renderSummary(env, { maxChars: Infinity })).toContain("m199: distinct issue number 199") + }) +}) + +describe("portability noise", () => { + const portability = finding({ + severity: "suggestion", + category: "sql_quality", + title: "m: DISTINCT ON isn't portable", + body: "`DISTINCT ON (โ€ฆ)` isn't portable; use `qualify row_number()` for first-row-per-group.", + evidence: { tool: "rule-catalog", result: { rule: "distinct-on", portability: true, worksOn: ["postgres", "duckdb"] } }, + }) + const coreMissing = finding({ + category: "sql_quality", + title: "m: non_portable_function", + body: "GETDATE() is a non-standard / dialect-specific function.", + evidence: { tool: "altimate_core.check", result: { rule: "non_portable_function" } }, + }) + + test("only explicitly tagged rules are portability advice, not rules that mention standard SQL", async () => { + const legacy = evaluateCatalog( + { path: "models/m.sql", status: "added" }, + "select * from [proj:ds.t]", + ["select * from [proj:ds.t]"], + [], + DEFAULT_RUBRIC, + ).find((f) => (f.evidence?.result as { rule: string }).rule === "bq-legacy-sql") + expect(legacy).toBeDefined() + expect(isCatalogPortability(legacy!)).toBe(false) + }) + + test("a construct that fails on the project's own engine is kept", () => { + expect(isSuppressiblePortability(portability, "postgres")).toBe(true) + expect(isSuppressiblePortability(portability, "snowflake")).toBe(false) + const untagged = { ...portability, evidence: { tool: "rule-catalog", result: { rule: "pivot-portability", portability: true } } } + expect(isSuppressiblePortability(untagged, "snowflake")).toBe(true) + }) + + test("catalog portability advice is recognised; core's dialect-aware check is not", () => { + expect(isCatalogPortability(portability)).toBe(true) + expect(isCatalogPortability(coreMissing)).toBe(false) + }) + + test("a single known engine drops portability advice it supports, keeps what fails on it", async () => { + const runner = { + async impact() { + return { hasManifest: true, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async grade() { + return { grade: "B" } + }, + async check() { + return { issues: [], ran: true } + }, + async equivalence() { + return { decided: true, equivalent: true } + }, + async detectPii() { + return { columns: [] } + }, + } as ReviewRunner + const sql = "select distinct on (customer_id) customer_id, order_id from orders" + const base = { + changedFiles: [{ path: "models/m.sql", status: "added" as const, diff: `+${sql}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"], dialect: "snowflake" }, + rubric: DEFAULT_RUBRIC, + mode: "comment" as const, + runner, + getContent: async () => sql, + } + const kept = await runReview(base) + expect(kept.findings.filter(isCatalogPortability).length).toBeGreaterThan(0) + // Postgres supports DISTINCT ON: the advice is noise there and is dropped. + const pg = { ...base, config: { ...base.config, dialect: "postgres" } } + expect((await runReview({ ...pg, suppressPortability: true })).findings.filter(isCatalogPortability).length).toBe(0) + // Snowflake doesn't: on a Snowflake project it is a real error and stays. + expect((await runReview({ ...base, suppressPortability: true })).findings.filter(isCatalogPortability).length).toBeGreaterThan(0) + }) +}) + +describe("moved files", () => { + test("moves are named in the comment with the folder-config caveat, and are not a lint-only run", async () => { + const env = buildEnvelope({ + findings: [], + tier: "trivial", + mode: "comment", + scope: { movedUnchangedFiles: 3 } as any, + }) + expect(renderSummary(env)).toContain("3 file(s) moved without edits") + expect(renderSummary(env)).toContain("`+schema`") + }) +}) + +describe("postGitHubReview", () => { + const BOT = "github-actions[bot]" + const target = { token: "t", owner: "o", repo: "r", prNumber: 7 } + const PATCH = DIFF.split("\n").slice(3).join("\n") + + function fakeOcto( + opts: { + reviews?: Array<{ body: string; user?: { login: string } }> + listFails?: boolean + files?: Array<{ filename: string; patch?: string }> + createReview?: (call: number) => unknown + } = {}, + ) { + const reviewCalls: any[] = [] + const fail = async () => { + throw new Error("listing failed") + } + const octo = { + paginate: async (fn: (p: unknown) => unknown, p: unknown) => fn(p), + rest: { + issues: { + listComments: async () => [], + createComment: async () => ({ data: { id: 1, user: { login: BOT } } }), + updateComment: async () => ({ data: { id: 1, user: { login: BOT } } }), + }, + pulls: { + listReviewComments: opts.listFails ? fail : async () => [], + listReviews: opts.listFails ? fail : async () => opts.reviews ?? [], + listFiles: opts.listFails ? fail : async () => opts.files ?? [{ filename: "models/m.sql", patch: PATCH }], + get: async () => ({ data: { head: { sha: "abc" } } }), + createReview: async (p: any) => { + reviewCalls.push(p) + const r = opts.createReview?.(reviewCalls.length) + return r ?? { data: { id: 9 } } + }, + }, + }, + } + return { octo: octo as any, reviewCalls } + } + + const noLine = buildEnvelope({ findings: [finding()], tier: "lite", mode: "comment" }) + + test("skips a new review when this bot's latest review has the same headline", async () => { + const { octo, reviewCalls } = fakeOcto({ + reviews: [ + { body: "๐Ÿ›‘ Changes requested โ€” 1 critical (lite tier)", user: { login: BOT } }, + { body: verdictHeadline(noLine), user: { login: BOT } }, + ], + }) + const r = await postGitHubReview(noLine, target, octo) + expect(r.reviewSkipped).toBe(true) + expect(reviewCalls.length).toBe(0) + }) + + test("posts a new review when this bot's latest review requested changes", async () => { + const { octo, reviewCalls } = fakeOcto({ + reviews: [ + { body: verdictHeadline(noLine), user: { login: BOT } }, + { body: "๐Ÿ›‘ Changes requested โ€” 1 critical (lite tier)", user: { login: BOT } }, + ], + }) + const r = await postGitHubReview(noLine, target, octo) + expect(r.reviewSkipped).toBeUndefined() + expect(reviewCalls.length).toBe(1) + expect(reviewCalls[0].event).toBe("COMMENT") + }) + + test("another account's review with the same headline does not count", async () => { + const { octo, reviewCalls } = fakeOcto({ reviews: [{ body: verdictHeadline(noLine), user: { login: "someone" } }] }) + const r = await postGitHubReview(noLine, target, octo) + expect(r.reviewSkipped).toBeUndefined() + expect(reviewCalls.length).toBe(1) + }) + + test("inline comments go only to lines inside the PR diff", async () => { + const env = buildEnvelope({ + findings: [finding({ startLine: 3, title: "m: a" }), finding({ startLine: 40, title: "m: b" })], + tier: "lite", + mode: "comment", + }) + const { octo, reviewCalls } = fakeOcto() + const r = await postGitHubReview(env, target, octo) + expect(reviewCalls[0].comments.map((c: { line: number }) => c.line)).toEqual([3]) + expect(r.inlineSkippedAsPosted).toBe(0) + }) + + test("a file GitHub lists without a patch keeps its inline comments", async () => { + // GitHub omits `patch` for large diffs: the hunks are unknown, so the lines + // are attempted (the 422 fallback covers a miss) instead of all dropped. + const env = buildEnvelope({ + findings: [ + finding({ startLine: 3, title: "m: a" }), + finding({ startLine: 40, title: "m: b" }), + finding({ file: "models/big.sql", startLine: 900, title: "big: c" }), + ], + tier: "lite", + mode: "comment", + }) + const { octo, reviewCalls } = fakeOcto({ + files: [{ filename: "models/m.sql", patch: PATCH }, { filename: "models/big.sql" }], + }) + await postGitHubReview(env, target, octo) + expect(reviewCalls[0].comments.map((c: { path: string; line: number }) => `${c.path}:${c.line}`)).toEqual([ + "models/m.sql:3", + "models/big.sql:900", + ]) + }) + + test("when listing fails, everything is posted and nothing is skipped", async () => { + const env = buildEnvelope({ + findings: [finding({ startLine: 3, title: "m: a" }), finding({ startLine: 40, title: "m: b" })], + tier: "lite", + mode: "comment", + }) + const { octo, reviewCalls } = fakeOcto({ listFails: true, reviews: [{ body: verdictHeadline(env), user: { login: BOT } }] }) + const r = await postGitHubReview(env, target, octo) + expect(r.reviewSkipped).toBeUndefined() + expect(reviewCalls[0].comments.map((c: { line: number }) => c.line)).toEqual([3, 40]) + }) + + test("a positioning 422 retries the review without inline comments", async () => { + const env = buildEnvelope({ findings: [finding({ startLine: 3 })], tier: "lite", mode: "comment" }) + const { octo, reviewCalls } = fakeOcto({ + createReview: (call) => { + if (call === 1) + throw Object.assign(new Error("Unprocessable Entity"), { + status: 422, + response: { data: { errors: ["Line could not be resolved"] } }, + }) + return undefined + }, + }) + const r = await postGitHubReview(env, target, octo) + expect(reviewCalls.length).toBe(2) + expect(reviewCalls[0].comments.length).toBe(1) + expect(reviewCalls[1].comments).toBeUndefined() + expect(r.inlineFellBack).toBe(true) + expect(r.postError).toBeUndefined() + expect(r.reviewId).toBe(9) + }) + + test("a positioning 422 with a patchless file retries with the verified comments first", async () => { + const env = buildEnvelope({ + findings: [ + finding({ file: "models/known.sql", startLine: 3, title: "known: a" }), + finding({ file: "models/big.sql", startLine: 900, title: "big: b" }), + ], + tier: "lite", + mode: "comment", + }) + const positioning422 = Object.assign(new Error("Unprocessable Entity"), { + status: 422, + response: { data: { errors: ["Line could not be resolved"] } }, + }) + const where = (call: any) => (call.comments ?? []).map((c: { path: string; line: number }) => `${c.path}:${c.line}`) + const files = [{ filename: "models/known.sql", patch: PATCH }, { filename: "models/big.sql" }] + + const kept = fakeOcto({ + files, + createReview: (call) => { + if (call === 1) throw positioning422 + return undefined + }, + }) + const r = await postGitHubReview(env, target, kept.octo) + expect(kept.reviewCalls.map(where)).toEqual([["models/known.sql:3", "models/big.sql:900"], ["models/known.sql:3"]]) + expect(r.inlineFellBack).toBe(true) + expect(r.postError).toBeUndefined() + expect(r.reviewId).toBe(9) + + // The verified-only retry also failing falls back to an event-only review. + const none = fakeOcto({ + files, + createReview: (call) => { + if (call <= 2) throw positioning422 + return undefined + }, + }) + const r2 = await postGitHubReview(env, target, none.octo) + expect(none.reviewCalls.length).toBe(3) + expect(none.reviewCalls[2].comments).toBeUndefined() + expect(r2.inlineFellBack).toBe(true) + expect(r2.reviewId).toBe(9) + }) +}) + +describe("portability settings", () => { + test("unset follows whether the engine is known; an explicit value always wins", () => { + expect(shouldSuppressPortability(undefined, true)).toBe(true) + expect(shouldSuppressPortability(undefined, false)).toBe(false) + expect(shouldSuppressPortability(false, false)).toBe(true) + expect(shouldSuppressPortability(true, true)).toBe(false) + }) + + test("integer arithmetic on a timestamp is kept on Postgres; on a date it is not", () => { + const rule = (sql: string, id: string) => + evaluateCatalog({ path: "models/m.sql", status: "added" }, sql, [sql], [], DEFAULT_RUBRIC).find( + (f) => (f.evidence?.result as { rule: string }).rule === id, + ) + const ts = rule("select updated_at + 1 from t", "timestamp-plus-int") + expect(ts).toBeDefined() + expect(rule("select updated_at + 1 from t", "date-plus-int")).toBeUndefined() + expect(isSuppressiblePortability(ts!, "postgres")).toBe(false) + expect(isSuppressiblePortability(ts!, "snowflake")).toBe(false) + const date = rule("select order_date + 7 from t", "date-plus-int") + expect(date).toBeDefined() + expect(isSuppressiblePortability(date!, "postgres")).toBe(true) + }) +}) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 113a2202fd..f5ef7843be 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -1967,8 +1967,8 @@ describe("orchestrate", () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+email\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["email", "ssn"] } + async detectPii(sql: string) { + return { columns: ["email", "ssn"].filter((c) => sql.includes(c)) } }, } const env = await runReview({ @@ -1977,7 +1977,7 @@ describe("orchestrate", () => { rubric: DEFAULT_RUBRIC, mode: "gate", runner, - getContent: content("select email, ssn from x"), + getContent: content("select email, ssn from x", "select id from x"), }) const pii = env.findings.find((f) => f.category === "pii_exposure") expect(pii).toBeDefined() @@ -2024,7 +2024,7 @@ describe("orchestrate", () => { expect(env.verdict).toBe("REQUEST_CHANGES") }) - test("broad PII detector remains fallback for existing output columns", async () => { + test("a PII column the base already exposed is not re-flagged when the PR only touches it", async () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ lower(email) as email\n" }] const runner: ReviewRunner = { ...fakeRunner({}), @@ -2056,18 +2056,18 @@ describe("orchestrate", () => { runner, getContent: content("select customer_id, lower(email) as email from customers", "select customer_id, email from customers"), }) + // `email` was already in the base's output: this PR does not newly expose it. const pii = env.findings.filter((f) => f.category === "pii_exposure") - expect(pii).toHaveLength(1) - expect(pii[0].evidence?.tool).toBe("schema.detect_pii") - expect(env.verdict).toBe("REQUEST_CHANGES") + expect(pii).toHaveLength(0) + expect(env.verdict).not.toBe("REQUEST_CHANGES") }) test("PII fallback survives core lineage failure instead of aborting review", async () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ email\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["email"] } + async detectPii(sql: string) { + return { columns: sql.includes("email") ? ["email"] : [] } }, async columnLineage() { throw new Error("lineage parser crashed") @@ -2098,8 +2098,8 @@ describe("orchestrate", () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ email\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["email"] } + async detectPii(sql: string) { + return { columns: sql.includes("email") ? ["email"] : [] } }, async columnLineage(sql) { return sql.includes("email") @@ -2127,6 +2127,293 @@ describe("orchestrate", () => { expect(env.verdict).toBe("REQUEST_CHANGES") }) + test("without a compiled base, head PII may predate the PR: reported as a non-blocking warning", async () => { + const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ lower(email) as email\n" }] + const runner: ReviewRunner = { + ...fakeRunner({}), + async detectPii(sql: string) { + return { columns: sql.includes("email") ? ["email"] : [] } + }, + async columnLineage(sql) { + return [ + { source: "customers.customer_id", target: "customer_id" }, + ...(sql.includes("email") ? [{ source: "customers.email", target: "email" }] : []), + ] + }, + async classifyPii(columns) { + return columns.map((column) => ({ column, classification: "Email", confidence: 0.95 })) + }, + } + const env = await runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner, + // The base is raw Jinja with no compiled artifact: it cannot be analysed. + getContent: content( + "select customer_id, lower(email) as email from customers", + "select customer_id, email from {{ ref('customers') }}", + ), + }) + const pii = env.findings.filter((f) => f.category === "pii_exposure") + expect(pii.length).toBeGreaterThan(0) + expect(pii.every((f) => f.severity !== "critical")).toBe(true) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + }) + + test("PII warnings without a compiled base never add up to a block", async () => { + // Three head PII columns, base not compilable: each is a warning of undecided + // exposure and must not count toward the warning-pattern threshold. + const files: ChangedFile[] = [ + { path: "models/marts/dim_customers.sql", status: "modified", diff: "+ email,\n+ ssn,\n+ phone_number\n" }, + ] + const PII = ["email", "ssn", "phone_number"] + const runner: ReviewRunner = { + ...fakeRunner({}), + async detectPii(sql: string) { + return { columns: PII.filter((c) => sql.includes(c)) } + }, + async columnLineage(sql) { + return ["customer_id", ...PII].filter((c) => sql.includes(c)).map((c) => ({ source: `customers.${c}`, target: c })) + }, + async classifyPii(columns) { + return columns + .filter((c) => PII.includes(c)) + .map((column) => ({ column, classification: column === "email" ? "Email" : column === "ssn" ? "SSN" : "Phone", confidence: 0.95 })) + }, + } + const env = await runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner, + getContent: content( + "select customer_id, email, ssn, phone_number from customers", + "select customer_id from {{ ref('customers') }}", + ), + }) + const pii = env.findings.filter((f) => f.category === "pii_exposure") + expect(pii.length).toBeGreaterThanOrEqual(3) + expect(pii.every((f) => f.severity === "warning" && f.confidence === "unknown")).toBe(true) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + }) + + // Output names of `col` in `sql`, like the real engine: `c.ssn as tax_ref` + // exposes `tax_ref` (runner.ts prefers query_targets), plain `ssn` exposes `ssn`. + 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] : [] + } + // Runner whose base/head PII is exactly the listed columns present in the SQL, + // reported by output name (alias) as `runner.detectPii` does. + const piiRunner = (cols: string[], classify: ReviewRunner["classifyPii"] = async () => []): ReviewRunner => ({ + ...fakeRunner({}), + async detectPii(sql: string) { + return { columns: cols.flatMap((c) => outputNames(sql, c)) } + }, + async columnLineage(sql) { + return ["customer_id", ...cols].flatMap((c) => + outputNames(sql, c).map((target) => ({ source: `customers.${c}`, target })), + ) + }, + classifyPii: classify, + }) + const isTwin = (f: { evidence?: { tool?: string; result?: unknown } }) => + ["pii_into_mart", "select-pii-columns"].includes((f.evidence?.result as any)?.rule) + const MARTS = ["models/marts/m1.sql", "models/marts/m2.sql", "models/marts/m3.sql"] + + test("a reindented PII line the base already exposed raises no regex twin", async () => { + // Whitespace-only edit of the `ssn` line in three marts: base and head expose + // the same columns, so neither the broad fallback nor either regex twin + // applies, and three of them do not add up to a block. + const files: ChangedFile[] = MARTS.map((path) => ({ path, status: "modified", diff: "- ssn\n+ ssn\n" })) + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id,\n ssn\nfrom customers"), + }) + expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + } + // Control: the same head with a base that lacked `ssn` still gets both twins. + const added = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "+ ssn\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id\nfrom customers"), + }) + const rules = added.findings.filter(isTwin).map((f) => (f.evidence?.result as any)?.rule) + expect(rules.sort()).toEqual(["pii_into_mart", "select-pii-columns"]) + }) + + test("a new PII column next to a reindented base one keeps its own critical twin", async () => { + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn\n+ ssn,\n+ passport\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn", "passport"]), + getContent: content( + "select customer_id,\n ssn,\n passport\nfrom customers", + "select customer_id,\n ssn\nfrom customers", + ), + }) + const twin = env.findings.find((f) => (f.evidence?.result as any)?.rule === "pii_into_mart") + expect(twin?.severity).toBe("critical") + expect((twin?.evidence?.result as any)?.line).toContain("passport") + // `select-pii-columns` names a column the base lacked, so it is kept too. + const catalog = env.findings.find((f) => (f.evidence?.result as any)?.rule === "select-pii-columns") + expect((catalog?.evidence?.result as any)?.columns).toEqual(["ssn", "passport"]) + }) + + const ALIASED_BASE = "select c.customer_id,\n c.email as contact,\n c.ssn as tax_ref\nfrom customers c" + + test("a reindented aliased PII column in three marts raises no twin and does not block", async () => { + // detectPii reports output aliases (`contact`, `tax_ref`), not the source + // tokens the regex twins match (`email`, `ssn`): both must be reconciled. + const cases = [ + { line: "c.ssn as tax_ref", head: ALIASED_BASE.replace(" c.ssn", " c.ssn") }, + { line: "c.email as contact,", head: ALIASED_BASE.replace(" c.email", " c.email") }, + ] + for (const { line, head } of cases) { + const files: ChangedFile[] = MARTS.map((path) => ({ path, status: "modified", diff: `- ${line}\n+ ${line}\n` })) + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["email", "ssn"]), + getContent: content(head, ALIASED_BASE), + }) + expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + } + } + }) + + test("an aliased PII line whose alias the base exposes raises no twin even when not a pure reindent", async () => { + // Table alias renamed `c` โ†’ `cust`: the line text changes, but the output + // `tax_ref` (built from `ssn`) was already exposed by the base. + const head = ALIASED_BASE.replace(/\bc\./g, "cust.").replace("customers c", "customers cust") + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- c.ssn as tax_ref\n+ cust.ssn as tax_ref\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["email", "ssn"]), + getContent: content(head, ALIASED_BASE), + }) + expect(env.findings.filter(isTwin)).toEqual([]) + // Control: the same aliased line added to a base without it keeps both twins. + const added = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "+ c.ssn as tax_ref\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["email", "ssn"]), + getContent: content(ALIASED_BASE, "select c.customer_id,\n c.email as contact\nfrom customers c"), + }) + const twins = added.findings.filter(isTwin) + expect(twins.map((f) => (f.evidence?.result as any)?.rule).sort()).toEqual(["pii_into_mart", "select-pii-columns"]) + expect(twins.find((f) => (f.evidence?.result as any)?.rule === "pii_into_mart")?.severity).toBe("critical") + }) + + test("a pure reindent drops the regex twins even when base PII detection misses the column", async () => { + // detectPii finds nothing on either side: only the reindent check applies. + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn\n+ ssn\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner([]), + getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id,\n ssn\nfrom customers"), + }) + expect(env.findings.filter(isTwin)).toEqual([]) + }) + + test("a new PII column on the same line as a base-exposed one keeps its twins", async () => { + // `- ssn` / `+ ssn, passport`: `ssn` is base-exposed, `passport` is new and + // must not hide behind the first token on the line. + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn\n+ ssn, passport\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn", "passport"]), + getContent: content("select customer_id,\n ssn, passport\nfrom customers", "select customer_id,\n ssn\nfrom customers"), + }) + const intoMart = env.findings.filter((f) => (f.evidence?.result as any)?.rule === "pii_into_mart") + expect(intoMart.map((f) => (f.evidence?.result as any)?.column)).toEqual(["passport"]) + expect(intoMart[0].severity).toBe("critical") + const catalog = env.findings.find((f) => (f.evidence?.result as any)?.rule === "select-pii-columns") + expect((catalog?.evidence?.result as any)?.columns).toEqual(["ssn", "passport"]) + // Both tokens already in the base: nothing is reported. + const both = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn,\n- passport\n+ ssn, passport\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn", "passport"]), + getContent: content( + "select customer_id,\n ssn, passport\nfrom customers", + "select customer_id,\n ssn,\n passport\nfrom customers", + ), + }) + expect(both.findings.filter(isTwin)).toEqual([]) + }) + + test("without a compiled base the regex PII twins are unknown-confidence warnings that never block", async () => { + // Raw Jinja on both sides and no compiled artifacts: whether an added `ssn` + // line is new cannot be decided (it is not a reindent of a removed line), so + // neither twin is critical or counts toward a block. + const files: ChangedFile[] = MARTS.map((path) => ({ path, status: "modified", diff: "+ ssn\n" })) + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content( + "select customer_id,\n ssn\nfrom {{ ref('customers') }}", + "select customer_id,\n ssn\nfrom {{ ref('customers') }}", + ), + }) + const twins = env.findings.filter(isTwin) + if (reviewers.length) expect(twins.length).toBeGreaterThan(0) + expect(twins.every((f) => f.severity === "warning" && f.confidence === "unknown")).toBe(true) + expect(env.findings.filter((f) => f.severity === "critical")).toEqual([]) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + } + }) + + 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") + expect(fallback.length).toBe(1) + expect(fallback[0].severity).toBe("warning") + expect(fallback[0].confidence).toBe("unknown") + }) + test("case-variant PII detector output does not duplicate core diff-scoped finding", async () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ Email as EMAIL\n" }] const runner: ReviewRunner = { @@ -2205,8 +2492,8 @@ describe("orchestrate", () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ ssn\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["ssn"] } + async detectPii(sql: string) { + return { columns: sql.includes("ssn") ? ["ssn"] : [] } }, async columnLineage(sql) { return sql.includes("ssn") @@ -2241,8 +2528,8 @@ describe("orchestrate", () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ ssn\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["ssn"] } + async detectPii(sql: string) { + return { columns: sql.includes("ssn") ? ["ssn"] : [] } }, async columnLineage(sql) { return sql.includes("ssn") @@ -2280,8 +2567,8 @@ describe("orchestrate", () => { const files: ChangedFile[] = [{ path: "models/marts/dim_customers.sql", status: "modified", diff: "+ ssn\n" }] const runner: ReviewRunner = { ...fakeRunner({}), - async detectPii() { - return { columns: ["ssn"] } + async detectPii(sql: string) { + return { columns: sql.includes("ssn") ? ["ssn"] : [] } }, async columnLineage() { // Lineage resolves but derives zero output columns for every input.