From 0c4e2c667927eb215ab1201c7d1fcb51c8b933e3 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Thu, 12 Nov 2026 16:35:36 +0530 Subject: [PATCH 01/81] fix(review): a readable PR comment: diff-anchored inline comments, no reposts, grouped rules, size budget, new-only PII, no portability noise - Inline comments only on head-side lines inside the file's diff hunks; engine findings computed on compiled SQL no longer carry raw-file lines. Anything else moves to the summary instead of 422-ing the whole batch. - Each inline comment carries `` (the line-independent fingerprint); a rerun skips findings already on the PR, and a non-blocking rerun with nothing new only updates the summary. - The same rule on 3+ models collapses into one bullet listing the models. - The posted summary has a ~5K-character budget, most severe first, with a count of what was left out (the envelope keeps everything); CLI and agent tool output stay complete. - The PII fallback flags only columns the change newly exposes, not columns the base already surfaced. - Cross-engine portability advice from the regex catalog is dropped once the engine is known (`portability: true` in review.yml re-enables it for multi-adapter packages); core's dialect-aware check is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 18 ++ .../opencode/src/altimate/review/config.ts | 8 + .../opencode/src/altimate/review/format.ts | 143 +++++++++-- .../src/altimate/review/orchestrate.ts | 76 +++++- .../src/altimate/review/post-github.ts | 37 ++- packages/opencode/src/altimate/review/run.ts | 5 +- .../opencode/src/altimate/review/telemetry.ts | 3 +- .../src/altimate/tools/dbt-pr-review.ts | 2 +- packages/opencode/src/cli/cmd/review.ts | 7 +- .../test/altimate/review-noise.test.ts | 235 ++++++++++++++++++ .../opencode/test/altimate/review.test.ts | 26 +- 11 files changed, 510 insertions(+), 50 deletions(-) create mode 100644 packages/opencode/test/altimate/review-noise.test.ts diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 6fdf3dd46f..58d85cb715 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -264,6 +264,8 @@ mode: comment # comment | gate severityThreshold: suggestion manifestPath: target/manifest.json dialect: snowflake +portability: false # cross-engine advice; default off once the engine is known + # (set true for packages that support several adapters) reviewers: [] # empty = risk-tier defaults; or pin lanes dataDiff: # OFF by default — see "Data-diff in CI" below enabled: false @@ -283,6 +285,22 @@ 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 rules are grouped:** the same rule on three or more models is one + bullet listing the models. +- **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 only updates the summary. +- **PII:** flagged only for PII columns the change newly exposes, not for + columns the base already surfaced. + ### 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/format.ts b/packages/opencode/src/altimate/review/format.ts index 9c055e6a7b..778ab2acae 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 = 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,90 @@ 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. + 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})`, ""] + const bullets = bulletsFor(items) + 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") +} + +/** A finding's title without its leading `model: `, with backticked names + * blanked, so the same rule on different models/columns shares a key. */ +function ruleTitle(f: Finding): string { + const t = f.model && f.title.startsWith(`${f.model}: `) ? f.title.slice(f.model.length + 2) : f.title + return t.replace(/`[^`]*`/g, "`…`") +} + +/** Render findings of one severity as bullets; a rule repeated on GROUP_MIN or + * more models collapses into a single bullet listing the models. */ +function bulletsFor(items: Finding[]): Array<{ text: string; count: number }> { + const groups = new Map() + for (const f of items) { + const key = `${f.category}|${ruleTitle(f)}` + 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()) { + if (g.length >= GROUP_MIN) { + const names = [...new Set(g.map((f) => f.model ?? f.file))] + const shown = names.slice(0, 8).map((n) => `\`${n}\``).join(", ") + const more = names.length > 8 ? ` (+${names.length - 8} more)` : "" + out.push({ + text: + `- **${ruleTitle(g[0])}** — ${g.length} findings across ${names.length} model(s): ${shown}${more} \n` + + ` ${oneLine(g[0].body)} \n ${g[0].category}`, + 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 } /** @@ -157,14 +234,28 @@ 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 +} + +export function inlineComments(env: VerdictEnvelope, alreadyPosted: Set = new Set()): InlineComment[] { return env.findings - .filter((f) => typeof f.startLine === "number") + .filter((f) => typeof f.startLine === "number" && !alreadyPosted.has(f.id)) .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..04b055bfb1 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -206,6 +206,57 @@ 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 +} + +const PORTABILITY_RE = /portab|dialect[ -]specific|non-?standard|n't standard|not standard|standard sql/i + +/** A regex-catalog finding whose concern is portability across warehouses. */ +export function isCatalogPortability(f: Finding): boolean { + const tool = f.evidence?.tool + return (tool === "rule-catalog" || tool === "dbt-patterns") && PORTABILITY_RE.test(`${f.title} ${f.body}`) +} + +/** 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 +} + +/** + * Keep a finding's line only when it can be commented on: inside the file's + * diff hunks on the head side. Anything else (a line from compiled SQL, an + * unchanged region) moves to the summary instead of making GitHub reject the + * whole batch of inline comments. + */ +export function anchorToDiff(findings: Finding[], files: ChangedFile[]): Finding[] { + const lines = new Map(files.map((f) => [f.path, commentableLines(f.diff)])) + return findings.map((f) => { + if (typeof f.startLine !== "number") return f + if (lines.get(f.file)?.has(f.startLine)) return f + const { startLine: _s, endLine: _e, ...rest } = f + return rest as Finding + }) } /** True when SQL text contains Jinja (`{{ }}`, `{% %}` or `{# #}`). */ @@ -395,6 +446,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 +485,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. @@ -1186,7 +1239,9 @@ export async function runReview(input: OrchestrateInput): 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)) @@ -1228,9 +1283,17 @@ export async function runReview(input: OrchestrateInput): Promise !diffScopedPii.classifiedColumns.has(col.toLowerCase())) : currentCtx.pii + // Only columns this PR newly exposes: a PII column the base already + // surfaced is not this change's concern (the docs promise "newly expose"). + if (fallbackPii.length && hasOldSide(currentCtx.file) && currentCtx.engineOldSql) { + const basePii = new Set( + (await input.runner.detectPii(currentCtx.engineOldSql, dialect)).columns.map((c) => c.toLowerCase()), + ) + fallbackPii = fallbackPii.filter((col) => !basePii.has(col.toLowerCase())) + } findings.push(...piiLane(currentCtx.file, fallbackPii)) } return findings @@ -1448,6 +1511,11 @@ 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) => !isCatalogPortability(f)) + findings = anchorToDiff(findings, input.changedFiles) 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..9a34c83199 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -1,7 +1,7 @@ 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 { renderSummary, inlineComments, postedFindingIds, REVIEW_MARKER, verdictHeadline } from "./format" /** * Post a verdict envelope to a GitHub pull request: an upserted summary comment @@ -54,8 +54,16 @@ export interface PostResult { 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 to say and a previous + * non-blocking altimate review already exists (the summary comment was updated). */ + reviewSkipped?: boolean } +/** 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): Promise { const octo = new Octokit({ auth: target.token }) const { owner, repo, prNumber } = target @@ -85,9 +93,34 @@ export async function postGitHubReview(env: VerdictEnvelope, target: GitHubTarge // 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 priorBotReview = false + 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)) + priorBotReview = reviews.some((r) => BOT_REVIEW_RE.test(r.body ?? "")) + } catch { + /* listing failed: post everything rather than nothing */ + } + const comments = inlineComments(env, posted) + const withLine = env.findings.filter((f) => typeof f.startLine === "number").length + result.inlineSkippedAsPosted = withLine - comments.length + + // Nothing new inline, not blocking, and the PR already has an altimate + // review: the updated summary comment says it all; another "Reviewed with + // comments" entry per push is noise. A blocking verdict always posts. + if (!comments.length && event === "COMMENT" && priorBotReview) { + 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 diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index 508f4108b6..c6a86b7925 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: config.portability === undefined ? dialectKnown : !config.portability, scope: { baseRef: resolved?.ref ?? opts.base, baseSha: resolved?.sha, 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..ae64c9a67e --- /dev/null +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -0,0 +1,235 @@ +import { describe, test, expect } from "bun:test" +import { + anchorToDiff, + commentableLines, + isCatalogPortability, + 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 { + findingMarker, + inlineComments, + postedFindingIds, + renderSummary, + SUMMARY_BUDGET_CHARS, +} from "../../src/altimate/review/format" +import { buildEnvelope } from "../../src/altimate/review/verdict" +import { classifyPostOutcome } from "../../src/altimate/review/telemetry" + +/** + * 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 moves to the summary instead of failing the batch", () => { + const inDiff = finding({ startLine: 3, endLine: 3, title: "m: a" }) + const outside = finding({ startLine: 40, endLine: 40, title: "m: b" }) + const [a, b] = anchorToDiff([inDiff, outside], [{ path: "models/m.sql", status: "modified", diff: DIFF }]) + expect(a.startLine).toBe(3) + expect(b.startLine).toBeUndefined() + expect(b.endLine).toBeUndefined() + }) + + 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("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("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: {} }, + }) + 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("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 catalog portability findings", 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) + const dropped = await runReview({ ...base, suppressPortability: true }) + const before = kept.findings.filter(isCatalogPortability).length + expect(before).toBeGreaterThan(0) + expect(dropped.findings.filter(isCatalogPortability).length).toBe(0) + }) +}) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 113a2202fd..2ec9445a26 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") @@ -2205,8 +2205,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") From 147c38da51e8302a89a16ad51ccdad55ec5692cc Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 13 Nov 2026 11:07:42 +0530 Subject: [PATCH 02/81] fix(review): portability advice is an explicit tag, kept when it fails on the project's own engine; moved files are named - catalog rules carry `portability: { worksOn? }` instead of the comment text being matched: `bq-legacy-sql` ("use Standard SQL") was being dropped on BigQuery projects - with a known engine, portability advice is dropped only when that engine supports the construct; `DISTINCT ON` on Snowflake or `GROUP BY alias` on SQL Server stays, because it errors there - files moved without edits are named in the comment, with the caveat that folder-level `dbt_project.yml` config can still change how they build - a run with no model files (yml-only, pure moves) is no longer labeled lint-only Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 5 ++ .../src/altimate/review/orchestrate.ts | 23 ++++++--- .../src/altimate/review/rule-catalog.ts | 29 +++++++---- .../test/altimate/review-noise.test.ts | 48 ++++++++++++++++--- 4 files changed, 82 insertions(+), 23 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 778ab2acae..e833c058e1 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -219,6 +219,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}` : ""}.`) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 04b055bfb1..223e657111 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -210,12 +210,20 @@ export interface OrchestrateInput { suppressPortability?: boolean } -const PORTABILITY_RE = /portab|dialect[ -]specific|non-?standard|n't standard|not standard|standard sql/i - -/** A regex-catalog finding whose concern is portability across warehouses. */ +/** A catalog finding tagged as cross-engine portability advice. */ export function isCatalogPortability(f: Finding): boolean { - const tool = f.evidence?.tool - return (tool === "rule-catalog" || tool === "dbt-patterns") && PORTABILITY_RE.test(`${f.title} ${f.body}`) + 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()) } /** Line numbers on the head side of a unified diff that GitHub accepts for an @@ -1170,7 +1178,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 @@ -1514,7 +1523,7 @@ export async function runReview(input: OrchestrateInput): Promise !isCatalogPortability(f)) + if (input.suppressPortability) findings = findings.filter((f) => !isSuppressiblePortability(f, dialect)) findings = anchorToDiff(findings, input.changedFiles) const minSev = SEVERITY_ORDER[input.config.severityThreshold] findings = findings.filter((f) => SEVERITY_ORDER[f.severity] >= minSev) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 0d8313c458..98360039a7 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -44,6 +44,12 @@ 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[] } example: RuleExample counter?: RuleExample } @@ -122,7 +128,10 @@ 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: rule.id }, + }, ruleKey: `${rule.category}:${rule.id}`, }) if (!exclusionReason(f, rubric)) matched.push({ rule, finding: f }) @@ -167,7 +176,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 +594,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)" }, ), @@ -1703,7 +1712,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 +1732,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 +1742,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,7 +1752,7 @@ 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|_at|_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)" }, ), @@ -1866,7 +1875,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 +1885,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 +2308,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/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index ae64c9a67e..dfd0208133 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -3,6 +3,7 @@ import { anchorToDiff, commentableLines, isCatalogPortability, + isSuppressiblePortability, runReview, type ReviewRunner, } from "../../src/altimate/review/orchestrate" @@ -17,6 +18,7 @@ import { SUMMARY_BUDGET_CHARS, } from "../../src/altimate/review/format" import { buildEnvelope } from "../../src/altimate/review/verdict" +import { evaluateCatalog } from "../../src/altimate/review/rule-catalog" import { classifyPostOutcome } from "../../src/altimate/review/telemetry" /** @@ -185,7 +187,7 @@ describe("portability noise", () => { 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: {} }, + evidence: { tool: "rule-catalog", result: { rule: "distinct-on", portability: true, worksOn: ["postgres", "duckdb"] } }, }) const coreMissing = finding({ category: "sql_quality", @@ -194,12 +196,31 @@ describe("portability noise", () => { 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 catalog portability findings", async () => { + 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 } @@ -227,9 +248,24 @@ describe("portability noise", () => { getContent: async () => sql, } const kept = await runReview(base) - const dropped = await runReview({ ...base, suppressPortability: true }) - const before = kept.findings.filter(isCatalogPortability).length - expect(before).toBeGreaterThan(0) - expect(dropped.findings.filter(isCatalogPortability).length).toBe(0) + 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`") }) }) From cfb0aa4ee3d9430e1b04ee4bf08d1f68e68160e2 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 20 Nov 2026 10:23:09 +0530 Subject: [PATCH 03/81] fix(review): address review comments: PII without a compiled base, same-model grouping - PII lanes: when a modified model's base SQL can't be compiled, the head's PII columns can't be told apart from pre-existing ones. Both the `schema.detect_pii` fallback and the diff-scoped classifier now report them as non-blocking warnings (with a note) instead of blocking criticals. Docs state the caveat. - Summary grouping counts distinct models, so several findings of one rule on the same model stay separate bullets instead of collapsing into the first. - Tests for both. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 4 ++- .../opencode/src/altimate/review/format.ts | 8 +++-- .../src/altimate/review/orchestrate.ts | 22 ++++++++---- .../test/altimate/review-noise.test.ts | 9 +++++ .../opencode/test/altimate/review.test.ts | 35 +++++++++++++++++++ 5 files changed, 68 insertions(+), 10 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 58d85cb715..e0f5908c46 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -299,7 +299,9 @@ rubric: fingerprint, so a push does not repeat findings already on the PR, and a non-blocking rerun with nothing new only updates the summary. - **PII:** flagged only for PII columns the change newly exposes, not for - columns the base already surfaced. + 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 diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index e833c058e1..22b2bd772c 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -161,7 +161,7 @@ function ruleTitle(f: Finding): string { } /** Render findings of one severity as bullets; a rule repeated on GROUP_MIN or - * more models collapses into a single bullet listing the models. */ + * more distinct models collapses into a single bullet listing the models. */ function bulletsFor(items: Finding[]): Array<{ text: string; count: number }> { const groups = new Map() for (const f of items) { @@ -172,8 +172,10 @@ function bulletsFor(items: Finding[]): Array<{ text: string; count: number }> { } const out: Array<{ text: string; count: number }> = [] for (const g of groups.values()) { - if (g.length >= GROUP_MIN) { - const names = [...new Set(g.map((f) => f.model ?? f.file))] + // 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 (names.length >= GROUP_MIN) { const shown = names.slice(0, 8).map((n) => `\`${n}\``).join(", ") const more = names.length > 8 ? ` (+${names.length - 8} more)` : "" out.push({ diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 223e657111..b6afeecf81 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1064,6 +1064,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) @@ -1071,7 +1074,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"), @@ -1092,20 +1095,26 @@ 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", + confidence: baseUnknown ? "medium" : "high", evidence: { tool: "schema.detect_pii", result: { columns } }, ruleKey: "pii:exposure", }), @@ -1303,7 +1312,8 @@ export async function runReview(input: OrchestrateInput): Promise !basePii.has(col.toLowerCase())) } - findings.push(...piiLane(currentCtx.file, fallbackPii)) + const baseUnknown = hasOldSide(currentCtx.file) && !currentCtx.engineOldSql + findings.push(...piiLane(currentCtx.file, fallbackPii, baseUnknown)) } return findings })(), diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index dfd0208133..eadc169466 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -150,6 +150,15 @@ describe("summary grouping and budget", () => { 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" }), diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 2ec9445a26..f4cea11a31 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2127,6 +2127,41 @@ 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("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 = { From 61430557be4bf0eb72db08801930c837c7f0ad46 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Mon, 23 Nov 2026 13:35:27 +0530 Subject: [PATCH 04/81] fix(review): grouping keeps distinct messages, base-exposed PII stays quiet, review skip and inline anchoring tightened - Summary grouping keys on the normalized body too, so one rule with different messages per model is no longer merged into the first message. A grouped bullet keeps `_unverified_` when any member is degraded and shows the body with names blanked when members differ only by name. Uncapped output (`maxChars: Infinity`) never groups. Renamed `ruleTitle` to `groupKeyTitle` and `GROUP_MIN` to `GROUP_MIN_MODELS`. - PII: the base's exposed PII columns are computed whenever a compiled base exists and suppress both the broad fallback and the `pii_into_mart` regex twin, so a reindented `ssn` line in a mart no longer blocks. - PII findings without a compiled base carry `unknown` confidence, so they no longer count toward `warningPatternThreshold`. - `postGitHubReview` skips a new review only when this bot's latest review (author taken from the summary comment) has the same headline as the current verdict; a prior "Changes requested" no longer suppresses it. Octokit is injectable for tests. - Findings keep `startLine` in the envelope; inline comments are filtered to commentable lines from the PR's file patches (`commentableLines` moved to `format.ts`, `anchorToDiff` removed). - `date-plus-int` split: the `_at` timestamp variant is `timestamp-plus-int` with `worksOn: ["oracle"]`, so it is kept on Postgres/Snowflake/DuckDB. - `shouldSuppressPortability` extracted from `run.ts`; docs example leaves `portability` commented out and explains explicit values. - Tests: grouping (differing bodies, mixed degraded, blanked names, more than eight models), mocked-Octokit `postGitHubReview` (skip, prior blocking review, other author, diff filtering, listing failure, 422 fallback), orchestrator PII (base-exposed twin, no-base warnings), timestamp rule, portability derivation. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 13 +- .../opencode/src/altimate/review/format.ts | 85 +++++-- .../src/altimate/review/orchestrate.ts | 76 ++---- .../src/altimate/review/post-github.ts | 66 ++++-- .../src/altimate/review/rule-catalog.ts | 14 +- packages/opencode/src/altimate/review/run.ts | 9 +- .../test/altimate/review-noise.test.ts | 224 +++++++++++++++++- .../opencode/test/altimate/review.test.ts | 89 ++++++- 8 files changed, 469 insertions(+), 107 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index e0f5908c46..a1375cb2a2 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -264,8 +264,9 @@ mode: comment # comment | gate severityThreshold: suggestion manifestPath: target/manifest.json dialect: snowflake -portability: false # cross-engine advice; default off once the engine is known - # (set true for packages that support several adapters) +# 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 @@ -291,13 +292,15 @@ rubric: 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 rules are grouped:** the same rule on three or more models is one - bullet listing the models. +- **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 only updates the summary. + 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 diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 22b2bd772c..0d84881822 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -39,7 +39,7 @@ export function verdictHeadline(env: VerdictEnvelope): string { /** 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 = 3 +export const GROUP_MIN_MODELS = 3 export interface RenderOptions { /** Character budget for the comment; findings beyond it are counted, not listed. @@ -117,7 +117,7 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s // 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. + // 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 @@ -126,7 +126,8 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s const items = grouped[sev] if (!items.length) continue const heading = [`### ${SEVERITY_EMOJI[sev]} ${capitalize(sev)} (${items.length})`, ""] - const bullets = bulletsFor(items) + // 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) @@ -153,19 +154,27 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s 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, so the same rule on different models/columns shares a key. */ -function ruleTitle(f: Finding): string { - const t = f.model && f.title.startsWith(`${f.model}: `) ? f.title.slice(f.model.length + 2) : f.title - return t.replace(/`[^`]*`/g, "`…`") + * 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; a rule repeated on GROUP_MIN or - * more distinct models collapses into a single bullet listing the models. */ -function bulletsFor(items: Finding[]): Array<{ text: string; count: number }> { +/** 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) { - const key = `${f.category}|${ruleTitle(f)}` + // 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]) @@ -175,13 +184,17 @@ function bulletsFor(items: Finding[]): Array<{ text: string; count: number }> { // 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 (names.length >= GROUP_MIN) { + 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: - `- **${ruleTitle(g[0])}** — ${g.length} findings across ${names.length} model(s): ${shown}${more} \n` + - ` ${oneLine(g[0].body)} \n ${g[0].category}`, + `- **${groupKeyTitle(g[0])}** — ${g.length} findings across ${names.length} model(s): ${shown}${more} \n` + + ` ${body} \n ${g[0].category}${unverified}`, count: g.length, }) continue @@ -255,9 +268,49 @@ export function postedFindingIds(bodies: Array): Set< return out } -export function inlineComments(env: VerdictEnvelope, alreadyPosted: Set = new Set()): InlineComment[] { +/** 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. 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" && !alreadyPosted.has(f.id)) + .filter( + (f) => + typeof f.startLine === "number" && + !alreadyPosted.has(f.id) && + (!commentable || !!commentable.get(f.file)?.has(f.startLine)), + ) .map((f) => ({ path: f.file, line: f.startLine!, diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index b6afeecf81..3fd1a019a0 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -226,47 +226,6 @@ export function isSuppressiblePortability(f: Finding, dialect: string): boolean return !worksOn || worksOn.includes(dialect.toLowerCase()) } -/** 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 -} - -/** - * Keep a finding's line only when it can be commented on: inside the file's - * diff hunks on the head side. Anything else (a line from compiled SQL, an - * unchanged region) moves to the summary instead of making GitHub reject the - * whole batch of inline comments. - */ -export function anchorToDiff(findings: Finding[], files: ChangedFile[]): Finding[] { - const lines = new Map(files.map((f) => [f.path, commentableLines(f.diff)])) - return findings.map((f) => { - if (typeof f.startLine !== "number") return f - if (lines.get(f.file)?.has(f.startLine)) return f - const { startLine: _s, endLine: _e, ...rest } = f - return rest as Finding - }) -} - /** True when SQL text contains Jinja (`{{ }}`, `{% %}` or `{# #}`). */ export function hasJinja(sql: string | undefined): boolean { return !!sql && /\{\{|\{%|\{#/.test(sql) @@ -1086,7 +1045,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}`, }), @@ -1114,7 +1075,8 @@ function piiLane(file: ChangedFile & { kind: string }, columns: string[], baseUn : ""), file: file.path, model, - confidence: baseUnknown ? "medium" : "high", + // `unknown`: undecided exposure never counts toward the warning pattern. + confidence: baseUnknown ? "unknown" : "high", evidence: { tool: "schema.detect_pii", result: { columns } }, ruleKey: "pii:exposure", }), @@ -1253,6 +1215,9 @@ 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. @@ -1296,6 +1261,17 @@ 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) — @@ -1304,14 +1280,8 @@ export async function runReview(input: OrchestrateInput): Promise !diffScopedPii.classifiedColumns.has(col.toLowerCase())) : currentCtx.pii - // Only columns this PR newly exposes: a PII column the base already - // surfaced is not this change's concern (the docs promise "newly expose"). - if (fallbackPii.length && hasOldSide(currentCtx.file) && currentCtx.engineOldSql) { - const basePii = new Set( - (await input.runner.detectPii(currentCtx.engineOldSql, dialect)).columns.map((c) => c.toLowerCase()), - ) - fallbackPii = fallbackPii.filter((col) => !basePii.has(col.toLowerCase())) - } + // 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)) } @@ -1456,6 +1426,9 @@ export async function runReview(input: OrchestrateInput): Promise !isSuppressiblePortability(f, dialect)) - findings = anchorToDiff(findings, input.changedFiles) 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 9a34c83199..d3b2217b95 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, postedFindingIds, 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 @@ -56,16 +63,20 @@ export interface PostResult { 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 to say and a previous - * non-blocking altimate review already exists (the summary comment was updated). */ + /** 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 } /** 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): Promise { - const octo = new Octokit({ auth: target.token }) +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 } @@ -80,13 +91,12 @@ 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); @@ -98,25 +108,39 @@ export async function postGitHubReview(env: VerdictEnvelope, target: GitHubTarge // 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 priorBotReview = false + 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)) - priorBotReview = reviews.some((r) => BOT_REVIEW_RE.test(r.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 */ } - const comments = inlineComments(env, posted) - const withLine = env.findings.filter((f) => typeof f.startLine === "number").length - result.inlineSkippedAsPosted = withLine - comments.length - // Nothing new inline, not blocking, and the PR already has an altimate - // review: the updated summary comment says it all; another "Reviewed with - // comments" entry per push is noise. A blocking verdict always posts. - if (!comments.length && event === "COMMENT" && priorBotReview) { + // Inline comments only on lines GitHub accepts (inside the PR's diff hunks). + // If the file list can't be read, post everything 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.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 } diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 98360039a7..a1be727539 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -1752,10 +1752,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, portability: { worksOn: ["postgres", "redshift", "snowflake", "duckdb", "oracle"] } }, + { 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[] = [ diff --git a/packages/opencode/src/altimate/review/run.ts b/packages/opencode/src/altimate/review/run.ts index c6a86b7925..f2d68f39ca 100644 --- a/packages/opencode/src/altimate/review/run.ts +++ b/packages/opencode/src/altimate/review/run.ts @@ -395,7 +395,7 @@ export async function reviewPullRequest(opts: ReviewPullRequestOptions): Promise forceTier: opts.forceTier, staleManifest, layout, - suppressPortability: config.portability === undefined ? dialectKnown : !config.portability, + suppressPortability: shouldSuppressPortability(config.portability, dialectKnown), scope: { baseRef: resolved?.ref ?? opts.base, baseSha: resolved?.sha, @@ -407,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/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index eadc169466..04ccdb6efe 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -1,7 +1,5 @@ import { describe, test, expect } from "bun:test" import { - anchorToDiff, - commentableLines, isCatalogPortability, isSuppressiblePortability, runReview, @@ -11,6 +9,7 @@ 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, @@ -18,8 +17,11 @@ import { 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 @@ -68,13 +70,16 @@ describe("inline anchors", () => { expect([...commentableLines(d)].sort()).toEqual([1, 2]) }) - test("a line outside the diff moves to the summary instead of failing the batch", () => { + 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 [a, b] = anchorToDiff([inDiff, outside], [{ path: "models/m.sql", status: "modified", diff: DIFF }]) - expect(a.startLine).toBe(3) - expect(b.startLine).toBeUndefined() - expect(b.endLine).toBeUndefined() + 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 () => { @@ -167,6 +172,67 @@ describe("summary grouping and budget", () => { 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++) @@ -278,3 +344,147 @@ describe("moved files", () => { 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 + 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 () => [{ 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("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) + }) +}) + +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 f4cea11a31..dbe942fefe 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2162,6 +2162,87 @@ describe("orchestrate", () => { 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") + }) + + test("a reindented PII line the base already exposed raises no regex twin", async () => { + // Whitespace-only edit of the `ssn` line in a mart: base and head expose the + // same columns, so neither the broad fallback nor `pii_into_mart` applies. + const files: ChangedFile[] = [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn\n+ ssn\n" }] + const runner = (): ReviewRunner => ({ + ...fakeRunner({}), + async detectPii(sql: string) { + return { columns: sql.includes("ssn") ? ["ssn"] : [] } + }, + async columnLineage(sql) { + return ["customer_id", "ssn"].filter((c) => sql.includes(c)).map((c) => ({ source: `customers.${c}`, target: c })) + }, + async classifyPii() { + return [] + }, + }) + const twin = (env: { findings: Array<{ evidence?: { tool?: string; result?: unknown } }> }) => + env.findings.some((f) => (f.evidence?.result as any)?.rule === "pii_into_mart") + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: runner(), + getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id,\n ssn\nfrom customers"), + }) + expect(twin(env)).toBe(false) + expect(env.findings.filter((f) => f.category === "pii_exposure" && f.severity === "critical")).toEqual([]) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + } + // Control: the same head with a base that lacked `ssn` still gets the twin. + 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: runner(), + getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id\nfrom customers"), + }) + expect(twin(added)).toBe(true) + }) + 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 = { @@ -2276,8 +2357,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") @@ -2315,8 +2396,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. From aca1e85104677d8052a42c4540f7ff2cbbf1ef1c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Mon, 23 Nov 2026 15:32:11 +0530 Subject: [PATCH 05/81] fix(review): reconcile both regex PII twins with the base, keep inline comments on patchless files - `select-pii-columns` now carries its matched columns on `evidence.result.columns` (new `capturesColumns` catalog flag) and is dropped when the compiled base already exposed every one of them - `pii_into_mart` emits one finding per added PII line, so a reindented base column no longer hides a genuinely new high-risk column on another line (shared fingerprint: dedupe keeps the most severe survivor) - without a compiled base (raw Jinja on the old side) both twins are reported as `warning` with `confidence: "unknown"`, like the other PII lanes, so they never block or count toward the warning-pattern threshold - `postGitHubReview` maps only files that have a `patch`; a file GitHub lists without one (large diff) has unknown hunks and its inline comments are attempted, relying on the existing 422 fallback Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/dbt-patterns.ts | 49 ++++---- .../opencode/src/altimate/review/format.ts | 6 +- .../src/altimate/review/orchestrate.ts | 21 +++- .../src/altimate/review/post-github.ts | 5 +- .../src/altimate/review/rule-catalog.ts | 25 +++- .../test/altimate/review-noise.test.ts | 25 +++- .../opencode/test/altimate/review.test.ts | 109 ++++++++++++++---- 7 files changed, 184 insertions(+), 56 deletions(-) diff --git a/packages/opencode/src/altimate/review/dbt-patterns.ts b/packages/opencode/src/altimate/review/dbt-patterns.ts index b9b99c1f8b..b48ba69a25 100644 --- a/packages/opencode/src/altimate/review/dbt-patterns.ts +++ b/packages/opencode/src/altimate/review/dbt-patterns.ts @@ -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 added PII line: each carries its own column in `result.line` + // so the orchestrator can suppress a base-exposed column without hiding a new + // one on another line. They share a fingerprint, so dedupe keeps the most + // severe survivor. + return hits.map((hit) => { + // 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", + }) }) } @@ -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 0d84881822..0d73434108 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -297,7 +297,9 @@ export function commentableLines(diff: string | undefined): Set { * 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. The finding keeps its line in the envelope and summary. + * 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, @@ -309,7 +311,7 @@ export function inlineComments( (f) => typeof f.startLine === "number" && !alreadyPosted.has(f.id) && - (!commentable || !!commentable.get(f.file)?.has(f.startLine)), + (!commentable?.has(f.file) || commentable.get(f.file)!.has(f.startLine)), ) .map((f) => ({ path: f.file, diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 3fd1a019a0..3804ce42a6 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1434,9 +1434,14 @@ export async function runReview(input: OrchestrateInput): Promise basePii.has(c))) 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 } @@ -1463,6 +1468,16 @@ export async function runReview(input: OrchestrateInput): Promise> | undefined try { const files = await octo.paginate(octo.rest.pulls.listFiles, { owner, repo, pull_number: prNumber, per_page: 100 }) - commentable = new Map(files.map((f) => [f.filename, commentableLines(f.patch)])) + commentable = new Map(files.filter((f) => f.patch).map((f) => [f.filename, commentableLines(f.patch)])) } catch { /* fall back to the positioning retry below */ } diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index a1be727539..dc2f444db4 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -50,6 +50,9 @@ export interface Rule { * error there and is kept). Omit `worksOn` when support isn't established. */ portability?: { worksOn?: string[] } + /** `added`'s first capture group is a column name: matched columns are kept on + * `evidence.result.columns` so the orchestrator can reconcile them per column. */ + capturesColumns?: boolean example: RuleExample counter?: RuleExample } @@ -107,6 +110,18 @@ export function ruleMatches(rule: Rule, input: RuleInput): boolean { return relevant } +/** Distinct lowercased first-group captures of `rule.added` over the added lines. */ +function capturedColumns(rule: Rule, added: string[]): string[] { + const cols = new Set() + for (const l of added) { + const s = stripComments(l) + if (rule.unless?.test(s)) continue + const col = rule.added?.exec(s)?.[1] + if (col) cols.add(col.toLowerCase()) + } + return [...cols] +} + /** Evaluate the catalog against a changed file. */ export function evaluateCatalog( file: ChangedFile, @@ -130,7 +145,11 @@ export function evaluateCatalog( confidence: "high", evidence: { tool: "rule-catalog", - result: rule.portability ? { rule: rule.id, portability: true, worksOn: rule.portability.worksOn } : { rule: rule.id }, + result: rule.portability + ? { rule: rule.id, portability: true, worksOn: rule.portability.worksOn } + : rule.capturesColumns + ? { rule: rule.id, columns: capturedColumns(rule, added) } + : { rule: rule.id }, }, ruleKey: `${rule.category}:${rule.id}`, }) @@ -176,7 +195,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 }) @@ -1202,7 +1221,7 @@ 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: true }, { add: " c.ssn," }, { add: " c.country," }, ), diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 04ccdb6efe..7a3d6d8024 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -354,6 +354,7 @@ describe("postGitHubReview", () => { opts: { reviews?: Array<{ body: string; user?: { login: string } }> listFails?: boolean + files?: Array<{ filename: string; patch?: string }> createReview?: (call: number) => unknown } = {}, ) { @@ -372,7 +373,7 @@ describe("postGitHubReview", () => { pulls: { listReviewComments: opts.listFails ? fail : async () => [], listReviews: opts.listFails ? fail : async () => opts.reviews ?? [], - listFiles: opts.listFails ? fail : async () => [{ filename: "models/m.sql", patch: PATCH }], + 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) @@ -431,6 +432,28 @@ describe("postGitHubReview", () => { 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" })], diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index dbe942fefe..2a6abb9eb6 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2200,47 +2200,110 @@ describe("orchestrate", () => { expect(env.verdict).not.toBe("REQUEST_CHANGES") }) + // Runner whose base/head PII is exactly the listed columns present in the SQL. + const piiRunner = (cols: string[], classify: ReviewRunner["classifyPii"] = async () => []): ReviewRunner => ({ + ...fakeRunner({}), + async detectPii(sql: string) { + return { columns: cols.filter((c) => sql.includes(c)) } + }, + async columnLineage(sql) { + return ["customer_id", ...cols].filter((c) => sql.includes(c)).map((c) => ({ source: `customers.${c}`, target: c })) + }, + 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 a mart: base and head expose the - // same columns, so neither the broad fallback nor `pii_into_mart` applies. - const files: ChangedFile[] = [{ path: "models/marts/m.sql", status: "modified", diff: "- ssn\n+ ssn\n" }] - const runner = (): ReviewRunner => ({ - ...fakeRunner({}), - async detectPii(sql: string) { - return { columns: sql.includes("ssn") ? ["ssn"] : [] } - }, - async columnLineage(sql) { - return ["customer_id", "ssn"].filter((c) => sql.includes(c)).map((c) => ({ source: `customers.${c}`, target: c })) - }, - async classifyPii() { - return [] - }, - }) - const twin = (env: { findings: Array<{ evidence?: { tool?: string; result?: unknown } }> }) => - env.findings.some((f) => (f.evidence?.result as any)?.rule === "pii_into_mart") + // 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: runner(), + runner: piiRunner(["ssn"]), getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id,\n ssn\nfrom customers"), }) - expect(twin(env)).toBe(false) - expect(env.findings.filter((f) => f.category === "pii_exposure" && f.severity === "critical")).toEqual([]) + 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 the twin. + // 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: runner(), + runner: piiRunner(["ssn"]), getContent: content("select customer_id,\n ssn\nfrom customers", "select customer_id\nfrom customers"), }) - expect(twin(added)).toBe(true) + 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"]) + }) + + 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 `ssn` is new + // cannot be decided, so neither twin is critical or counts toward 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 {{ 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 () => { From 932cf6fe558bfe9b44c803df2111821cc9e66a13 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Mon, 23 Nov 2026 18:42:56 +0530 Subject: [PATCH 06/81] fix(review): reconcile PII twins by output alias and every token, keep verified inline comments on a 422 - `pii_into_mart` and `select-pii-columns` now pair each PII token with its select item's `AS` alias (`selectItemColumns`) and suppress it when the base exposes either the alias or the source column, since `detectPii` reports output aliases (`c.ssn as tax_ref` -> `tax_ref`) - both twins also drop a line whose comment/whitespace-normalised text is among the file's removed lines (pure reindent), independent of base PII detection - both twins collect every PII token on a line, not just the first: `ssn, passport` with a base-exposed `ssn` still reports `passport`; `pii_into_mart` emits one finding per token (shared fingerprint, so dedupe keeps the most severe) - `postGitHubReview`: on a positioning 422, retry once with only the comments on files whose hunks are known before falling back to an event-only review - the test runner's `detectPii`/`columnLineage` fakes return output aliases like the real runner; the raw-Jinja test uses an added line, since a pure reindent is now dropped outright Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/dbt-patterns.ts | 16 +-- .../src/altimate/review/orchestrate.ts | 63 +++++---- .../src/altimate/review/post-github.ts | 23 +++- .../src/altimate/review/rule-catalog.ts | 91 +++++++++++-- .../test/altimate/review-noise.test.ts | 44 +++++++ .../opencode/test/altimate/review.test.ts | 120 +++++++++++++++++- 6 files changed, 308 insertions(+), 49 deletions(-) diff --git a/packages/opencode/src/altimate/review/dbt-patterns.ts b/packages/opencode/src/altimate/review/dbt-patterns.ts index b48ba69a25..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 { @@ -313,14 +313,14 @@ const detectPiiIntoMart: Detector = (c) => { ) ) }) - // One finding per added PII line: each carries its own column in `result.line` - // so the orchestrator can suppress a base-exposed column without hiding a new - // one on another line. They share a fingerprint, so dedupe keeps the most - // severe survivor. - return hits.map((hit) => { + // 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 = /\b(ssn|social_security|credit_card|passport|date_of_birth|dob)\b/i.test(hit) + const sev: Severity = /^(ssn|social_security|credit_card|passport|date_of_birth|dob)$/i.test(column) ? "critical" : "warning" return makeFinding({ @@ -333,7 +333,7 @@ const detectPiiIntoMart: Detector = (c) => { file: c.file.path, model: c.model, confidence: "high", - evidence: { tool: "dbt-patterns", result: { rule: "pii_into_mart", line: hit.trim() } }, + evidence: { tool: "dbt-patterns", result: { rule: "pii_into_mart", line, column, alias } }, ruleKey: "pii_exposure:into-mart", }) }) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 3804ce42a6..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" /** @@ -865,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 [] @@ -1405,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, "-") @@ -1420,25 +1435,29 @@ export async function runReview(input: OrchestrateInput): Promise basePii.has(c))) return false + // `select-pii-columns` keeps every matched column with its alias and line: + // drop it when each one is a reindented base line or already base-exposed. + const items = result.items ?? [] + if (items.length && items.every((i) => isReindented(f.file, i.line) || isBaseExposed(f.file, i))) 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/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index fe210cb466..fb3010d8c1 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -57,7 +57,7 @@ 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 @@ -180,6 +180,27 @@ export async function postGitHubReview( 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 dc2f444db4..4d3ef71a89 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -50,9 +50,11 @@ export interface Rule { * error there and is kept). Omit `worksOn` when support isn't established. */ portability?: { worksOn?: string[] } - /** `added`'s first capture group is a column name: matched columns are kept on - * `evidence.result.columns` so the orchestrator can reconcile them per column. */ - capturesColumns?: boolean + /** 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 } @@ -110,16 +112,75 @@ export function ruleMatches(rule: Rule, input: RuleInput): boolean { return relevant } -/** Distinct lowercased first-group captures of `rule.added` over the added lines. */ -function capturedColumns(rule: Rule, added: string[]): string[] { - const cols = new Set() +/** 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.unless?.test(s)) continue - const col = rule.added?.exec(s)?.[1] - if (col) cols.add(col.toLowerCase()) + if (!rule.capturesColumns || !rule.added?.test(s) || rule.unless?.test(s)) continue + out.push(...selectItemColumns(l, rule.capturesColumns)) } - return [...cols] + return out } /** Evaluate the catalog against a changed file. */ @@ -148,7 +209,10 @@ export function evaluateCatalog( result: rule.portability ? { rule: rule.id, portability: true, worksOn: rule.portability.worksOn } : rule.capturesColumns - ? { rule: rule.id, columns: capturedColumns(rule, added) } + ? (() => { + 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}`, @@ -1221,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, capturesColumns: true }, + { + 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," }, ), diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 7a3d6d8024..fe111bc0a3 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -486,6 +486,50 @@ describe("postGitHubReview", () => { 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", () => { diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 2a6abb9eb6..f5ef7843be 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2200,14 +2200,24 @@ describe("orchestrate", () => { expect(env.verdict).not.toBe("REQUEST_CHANGES") }) - // Runner whose base/head PII is exactly the listed columns present in the SQL. + // 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.filter((c) => sql.includes(c)) } + return { columns: cols.flatMap((c) => outputNames(sql, c)) } }, async columnLineage(sql) { - return ["customer_id", ...cols].filter((c) => sql.includes(c)).map((c) => ({ source: `customers.${c}`, target: c })) + return ["customer_id", ...cols].flatMap((c) => + outputNames(sql, c).map((target) => ({ source: `customers.${c}`, target })), + ) }, classifyPii: classify, }) @@ -2265,10 +2275,108 @@ describe("orchestrate", () => { 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 `ssn` is new - // cannot be decided, so neither twin is critical or counts toward a block. - const files: ChangedFile[] = MARTS.map((path) => ({ path, status: "modified", diff: "- ssn\n+ ssn\n" })) + // 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, From 3f7ae537393528fd5be6fe96c682df28e341fe13 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 01:42:54 +0530 Subject: [PATCH 07/81] fix(review): count a PII column as base-exposed only when the base exposed the same source `isBaseExposed` treated the line's output alias as proof of prior exposure, whatever source the base built that alias from, so base `c.email as contact` -> head `c.ssn as contact` suppressed both regex PII twins and a newly exposed SSN in a mart was approved. - `rule-catalog.ts`: add `aliasSourceTokens`, mapping each output alias in a SQL text to the identifiers its select items are built from - `orchestrate.ts`: a source column is base-exposed only when the base output holds it under its own name, or under an alias the base built from that column; an alias with an unknown or different base source keeps the finding - tests: same-alias source swap (`contact`, `customer_key`) keeps a critical `pii_into_mart` under reviewers `[]` and `["dbt_patterns"]`; an alias-only rename of the same source raises nothing Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 26 +++++++++--- .../src/altimate/review/rule-catalog.ts | 18 ++++++++ .../opencode/test/altimate/review.test.ts | 42 +++++++++++++++++++ 3 files changed, 81 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 1ceb9807f0..38ff48a868 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -14,7 +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 SelectItemColumn, aliasSourceTokens, normalizeSelectLine } from "./rule-catalog" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult, safeReason } from "./ai-review" /** @@ -1413,12 +1413,28 @@ export async function runReview(input: OrchestrateInput): Promise>>() + const baseAliasSources = (file: string) => { + let sources = baseAliasSourcesByFile.get(file) + if (!sources) { + const ctx = ctxByPath.get(file) + sources = aliasSourceTokens([ctx?.oldSql, ctx?.engineOldSql].filter(Boolean).join("\n")) + baseAliasSourcesByFile.set(file, sources) + } + return sources + } + // `detectPii` reports OUTPUT names (`c.ssn as tax_ref` → `tax_ref`): a SOURCE + // column is already exposed when the base output holds it under its own name, or + // under an alias the base built from it (so `c.ssn as tax_ref` → `c.ssn as tax_id` + // re-exposes nothing new). The line's alias alone is not proof: `c.email as + // contact` → `c.ssn as contact` newly exposes `ssn`. 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))) + if (!basePii) return false + if (basePii.has(item.column)) return true + const sources = baseAliasSources(file) + return [...basePii].some((name) => !!sources.get(name)?.has(item.column)) } const merged = flat.filter((f) => { const tool = f.evidence?.tool diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 4d3ef71a89..09ad5c4cc6 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -162,6 +162,24 @@ export function selectItemColumns(line: string, tokenRe: RegExp): SelectItemColu return out } +/** + * Per output alias in `sql`, every identifier the select items carrying that + * alias are built from (`c.email as contact` → `contact: {c, email, …}`). An + * alias only proves exposure of a column that is among its sources. + */ +export function aliasSourceTokens(sql: string): Map> { + const out = new Map>() + for (const line of sql.split("\n")) { + for (const { column, alias } of selectItemColumns(line, /\b([A-Za-z_][\w$]*)\b/)) { + if (!alias) continue + const sources = out.get(alias) ?? new Set() + sources.add(column) + out.set(alias, sources) + } + } + 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 { diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index f5ef7843be..2c28827bb2 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2328,6 +2328,48 @@ describe("orchestrate", () => { expect(twins.find((f) => (f.evidence?.result as any)?.rule === "pii_into_mart")?.severity).toBe("critical") }) + test("an alias the base exposes from a different source does not hide a newly exposed PII column", async () => { + // Same output alias, different source: base `c.email as contact`, head + // `c.ssn as contact`. detectPii and the classifier see `contact` on both + // sides, so the regex twins are the only detectors left and must stay. + for (const [from, to] of [ + ["c.email as contact", "c.ssn as contact"], + ["c.email as customer_key", "c.ssn as customer_key"], + ]) { + const base = `select c.customer_id,\n ${from}\nfrom customers c` + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: `- ${from}\n+ ${to}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["email", "ssn"]), + getContent: content(base.replace(from, to), base), + }) + 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(["ssn"]) + expect(intoMart[0].severity).toBe("critical") + expect(env.verdict).toBe("REQUEST_CHANGES") + } + } + // Control: only the alias changes, the source stays (`c.ssn as tax_ref` → + // `c.ssn as tax_id`): nothing new is exposed, so no PII finding. + const base = "select c.customer_id,\n c.ssn as tax_ref\nfrom customers c" + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: [ + { path: "models/marts/m.sql", status: "modified", diff: "- c.ssn as tax_ref\n+ c.ssn as tax_id\n" }, + ], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content(base.replace("tax_ref", "tax_id"), base), + }) + expect(env.findings.filter(isTwin)).toEqual([]) + } + }) + 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({ From 18613b9e752a1abce0208b5f2bcae7590e9b9a68 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 01:46:13 +0530 Subject: [PATCH 08/81] fix(review): ignore string-literal contents when collecting PII select-item columns `selectItemColumns` matched PII tokens inside single-quoted literals and `topLevelItems` split select items on commas inside them, so `email` -> `email, 'passport' as kind` raised a critical `pii_into_mart` for `passport`, and `email || ',' || phone_number as contact` lost the alias of `email`. - `rule-catalog.ts`: blank literal contents with `stripLiterals` before splitting and matching; `stripLiterals` moves here and is exported - `dbt-patterns.ts`: import `stripLiterals` from `rule-catalog.ts` instead of keeping a private copy - tests: `'passport'` literal negative control under reviewers `[]` and `["dbt_patterns"]`, the `email || ',' || phone_number as contact` alias case end to end, and `selectItemColumns` unit tests for both Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/dbt-patterns.ts | 13 +---- .../src/altimate/review/rule-catalog.ts | 20 +++++++- .../test/altimate/review-rule-catalog.test.ts | 18 ++++++- .../opencode/test/altimate/review.test.ts | 47 +++++++++++++++++++ 4 files changed, 83 insertions(+), 15 deletions(-) diff --git a/packages/opencode/src/altimate/review/dbt-patterns.ts b/packages/opencode/src/altimate/review/dbt-patterns.ts index c05523fe1f..82ffe4ddc7 100644 --- a/packages/opencode/src/altimate/review/dbt-patterns.ts +++ b/packages/opencode/src/altimate/review/dbt-patterns.ts @@ -4,7 +4,7 @@ import { Log } from "@/altimate/util/log" import { type Finding, type Severity, type ReviewCategory, makeFinding } from "./finding" import { type ChangedFile, fileKind } from "./diff-filter" import { type Rubric, clampSeverity, exclusionReason } from "./rubric" -import { evaluateCatalog, selectItemColumns } from "./rule-catalog" +import { evaluateCatalog, selectItemColumns, stripLiterals } from "./rule-catalog" /** Local copy to avoid a cycle with orchestrate.ts. */ function modelNameFromPath(p: string): string { @@ -53,17 +53,6 @@ function stripComments(s: string): string { .replace(/\{#[\s\S]*?#\}/g, " ") } -/** - * Blank out single-quoted SQL string-literal CONTENTS (keeping the quotes) so a - * regex detector can't be tripped by punctuation inside a literal — e.g. the - * `/` in `'n/a'` must not read as division, a `,` in `'a,b'` must not read as a - * comma join. Detectors that legitimately inspect literal content (leading - * wildcard, hardcoded date) must NOT use this. Handles doubled-quote escapes. - */ -function stripLiterals(s: string): string { - return s.replace(/'(?:[^']|'')*'/g, "''") -} - /** * True when a line's FROM clause lists two relations separated by a comma at * paren-depth 0 — i.e. `FROM a, b` (an implicit cross join). Scans only after diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 09ad5c4cc6..a3d66084f1 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -70,6 +70,18 @@ function stripComments(s: string): string { .replace(/\{#[\s\S]*?#\}/g, " ") } +/** + * Blank out single-quoted SQL string-literal CONTENTS (keeping the quotes) so a + * regex detector can't be tripped by punctuation inside a literal — e.g. the + * `/` in `'n/a'` must not read as division, a `,` in `'a,b'` must not read as a + * comma join, and `'passport'` must not read as a column. Detectors that + * legitimately inspect literal content (leading wildcard, hardcoded date) must + * NOT use this. Handles doubled-quote escapes. + */ +export function stripLiterals(s: string): string { + return s.replace(/'(?:[^']|'')*'/g, "''") +} + export interface RuleInput { file: ChangedFile newSql: string @@ -120,7 +132,8 @@ export interface SelectItemColumn { line: string } -/** Split on commas outside parentheses (one entry per select item). */ +/** Split on commas outside parentheses (one entry per select item). Callers + * blank string literals first (`stripLiterals`), so a comma inside one never splits. */ function topLevelItems(s: string): string[] { const items: string[] = [] let depth = 0 @@ -141,12 +154,15 @@ function topLevelItems(s: string): string[] { * 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`. + * Tokens inside single-quoted literals are ignored. */ 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))) { + // Literals are blanked first: their contents are neither column tokens nor + // item separators (`email || ',' || phone_number as contact` is one item). + for (const item of topLevelItems(stripLiterals(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 diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 84cf8714d0..6dbddc0486 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -1,5 +1,5 @@ import { describe, test, expect } from "bun:test" -import { CATALOG, ruleMatches, inputFromExample } from "../../src/altimate/review/rule-catalog" +import { CATALOG, ruleMatches, inputFromExample, selectItemColumns } from "../../src/altimate/review/rule-catalog" describe("rule catalog (self-verifying scenario corpus)", () => { test("every rule fires on its example and stays clean on its counter", () => { @@ -26,3 +26,19 @@ describe("rule catalog (self-verifying scenario corpus)", () => { expect(CATALOG.length).toBeGreaterThanOrEqual(150) }) }) + +describe("selectItemColumns", () => { + const PII = /\b(email|ssn|phone_number|passport)\b/i + test("ignores tokens inside string literals", () => { + expect(selectItemColumns("email, 'passport' as kind", PII)).toEqual([ + { column: "email", alias: undefined, line: "email, 'passport' as kind" }, + ]) + }) + test("does not split a select item on a comma inside a literal", () => { + const line = "email || ',' || phone_number as contact" + expect(selectItemColumns(line, PII)).toEqual([ + { column: "email", alias: "contact", line }, + { column: "phone_number", alias: "contact", line }, + ]) + }) +}) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 2c28827bb2..4a6f5b925c 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2414,6 +2414,53 @@ describe("orchestrate", () => { expect(both.findings.filter(isTwin)).toEqual([]) }) + test("a PII name inside a string literal is not a PII column", async () => { + // `- email` / `+ email, 'passport' as kind`: `email` is base-exposed and + // `'passport'` is a literal, so nothing new is exposed. + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: [ + { path: "models/marts/m.sql", status: "modified", diff: "- email\n+ email, 'passport' as kind\n" }, + ], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["email"]), + getContent: content( + "select customer_id,\n email, 'passport' as kind\nfrom customers", + "select customer_id,\n email\nfrom customers", + ), + }) + expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + } + }) + + test("a comma inside a literal does not split an aliased PII item from its alias", async () => { + // `email || ',' || phone_number as contact` is ONE item aliased `contact`; the + // base built `contact` from both columns, so a table-alias rename exposes nothing. + const base = "select c.customer_id,\n c.email || ',' || c.phone_number as contact\nfrom customers c" + const head = base.replace(/\bc\./g, "cust.").replace("customers c", "customers cust") + const env = await runReview({ + changedFiles: [ + { + path: "models/marts/m.sql", + status: "modified", + diff: "- c.email || ',' || c.phone_number as contact\n+ cust.email || ',' || cust.phone_number as contact\n", + }, + ], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: { + ...piiRunner([]), + detectPii: async (sql: string) => ({ columns: /as contact/.test(sql) ? ["contact"] : [] }), + }, + getContent: content(head, base), + }) + expect(env.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 From 56a227e0995fc5bde07748b85b63c34b49dd755c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 01:49:48 +0530 Subject: [PATCH 09/81] fix(review): count a base PII output as exposing a column only when it selects the column raw A base output that masked a PII column (`sha2(c.ssn) as ssn_hash`, flagged by name) counted as exposing `ssn`, because any identifier in the base item was accepted as its source. A newly added raw `c.ssn as tax_ref` was then suppressed as base-exposed. - `rule-catalog.ts`: replace `aliasSourceTokens` with `rawColumnExposures`, mapping each base output name to the columns its select item exposes raw: a bare (optionally table-qualified) column reference, optionally aliased and optionally cast (`cast(c.ssn as varchar)`, `c.ssn::varchar`); any other function or expression (`sha2`, `left`, `concat`, `case`, `||`) exposes nothing raw - `orchestrate.ts`: `isBaseExposed` requires a base PII output that exposes the same source column raw, including the plain own-name case - tests: `sha2(c.ssn) as ssn_hash` base -> `+ c.ssn as tax_ref` keeps a critical finding and REQUEST_CHANGES under reviewers `[]` and `["dbt_patterns"]`; the literal-comma test now checks that both columns of `c.email || ',' || c.phone_number as contact` carry the `contact` alias, since a concatenation no longer proves base exposure Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 32 ++++----- .../src/altimate/review/rule-catalog.ts | 37 +++++++--- .../opencode/test/altimate/review.test.ts | 67 ++++++++++++++----- 3 files changed, 96 insertions(+), 40 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 38ff48a868..9d04cf6db8 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -14,7 +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, aliasSourceTokens, normalizeSelectLine } from "./rule-catalog" +import { type SelectItemColumn, normalizeSelectLine, rawColumnExposures } from "./rule-catalog" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult, safeReason } from "./ai-review" /** @@ -1413,28 +1413,28 @@ export async function runReview(input: OrchestrateInput): Promise>>() - const baseAliasSources = (file: string) => { - let sources = baseAliasSourcesByFile.get(file) - if (!sources) { + // Per file, the base SQL's output names mapped to the columns each exposes RAW. + const baseRawExposuresByFile = new Map>>() + const baseRawExposures = (file: string) => { + let exposures = baseRawExposuresByFile.get(file) + if (!exposures) { const ctx = ctxByPath.get(file) - sources = aliasSourceTokens([ctx?.oldSql, ctx?.engineOldSql].filter(Boolean).join("\n")) - baseAliasSourcesByFile.set(file, sources) + exposures = rawColumnExposures([ctx?.oldSql, ctx?.engineOldSql].filter(Boolean).join("\n")) + baseRawExposuresByFile.set(file, exposures) } - return sources + return exposures } // `detectPii` reports OUTPUT names (`c.ssn as tax_ref` → `tax_ref`): a SOURCE - // column is already exposed when the base output holds it under its own name, or - // under an alias the base built from it (so `c.ssn as tax_ref` → `c.ssn as tax_id` - // re-exposes nothing new). The line's alias alone is not proof: `c.email as - // contact` → `c.ssn as contact` newly exposes `ssn`. + // column is already exposed only when a base PII output exposes that same column + // RAW, under its own name or an alias (`c.ssn as tax_ref` → `c.ssn as tax_id` + // re-exposes nothing new). The line's alias alone is not proof (`c.email as + // contact` → `c.ssn as contact` newly exposes `ssn`), and neither is a base + // output that only masks the column (`sha2(c.ssn) as ssn_hash`). const isBaseExposed = (file: string, item: { column: string; alias?: string }) => { const basePii = basePiiColumnsByFile.get(file) if (!basePii) return false - if (basePii.has(item.column)) return true - const sources = baseAliasSources(file) - return [...basePii].some((name) => !!sources.get(name)?.has(item.column)) + const exposures = baseRawExposures(file) + return [...basePii].some((name) => !!exposures.get(name)?.has(item.column)) } const merged = flat.filter((f) => { const tool = f.evidence?.tool diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index a3d66084f1..fbba8d3d89 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -178,19 +178,38 @@ export function selectItemColumns(line: string, tokenRe: RegExp): SelectItemColu return out } +// A column reference, optionally table-qualified (`c.ssn`); group 1 is the column. +const COLUMN_REF = String.raw`(?:[A-Za-z_][\w$]*\.)*([A-Za-z_][\w$]*)` +// Select-item expressions that expose a column RAW: a bare reference, or one only +// cast to a type (`cast(c.ssn as varchar)`, `c.ssn::varchar(20)`). +const RAW_COLUMN_EXPRS = [ + new RegExp(String.raw`^${COLUMN_REF}$`, "i"), + new RegExp(String.raw`^cast\s*\(\s*${COLUMN_REF}\s+as\s+[\w\s(),]+\)$`, "i"), + new RegExp(String.raw`^${COLUMN_REF}\s*::\s*\w+(?:\s*\([\d\s,]*\))?$`, "i"), +] + /** - * Per output alias in `sql`, every identifier the select items carrying that - * alias are built from (`c.email as contact` → `contact: {c, email, …}`). An - * alias only proves exposure of a column that is among its sources. + * Per output name in `sql`, the columns a select item exposes RAW under that + * name (`c.ssn as tax_ref` → `tax_ref: {ssn}`, bare `ssn` → `ssn: {ssn}`). An + * item that wraps the column in any other function or expression (`sha2(c.ssn)`, + * `left(c.ssn, 4)`, `case …`, `a || b`) exposes nothing raw and is left out. */ -export function aliasSourceTokens(sql: string): Map> { +export function rawColumnExposures(sql: string): Map> { const out = new Map>() for (const line of sql.split("\n")) { - for (const { column, alias } of selectItemColumns(line, /\b([A-Za-z_][\w$]*)\b/)) { - if (!alias) continue - const sources = out.get(alias) ?? new Set() - sources.add(column) - out.set(alias, sources) + for (const item of topLevelItems(stripLiterals(stripComments(line)))) { + const s = item + .trim() + .replace(/^select\s+(?:distinct\s+)?/i, "") + .replace(/\s+from\s[\s\S]*$/i, "") + const aliased = /^([\s\S]*\S)\s+as\s+["`]?([A-Za-z_][\w$]*)["`]?$/i.exec(s) + const expr = aliased ? aliased[1] : s + const column = RAW_COLUMN_EXPRS.map((re) => re.exec(expr)?.[1]).find(Boolean)?.toLowerCase() + if (!column) continue + const name = aliased?.[2]?.toLowerCase() ?? column + const columns = out.get(name) ?? new Set() + columns.add(column) + out.set(name, columns) } } return out diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 4a6f5b925c..4e8357a1c1 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2437,28 +2437,65 @@ describe("orchestrate", () => { }) test("a comma inside a literal does not split an aliased PII item from its alias", async () => { - // `email || ',' || phone_number as contact` is ONE item aliased `contact`; the - // base built `contact` from both columns, so a table-alias rename exposes nothing. - const base = "select c.customer_id,\n c.email || ',' || c.phone_number as contact\nfrom customers c" - const head = base.replace(/\bc\./g, "cust.").replace("customers c", "customers cust") + // `email || ',' || phone_number as contact` is ONE item aliased `contact`, so + // both PII tokens carry that alias (not just the one after the literal comma). const env = await runReview({ changedFiles: [ - { - path: "models/marts/m.sql", - status: "modified", - diff: "- c.email || ',' || c.phone_number as contact\n+ cust.email || ',' || cust.phone_number as contact\n", - }, + { path: "models/marts/m.sql", status: "modified", diff: "+ c.email || ',' || c.phone_number as contact\n" }, ], config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, rubric: DEFAULT_RUBRIC, mode: "gate", - runner: { - ...piiRunner([]), - detectPii: async (sql: string) => ({ columns: /as contact/.test(sql) ? ["contact"] : [] }), - }, - getContent: content(head, base), + runner: piiRunner([]), + getContent: content( + "select c.customer_id,\n c.email || ',' || c.phone_number as contact\nfrom customers c", + "select c.customer_id\nfrom customers c", + ), }) - expect(env.findings.filter(isTwin)).toEqual([]) + // The two twins share a fingerprint (dedupe keeps one); the catalog twin lists every item. + const catalog = env.findings.find((f) => (f.evidence?.result as any)?.rule === "select-pii-columns") + expect((catalog?.evidence?.result as any)?.items.map((i: any) => [i.column, i.alias])).toEqual([ + ["email", "contact"], + ["phone_number", "contact"], + ]) + }) + + test("a base output that masks a PII column does not hide the raw column newly added", async () => { + // Base `sha2(c.ssn) as ssn_hash` (flagged by name) exposes no raw SSN, so a + // newly added `c.ssn as tax_ref` keeps its critical twin. + const base = "select c.customer_id,\n sha2(c.ssn) as ssn_hash\nfrom customers c" + const head = "select c.customer_id,\n sha2(c.ssn) as ssn_hash,\n c.ssn as tax_ref\nfrom customers c" + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: [ + { + path: "models/marts/m.sql", + status: "modified", + diff: "- sha2(c.ssn) as ssn_hash\n+ sha2(c.ssn) as ssn_hash,\n+ c.ssn as tax_ref\n", + }, + ], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: { + ...piiRunner([]), + detectPii: async (sql: string) => ({ + columns: ["ssn_hash", "tax_ref"].filter((name) => new RegExp(`as ${name}\\b`).test(sql)), + }), + }, + getContent: content(head, base), + }) + // Reported by the broad lane (reviewers `[]`) or, without it, by the regex twin. + const ssn = env.findings.filter( + (f) => + f.category === "pii_exposure" && + f.severity === "critical" && + ((f.evidence?.result as any)?.alias === "tax_ref" || f.title.includes("tax_ref")), + ) + expect(ssn.length).toBeGreaterThan(0) + if (reviewers.length) expect((ssn[0].evidence?.result as any)?.rule).toBe("pii_into_mart") + expect(env.verdict).toBe("REQUEST_CHANGES") + } }) test("without a compiled base the regex PII twins are unknown-confidence warnings that never block", async () => { From 29778bec755f1ab5a755067cd9a9c95a404ca260 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 15:59:23 +0530 Subject: [PATCH 10/81] fix(review): read base PII exposures from the final projection, across lines `rawColumnExposures` scanned the base SQL line by line with no query scope, so a CTE's `ssn as contact` merged with the final select's `email as contact` and hid a head `ssn as contact`. It also missed items whose expression or alias spans lines, quoted identifiers (`"c"."ssn"`) and aliases without `AS` (`c.ssn tax_ref`). - `selectItems` (`rule-catalog.ts`) parses every select list of a model with its scope (`final`, the CTE name, or a nested-query key), its set-operation branch and its source line span. Comments, Jinja and literal contents are blanked in one pass that keeps offsets, so items are parsed across lines. - `rawColumnExposures` / `finalOutputs` read the final projection only. A final column read from a CTE resolves through that CTE (masked there means nothing raw), `*` over CTEs takes their outputs, and later union branches take the first branch's names. - `orchestrate.ts` parses the raw and compiled base SQL separately instead of concatenating them, and `isBaseExposed` takes the source column only (the head alias was never read). Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 62 ++-- .../src/altimate/review/rule-catalog.ts | 271 ++++++++++++++++-- .../test/altimate/review-rule-catalog.test.ts | 40 ++- .../opencode/test/altimate/review.test.ts | 19 ++ 4 files changed, 342 insertions(+), 50 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 9d04cf6db8..322641a2a1 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -14,7 +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, rawColumnExposures } from "./rule-catalog" +import { type SelectItemColumn, finalOutputs, normalizeSelectLine } from "./rule-catalog" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult, safeReason } from "./ai-review" /** @@ -1214,6 +1214,36 @@ export async function runReview(input: OrchestrateInput): Promise>() + // Per file, the base model's final output (raw and compiled base SQL, each + // parsed on its own): every output name, and the source columns each exposes RAW. + const baseOutputsByFile = new Map>() + const baseOutputs = (file: string) => { + let outputs = baseOutputsByFile.get(file) + if (!outputs) { + const ctx = ctxByPath.get(file) + outputs = { raw: new Map(), names: new Set() } + for (const sql of new Set([ctx?.oldSql, ctx?.engineOldSql].filter((x): x is string => !!x))) { + const parsed = finalOutputs(sql) + for (const n of parsed.names) outputs.names.add(n) + for (const [n, cols] of parsed.raw) outputs.raw.set(n, new Set([...(outputs.raw.get(n) ?? []), ...cols])) + } + baseOutputsByFile.set(file, outputs) + } + return outputs + } + // `detectPii` reports OUTPUT names (`c.ssn as tax_ref` → `tax_ref`): a SOURCE + // column is already exposed only when a base PII output exposes that same column + // RAW in the base's final projection, under its own name or an alias (`c.ssn as + // tax_ref` → `c.ssn as tax_id` re-exposes nothing new). An alias alone is not + // proof (`c.email as contact` → `c.ssn as contact` newly exposes `ssn`), and + // neither is a base output that only masks the column (`sha2(c.ssn) as ssn_hash`) + // or a CTE's own alias that never reaches the final select. + const isBaseExposed = (file: string, column: string) => { + const basePii = basePiiColumnsByFile.get(file) + if (!basePii) return false + const exposures = baseOutputs(file).raw + return [...basePii].some((name) => !!exposures.get(name)?.has(column)) + } for (const ctx of ctxByPath.values()) { const tasks: Promise[] = [] // Engine lanes consume COMPILED SQL (rendered by dbt) when available. @@ -1413,29 +1443,6 @@ export async function runReview(input: OrchestrateInput): Promise>>() - const baseRawExposures = (file: string) => { - let exposures = baseRawExposuresByFile.get(file) - if (!exposures) { - const ctx = ctxByPath.get(file) - exposures = rawColumnExposures([ctx?.oldSql, ctx?.engineOldSql].filter(Boolean).join("\n")) - baseRawExposuresByFile.set(file, exposures) - } - return exposures - } - // `detectPii` reports OUTPUT names (`c.ssn as tax_ref` → `tax_ref`): a SOURCE - // column is already exposed only when a base PII output exposes that same column - // RAW, under its own name or an alias (`c.ssn as tax_ref` → `c.ssn as tax_id` - // re-exposes nothing new). The line's alias alone is not proof (`c.email as - // contact` → `c.ssn as contact` newly exposes `ssn`), and neither is a base - // output that only masks the column (`sha2(c.ssn) as ssn_hash`). - const isBaseExposed = (file: string, item: { column: string; alias?: string }) => { - const basePii = basePiiColumnsByFile.get(file) - if (!basePii) return false - const exposures = baseRawExposures(file) - return [...basePii].some((name) => !!exposures.get(name)?.has(item.column)) - } const merged = flat.filter((f) => { const tool = f.evidence?.tool const fallbackRule = String((f.evidence?.result as any)?.rule ?? "").replace(/_/g, "-") @@ -1462,18 +1469,17 @@ export async function runReview(input: OrchestrateInput): Promise isReindented(f.file, i.line) || isBaseExposed(f.file, i))) return false + if (items.length && items.every((i) => isReindented(f.file, i.line) || isBaseExposed(f.file, 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 fbba8d3d89..d8bd5a35a6 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -178,8 +178,10 @@ export function selectItemColumns(line: string, tokenRe: RegExp): SelectItemColu return out } -// A column reference, optionally table-qualified (`c.ssn`); group 1 is the column. -const COLUMN_REF = String.raw`(?:[A-Za-z_][\w$]*\.)*([A-Za-z_][\w$]*)` +// One identifier segment: bare, double-quoted or backtick-quoted. +const SEGMENT = String.raw`(?:[A-Za-z_][\w$]*|"[^"]+"|` + "`[^`]+`)" +// A column reference, optionally table-qualified (`c.ssn`, `"c"."ssn"`); group 1 is the column. +const COLUMN_REF = String.raw`(?:${SEGMENT}\s*\.\s*)*(${SEGMENT})` // Select-item expressions that expose a column RAW: a bare reference, or one only // cast to a type (`cast(c.ssn as varchar)`, `c.ssn::varchar(20)`). const RAW_COLUMN_EXPRS = [ @@ -187,32 +189,259 @@ const RAW_COLUMN_EXPRS = [ new RegExp(String.raw`^cast\s*\(\s*${COLUMN_REF}\s+as\s+[\w\s(),]+\)$`, "i"), new RegExp(String.raw`^${COLUMN_REF}\s*::\s*\w+(?:\s*\([\d\s,]*\))?$`, "i"), ] +const EXPLICIT_ALIAS = new RegExp(String.raw`^([\s\S]*\S)\s+as\s+(${SEGMENT})$`, "i") +// `expr name`: the expression must end in an identifier, quote or `)`, not an operator. +const IMPLICIT_ALIAS = new RegExp(String.raw`^([\s\S]*[\w$"\x60)\]])\s+(${SEGMENT})$`, "i") +// Trailing words that end an expression rather than name it (`case … end`, `x is null`). +const NOT_AN_ALIAS = new Set( + "end null true false and or not is in then else when case like ilike between asc desc over filter within as distinct all".split( + " ", + ), +) +// Words that end a select list at its own nesting level. +const SELECT_LIST_END = + /^(from|where|group|order|limit|qualify|having|union|intersect|except|minus|window|into|fetch|offset)\b/i + +const unquote = (s: string) => s.replace(/^["`]|["`]$/g, "").toLowerCase() + +/** One item of a select list, located in its query scope. */ +export interface SelectItem { + /** Output name: the alias (with or without `AS`) or a bare column's own name. */ + name?: string + /** The column the item exposes RAW (bare or qualified reference, or only cast). */ + rawColumn?: string + /** Whitespace-normalised item text, for comparing one item across base and head. */ + text: string + /** `final` for the outermost query, the CTE name for a CTE body, `>sub` for a nested query. */ + scope: string + /** Which `UNION`/`INTERSECT`/`EXCEPT` branch of its scope (0 for the first select). */ + branch: number + /** Position in its select list. */ + position: number + /** 1-based first and last source lines the item spans. */ + startLine: number + endLine: number +} /** - * Per output name in `sql`, the columns a select item exposes RAW under that - * name (`c.ssn as tax_ref` → `tax_ref: {ssn}`, bare `ssn` → `ssn: {ssn}`). An - * item that wraps the column in any other function or expression (`sha2(c.ssn)`, + * Blank comments, Jinja tags and string-literal contents to spaces, and Jinja + * expressions to `_`, keeping every offset and newline in place so positions + * still map to source lines. One left-to-right pass, so `--` inside a literal or + * a quote inside a comment is not misread. + */ +function maskSql(sql: string): string { + return sql.replace(/\{#[\s\S]*?#\}|\{%[\s\S]*?%\}|\{\{[\s\S]*?\}\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'/g, (m) => { + if (m.startsWith("{{")) return m.replace(/[^\n]/g, "_") + if (m.startsWith("'")) return `'${m.slice(1, -1).replace(/[^\n]/g, " ")}'` + return m.replace(/[^\n]/g, " ") + }) +} + +const isWordChar = (c: string | undefined) => !!c && /[\w$."`]/.test(c) + +function describeItem(raw: string): Pick { + const text = raw + .replace(/\s+/g, " ") + .replace(/\(\s+/g, "(") + .replace(/\s+([),])/g, "$1") + .replace(/\s*\.\s*/g, ".") + .trim() + let expr = text + let alias: string | undefined + const explicit = EXPLICIT_ALIAS.exec(text) + const implicit = explicit ? null : IMPLICIT_ALIAS.exec(text) + if (explicit) [, expr, alias] = explicit + else if (implicit && !NOT_AN_ALIAS.has(unquote(implicit[2]))) [, expr, alias] = implicit + const column = RAW_COLUMN_EXPRS.map((re) => re.exec(expr)?.[1]).find(Boolean) + const rawColumn = column ? unquote(column) : undefined + return { name: alias ? unquote(alias) : rawColumn, rawColumn, text } +} + +// Words that end a FROM clause's table list at its own nesting level. +const FROM_LIST_END = /^(where|group|order|limit|qualify|having|union|intersect|except|minus|window|fetch|offset|on|using)\b/i +const SET_OPERATOR = /^(union|intersect|except|minus)\b/i + +interface ParsedSelects { + items: SelectItem[] + /** Per `scope#branch`, the table or CTE names its FROM / JOIN clauses read. */ + sources: Map +} + +function parseSelects(sql: string): ParsedSelects { + const s = maskSql(sql) + const lineStarts = [0] + for (let i = 0; i < s.length; i++) if (s[i] === "\n") lineStarts.push(i + 1) + const lineOf = (offset: number) => { + let lo = 0 + let hi = lineStarts.length - 1 + while (lo < hi) { + const mid = (lo + hi + 1) >> 1 + if (lineStarts[mid] <= offset) lo = mid + else hi = mid - 1 + } + return lo + 1 + } + const items: SelectItem[] = [] + const sources = new Map() + const scopes: string[] = ["final"] + const branches = new Map() + const cteHead = new RegExp(String.raw`(${SEGMENT})\s+as\s*(?:(?:not\s+)?materialized\s*)?$`, "i") + const tableRef = new RegExp(String.raw`^\s*((?:${SEGMENT}\s*\.\s*)*${SEGMENT})`, "i") + let nested = 0 + for (let i = 0; i < s.length; i++) { + const c = s[i] + if (c === "(") { + const parent = scopes[scopes.length - 1] + const cte = cteHead.exec(s.slice(Math.max(0, i - 200), i)) + // A CTE body is named by its CTE; a nested query gets its own scope; any + // other parenthesis (a call, a grouping) stays in its parent's scope. + if (cte && !/^as$/i.test(cte[1])) scopes.push(unquote(cte[1])) + else if (/^[\s(]*select\b/i.test(s.slice(i + 1, i + 200))) scopes.push(`${parent}>sub${++nested}`) + else scopes.push(parent) + continue + } + if (c === ")") { + if (scopes.length > 1) scopes.pop() + continue + } + if ((c !== "s" && c !== "S") || isWordChar(s[i - 1]) || !/^select\b/i.test(s.slice(i, i + 7))) continue + const scope = scopes[scopes.length - 1] + const branch = branches.get(scope) ?? 0 + branches.set(scope, branch + 1) + // The list runs from after `select [distinct|all|top n]` to the first clause + // keyword, `)` or `;` at its own nesting level. + let start = i + 6 + const prefix = /^\s+(?:(?:distinct|all)\b|top\s+\d+\b)?/i.exec(s.slice(start)) + if (prefix) start += prefix[0].length + let depth = 0 + let itemStart = start + let position = 0 + let end = s.length + const push = (stop: number) => { + const raw = s.slice(itemStart, stop) + if (!raw.trim()) return + const first = itemStart + (raw.length - raw.trimStart().length) + const last = itemStart + raw.trimEnd().length - 1 + items.push({ ...describeItem(raw), scope, branch, position: position++, startLine: lineOf(first), endLine: lineOf(last) }) + } + for (let j = start; j <= s.length; j++) { + const d = s[j] + if (j === s.length || (depth === 0 && (d === ")" || d === ";"))) { + push(j) + end = j + break + } + if (d === "(") depth++ + else if (d === ")") depth-- + else if (depth === 0 && d === ",") { + push(j) + itemStart = j + 1 + } else if (depth === 0 && !isWordChar(s[j - 1]) && SELECT_LIST_END.test(s.slice(j, j + 10))) { + push(j) + end = j + break + } + } + // Tables read at this select's own level: the name after `from`, `join`, or a + // `,` inside a FROM list, up to the end of the select (`)`, `;`, a set operator). + const read: string[] = [] + let inFrom = false + depth = 0 + for (let j = end; j < s.length; j++) { + const d = s[j] + if (depth === 0 && (d === ")" || d === ";")) break + if (d === "(") depth++ + else if (d === ")") depth-- + if (depth !== 0) continue + const boundary = !isWordChar(s[j - 1]) + if (boundary && SET_OPERATOR.test(s.slice(j, j + 10))) break + const kw = boundary ? /^(from|join)\b/i.exec(s.slice(j, j + 5)) : null + if (kw || (inFrom && d === ",")) { + const after = j + (kw ? kw[0].length : 1) + const ref = tableRef.exec(s.slice(after, after + 300)) + if (ref) read.push(unquote(ref[1].split(".").pop()!.trim())) + inFrom = true + j = after - 1 + } else if (boundary && FROM_LIST_END.test(s.slice(j, j + 10))) inFrom = false + } + sources.set(`${scope}#${branch}`, read) + } + return { items, sources } +} + +/** + * Every select list in `sql`, item by item, with the query scope each belongs + * to. Scope is what separates a CTE's `ssn as contact` from the final select's + * `email as contact`: only `final` items are the model's output. Items are + * parsed across lines, so a multi-line expression or alias is one item. + */ +export function selectItems(sql: string): SelectItem[] { + return parseSelects(sql).items +} + +const STAR = new RegExp(String.raw`^(?:${SEGMENT}\.)*\*$`) + +/** + * Per output name of the model (its FINAL projection, never a CTE's or a + * nested query's own aliases), the source columns it exposes RAW under that + * name (`c.ssn as tax_ref` → `tax_ref: {ssn}`, bare `ssn` → `ssn: {ssn}`). + * A final item that reads a CTE takes the CTE's exposure for that column + * (`select contact from b` with `b` = `select email as contact` → `contact: + * {email}`), and `*` over CTEs takes all of theirs. A later set-operation + * branch takes the first branch's name at the same position. An item that + * wraps the column in any other function or expression (`sha2(c.ssn)`, * `left(c.ssn, 4)`, `case …`, `a || b`) exposes nothing raw and is left out. */ export function rawColumnExposures(sql: string): Map> { - const out = new Map>() - for (const line of sql.split("\n")) { - for (const item of topLevelItems(stripLiterals(stripComments(line)))) { - const s = item - .trim() - .replace(/^select\s+(?:distinct\s+)?/i, "") - .replace(/\s+from\s[\s\S]*$/i, "") - const aliased = /^([\s\S]*\S)\s+as\s+["`]?([A-Za-z_][\w$]*)["`]?$/i.exec(s) - const expr = aliased ? aliased[1] : s - const column = RAW_COLUMN_EXPRS.map((re) => re.exec(expr)?.[1]).find(Boolean)?.toLowerCase() - if (!column) continue - const name = aliased?.[2]?.toLowerCase() ?? column - const columns = out.get(name) ?? new Set() - columns.add(column) - out.set(name, columns) + return finalOutputs(sql).raw +} + +/** The model's final output: every name it resolves (`names`) and, per name, the + * source columns exposed raw under it (`raw`, as `rawColumnExposures`). */ +export function finalOutputs(sql: string): { raw: Map>; names: Set } { + const { items, sources } = parseSelects(sql) + const byScope = new Map() + for (const item of items) byScope.set(item.scope, [...(byScope.get(item.scope) ?? []), item]) + const memo = new Map>; names: Set }>() + const resolve = (scope: string, seen: Set) => { + const cached = memo.get(scope) + if (cached) return cached + const raw = new Map>() + const names = new Set() + const add = (name: string, cols: Iterable) => { + const set = raw.get(name) ?? new Set() + for (const col of cols) set.add(col) + raw.set(name, set) } + const scopeItems = byScope.get(scope) ?? [] + const firstNames = new Map(scopeItems.filter((i) => i.branch === 0).map((i) => [i.position, i.name])) + for (const item of scopeItems) { + const ctes = (sources.get(`${scope}#${item.branch}`) ?? []) + .filter((src) => src !== scope && byScope.has(src) && !seen.has(src)) + .map((src) => resolve(src, new Set([...seen, scope]))) + if (STAR.test(item.text)) { + for (const cte of ctes) { + for (const n of cte.names) names.add(n) + for (const [n, cols] of cte.raw) add(n, cols) + } + continue + } + const name = item.branch === 0 ? item.name : firstNames.get(item.position) + if (!name) continue + names.add(name) + if (!item.rawColumn) continue + // A column a source CTE outputs resolves through that CTE (masked there → + // nothing raw); one no CTE outputs comes straight from a table. + const via = ctes.filter((cte) => cte.names.has(item.rawColumn!)) + if (via.length) add(name, via.flatMap((cte) => [...(cte.raw.get(item.rawColumn!) ?? [])])) + else add(name, [item.rawColumn]) + } + for (const [n, cols] of raw) if (!cols.size) raw.delete(n) + const result = { raw, names } + memo.set(scope, result) + return result } - return out + return resolve("final", new Set()) } /** A diff line with comments and whitespace normalised (and a leading/trailing diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 6dbddc0486..c4634d00f0 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -1,5 +1,5 @@ import { describe, test, expect } from "bun:test" -import { CATALOG, ruleMatches, inputFromExample, selectItemColumns } from "../../src/altimate/review/rule-catalog" +import { CATALOG, ruleMatches, inputFromExample, rawColumnExposures, selectItemColumns } from "../../src/altimate/review/rule-catalog" describe("rule catalog (self-verifying scenario corpus)", () => { test("every rule fires on its example and stays clean on its counter", () => { @@ -42,3 +42,41 @@ describe("selectItemColumns", () => { ]) }) }) + +describe("rawColumnExposures", () => { + const asObject = (m: Map>) => Object.fromEntries([...m].map(([k, v]) => [k, [...v].sort()])) + test("reads the final projection only, not a CTE's own aliases", () => { + const sql = "with h as (\n select ssn as contact\n from customers\n)\nselect c.email as contact from customers c" + expect(asObject(rawColumnExposures(sql))).toEqual({ contact: ["email"] }) + }) + test("resolves a final column through the CTE it reads, and `*` over a CTE", () => { + const sql = [ + "with src as (select * from {{ ref('customers') }}),", + "final as (select id, sha2(phone) as phone, ssn, email as contact from src)", + "select * from final", + ].join("\n") + expect(asObject(rawColumnExposures(sql))).toEqual({ id: ["id"], ssn: ["ssn"], contact: ["email"] }) + expect(asObject(rawColumnExposures("with b as (select email as contact from c) select contact from b"))).toEqual({ + contact: ["email"], + }) + }) + test("parses a select item whose alias is on another line", () => { + const sql = "select c.customer_id,\n c.ssn\n as tax_ref\nfrom customers c" + expect(asObject(rawColumnExposures(sql))).toEqual({ customer_id: ["customer_id"], tax_ref: ["ssn"] }) + }) + test("accepts quoted identifiers", () => { + expect(asObject(rawColumnExposures('select "c"."ssn" as "tax_ref" from customers "c"'))).toEqual({ tax_ref: ["ssn"] }) + }) + test("accepts an alias without AS, and not a trailing keyword", () => { + const sql = "select c.ssn tax_ref, cast(c.dob as date) dob_day, case when x then y end, sha2(c.email) em from c" + expect(asObject(rawColumnExposures(sql))).toEqual({ tax_ref: ["ssn"], dob_day: ["dob"] }) + }) + test("names a later set-operation branch by the first branch's position", () => { + const sql = "select id, ssn as tax_ref from a\nunion all\nselect id, email from b" + expect(asObject(rawColumnExposures(sql))).toEqual({ id: ["id"], tax_ref: ["email", "ssn"] }) + }) + test("ignores commas and keywords inside literals and comments", () => { + const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" + expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["ssn"], c: ["email"] }) + }) +}) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 4e8357a1c1..e583dbe246 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2370,6 +2370,25 @@ describe("orchestrate", () => { } }) + test("a CTE alias does not count as a base exposure of the final output", async () => { + // Base CTE `ssn as contact`, base final `c.email as contact`: the base's + // output `contact` carried `email`, never raw `ssn`. + const base = + "with hashed as (\n select ssn as contact from customers\n)\nselect c.customer_id,\n c.email as contact\nfrom customers c" + const head = base.replace(" c.email as contact", " c.ssn as contact") + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- c.email as contact\n+ c.ssn as contact\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["email", "ssn"]), + getContent: content(head, base), + }) + 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(["ssn"]) + expect(env.verdict).toBe("REQUEST_CHANGES") + }) + 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({ From 4e255464aa8ae494893f554e57b7ff1af834611c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 15:59:44 +0530 Subject: [PATCH 11/81] fix(review): suppress a broad-fallback PII column only when the base exposed its source raw The fallback dropped any head PII output whose NAME the base already output, so base `md5(home_address) as home_address` -> head `home_address` (masking removed) went unreported. `isBaseExposedOutput` (`orchestrate.ts`) now reads the head's final projection: a name the head selects a column raw under is suppressed only when the base's final output exposed that same source column raw; a head output that is not a raw column is suppressed when the base had the name; a name the head does not resolve (`select *` from a table) counts only when the base had it and did not mask it. - `c.email as contact` -> `c.ssn as contact` is now reported by the fallback in tiers that run the `pii_exposure` lane (the regex twin still covers the others); the test accepts either detector. - The alias-rename control (`c.ssn as tax_ref` -> `c.ssn as tax_id`) now asserts no `pii_exposure` finding at all, not only no regex twin. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 19 ++++++++- .../opencode/test/altimate/review.test.ts | 40 +++++++++++++++++-- 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 322641a2a1..18039ca0f2 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1244,6 +1244,21 @@ export async function runReview(input: OrchestrateInput): Promise !!exposures.get(name)?.has(column)) } + // A head PII output name the base already exposed. When the head selects a + // column raw under it, that same source column must be raw in the base's final + // output (base `md5(home_address) as home_address` → head `home_address` is new). + // A head output that is not a raw column exposes no new raw value when the base + // had the name. A name the head's final select doesn't resolve (`select *` from a + // table) counts as base-exposed only when the base had it and did not mask it. + const isBaseExposedOutput = (file: string, name: string, basePii: Set) => { + const head = finalOutputs(ctxByPath.get(file)?.engineNewSql ?? "") + const rawColumns = head.raw.get(name) + if (rawColumns?.size) return [...rawColumns].every((col) => isBaseExposed(file, col)) + if (!basePii.has(name)) return false + if (head.names.has(name)) return true + const base = baseOutputs(file) + return !base.names.has(name) || base.raw.has(name) + } for (const ctx of ctxByPath.values()) { const tasks: Promise[] = [] // Engine lanes consume COMPILED SQL (rendered by dbt) when available. @@ -1307,7 +1322,9 @@ 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) => !basePii.has(col.toLowerCase())) + fallbackPii = fallbackPii.filter( + (col) => !isBaseExposedOutput(currentCtx.file.path, col.toLowerCase(), basePii), + ) const baseUnknown = hasOldSide(currentCtx.file) && !currentCtx.engineOldSql findings.push(...piiLane(currentCtx.file, fallbackPii, baseUnknown)) } diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index e583dbe246..cefe1370a0 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2331,7 +2331,8 @@ describe("orchestrate", () => { test("an alias the base exposes from a different source does not hide a newly exposed PII column", async () => { // Same output alias, different source: base `c.email as contact`, head // `c.ssn as contact`. detectPii and the classifier see `contact` on both - // sides, so the regex twins are the only detectors left and must stay. + // sides. The broad fallback (tiers with the pii_exposure lane) reports it + // because the base never exposed raw `ssn`; otherwise the regex twin must. for (const [from, to] of [ ["c.email as contact", "c.ssn as contact"], ["c.email as customer_key", "c.ssn as customer_key"], @@ -2346,9 +2347,15 @@ describe("orchestrate", () => { runner: piiRunner(["email", "ssn"]), getContent: content(base.replace(from, to), base), }) + const broad = env.findings.filter((f) => f.evidence?.tool === "schema.detect_pii") 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(["ssn"]) - expect(intoMart[0].severity).toBe("critical") + if (broad.length) { + expect((broad[0].evidence?.result as any)?.columns).toEqual([to.split(" as ")[1]]) + expect(broad[0].severity).toBe("critical") + } else { + expect(intoMart.map((f) => (f.evidence?.result as any)?.column)).toEqual(["ssn"]) + expect(intoMart[0].severity).toBe("critical") + } expect(env.verdict).toBe("REQUEST_CHANGES") } } @@ -2366,10 +2373,35 @@ describe("orchestrate", () => { runner: piiRunner(["ssn"]), getContent: content(base.replace("tax_ref", "tax_id"), base), }) - expect(env.findings.filter(isTwin)).toEqual([]) + expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) } }) + test("the broad fallback keeps a PII column the base exposed only masked under the same name", async () => { + // base `md5(home_address) as home_address` → head `home_address`: detectPii + // reports `home_address` on both sides, but the base never exposed it raw. + const masked = "select customer_id,\n md5(home_address) as home_address\nfrom customers" + const raw = "select customer_id,\n home_address\nfrom customers" + const run = (head: string, base: string, diff: string) => + runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["pii_exposure"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["home_address"]), + getContent: content(head, base), + }) + const unmasked = await run(raw, masked, "- md5(home_address) as home_address\n+ home_address\n") + const broad = unmasked.findings.filter((f) => f.evidence?.tool === "schema.detect_pii") + expect(broad.map((f) => (f.evidence?.result as any)?.columns)).toEqual([["home_address"]]) + expect(broad[0].severity).toBe("critical") + // Controls: masking a raw base column, or reindenting a raw one, exposes nothing new. + const maskedNow = await run(masked, raw, "- home_address\n+ md5(home_address) as home_address\n") + expect(maskedNow.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + const reindented = await run(raw.replace(" home", " home"), raw, "- home_address\n+ home_address\n") + expect(reindented.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + }) + test("a CTE alias does not count as a base exposure of the final output", async () => { // Base CTE `ssn as contact`, base final `c.email as contact`: the base's // output `contact` carried `email`, never raw `ssn`. From bc71523d054492fd80a8d23a8852535697d47e53 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 15:59:58 +0530 Subject: [PATCH 12/81] fix(review): exempt a PII line as a reindent only when its select item and scope are unchanged `isReindented` accepted an added line whose normalised text matched a removed line anywhere in the file. `email,` removed from a CTE and added to the final select, or the `ssn` line left when `sha2(\n ssn\n) as contact` is unwrapped, both read as reindents and both regex PII twins were dropped, including a gate-blocking critical in tiers without the broad lane. The exemption now also requires every head select item spanning that line to exist in the base with the same normalised text, in the same scope (the same CTE, nested query or final select) and set-operation branch. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 33 +++++--- .../opencode/test/altimate/review.test.ts | 77 +++++++++++++++++++ 2 files changed, 101 insertions(+), 9 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 18039ca0f2..d1b1ff226b 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -14,7 +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, finalOutputs, normalizeSelectLine } from "./rule-catalog" +import { type SelectItem, type SelectItemColumn, finalOutputs, normalizeSelectLine, selectItems } from "./rule-catalog" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult, safeReason } from "./ai-review" /** @@ -1448,17 +1448,32 @@ export async function runReview(input: OrchestrateInput): Promise>() + // An added line is a pure reindent (or comment/comma-only edit) only when it + // matches a removed line AND every select item it belongs to in the head is the + // same item, in the same query scope (CTE, nested query or final select), in the + // base. Matching a removed line elsewhere is not enough: `email,` moved from a + // CTE into the final select, or `ssn` left behind when `sha2(\n ssn\n) as x` + // is unwrapped, exposes something new. + const reindentByFile = new Map; head: SelectItem[]; headLines: string[]; base: Set }>() + const itemKey = (i: SelectItem) => `${i.scope}#${i.branch}\u0000${i.text.toLowerCase()}` 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 ctx = ctxByPath.get(file) + if (!ctx?.newSql || !ctx.oldSql) return false + let r = reindentByFile.get(file) + if (!r) { + r = { + removed: new Set(splitDiff(ctx.file.diff).removed.map(normalizeSelectLine).filter(Boolean)), + head: selectItems(ctx.newSql), + headLines: ctx.newSql.split("\n").map(normalizeSelectLine), + base: new Set(selectItems(ctx.oldSql).map(itemKey)), + } + reindentByFile.set(file, r) } const normalized = normalizeSelectLine(line) - return !!normalized && removed.has(normalized) + if (!normalized || !r.removed.has(normalized)) return false + const lineNos = r.headLines.flatMap((l, i) => (l === normalized ? [i + 1] : [])) + const items = r.head.filter((i) => lineNos.some((n) => i.startLine <= n && n <= i.endLine)) + return items.length > 0 && items.every((i) => r.base.has(itemKey(i))) } const merged = flat.filter((f) => { const tool = f.evidence?.tool diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index cefe1370a0..5667d08b33 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2402,6 +2402,83 @@ describe("orchestrate", () => { expect(reindented.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) }) + test("a PII line moved from a CTE into the final select is not a reindent", async () => { + // ` email,` leaves the CTE and the same text lands in the final select: the + // model's output now carries `email`, though the line matches a removed one. + const base = [ + "with c as (", + " select", + " customer_id,", + " email,", + " region", + " from customers", + ")", + "select", + " customer_id,", + " region", + "from c", + ].join("\n") + const head = [ + "with c as (", + " select", + " customer_id,", + " region", + " from customers", + ")", + "select", + " customer_id,", + " email,", + " region", + "from c", + ].join("\n") + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff: "- email,\n+ email,\n" }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner([]), + getContent: content(head, base), + }) + 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(["email"]) + } + }) + + test("a column left on its own line when a multi-line mask is unwrapped is not a reindent", async () => { + // `sha2(\n ssn\n ) as contact` → `ssn\n as contact`: the `ssn` line matches + // the removed hash-input line, but the final item went from masked to raw. + const base = "select customer_id,\n sha2(\n ssn\n ) as contact\nfrom customers" + const head = "select customer_id,\n ssn\n as contact\nfrom customers" + const env = await runReview({ + changedFiles: [ + { + path: "models/marts/m.sql", + status: "modified", + diff: "- sha2(\n- ssn\n- ) as contact\n+ ssn\n+ as contact\n", + }, + ], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner([]), + getContent: content(head, base), + }) + 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(["ssn"]) + expect(intoMart[0].severity).toBe("critical") + // Control: the same final-select item, only reindented, stays quiet. + const same = 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(base.replace(" ssn", " ssn"), base), + }) + expect(same.findings.filter(isTwin)).toEqual([]) + }) + test("a CTE alias does not count as a base exposure of the final output", async () => { // Base CTE `ssn as contact`, base final `c.email as contact`: the base's // output `contact` carried `email`, never raw `ssn`. From 1765b8d3e127fbe5b4571def131cc5378e8bdea4 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 16:00:40 +0530 Subject: [PATCH 13/81] fix(review): dedup inline findings only against this bot's own review comments `postGitHubReview` collected `` markers from every review comment on the PR, so anyone (the PR author, another bot quoting a comment) could post a marker and silently suppress that inline finding, including a critical. Markers now count only in comments authored by the bot login (the summary comment's author); with no known login nothing is deduped. Also notes why `inlineSkippedAsPosted` is a plain difference. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/post-github.ts | 6 +++++- .../opencode/test/altimate/review-noise.test.ts | 17 ++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index fb3010d8c1..a7bfbf2316 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -114,7 +114,9 @@ export async function postGitHubReview( 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)) + // Only this bot's own comments count: a marker anyone else posts (or quotes) + // must not suppress a finding. Unknown bot login: dedup nothing. + posted = postedFindingIds(reviewComments.filter((c) => !!botLogin && c.user?.login === botLogin).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 ?? "")) @@ -135,6 +137,8 @@ export async function postGitHubReview( /* fall back to the positioning retry below */ } const comments = inlineComments(env, posted, commentable) + // Both calls use the same `commentable`, so the difference is exactly the + // comments skipped because this bot already posted them. result.inlineSkippedAsPosted = inlineComments(env, new Set(), commentable).length - comments.length // Nothing new inline, not blocking, and this bot's latest review already says diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index fe111bc0a3..72506bdfde 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -355,6 +355,7 @@ describe("postGitHubReview", () => { reviews?: Array<{ body: string; user?: { login: string } }> listFails?: boolean files?: Array<{ filename: string; patch?: string }> + reviewComments?: Array<{ body: string; user?: { login: string } }> createReview?: (call: number) => unknown } = {}, ) { @@ -371,7 +372,7 @@ describe("postGitHubReview", () => { updateComment: async () => ({ data: { id: 1, user: { login: BOT } } }), }, pulls: { - listReviewComments: opts.listFails ? fail : async () => [], + listReviewComments: opts.listFails ? fail : async () => opts.reviewComments ?? [], 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" } } }), @@ -454,6 +455,20 @@ describe("postGitHubReview", () => { ]) }) + test("a finding marker counts only in this bot's own review comments", async () => { + const env = buildEnvelope({ findings: [finding({ startLine: 3, title: "m: a" })], tier: "lite", mode: "comment" }) + const [first] = inlineComments(env, new Set(), undefined) + // Another account posting (or quoting) the marker does not suppress the finding. + const foreign = fakeOcto({ reviewComments: [{ body: first.body, user: { login: "pr-author" } }] }) + const r = await postGitHubReview(env, target, foreign.octo) + expect(foreign.reviewCalls[0].comments.map((c: { line: number }) => c.line)).toEqual([3]) + expect(r.inlineSkippedAsPosted).toBe(0) + // The bot's own earlier comment does. + const own = fakeOcto({ reviewComments: [{ body: first.body, user: { login: BOT } }] }) + const again = await postGitHubReview(env, target, own.octo) + expect(again.inlineSkippedAsPosted).toBe(1) + }) + 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" })], From 1b4ffd1fe1270fc2120f2e9fffa23c372b5f56bd Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 16:02:00 +0530 Subject: [PATCH 14/81] fix(review): keep PIVOT and string-interval advice on engines that lack them `pivot-portability` and `interval-string-literal` had no `worksOn`, and `isSuppressiblePortability` treated a missing list as "works everywhere", so a dbt-postgres project lost the PIVOT error and a BigQuery project lost the `interval '1 day'` error. - PIVOT/UNPIVOT works on snowflake, bigquery, databricks, redshift, tsql, oracle, duckdb (not postgres, mysql, trino, athena). - `interval '1 day'` works on postgres, redshift, snowflake, duckdb, databricks (not bigquery, mysql, tsql, oracle, trino, athena). - A portability rule without `worksOn` is no longer suppressible: support that was never established may be an error on the project's engine. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 9 ++-- .../src/altimate/review/rule-catalog.ts | 19 +++++++-- .../test/altimate/review-noise.test.ts | 41 ++++++++++++++++++- 3 files changed, 60 insertions(+), 9 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index d1b1ff226b..c593a544e5 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -217,14 +217,15 @@ export function isCatalogPortability(f: Finding): boolean { } /** - * 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. + * Portability advice that is noise for a project on `dialect`: dropped only + * when the rule names `dialect` among the engines that support the construct. + * Otherwise (engine not listed, or support never established) it may be an + * error on this project's own engine and is kept. */ 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()) + return !!worksOn && worksOn.includes(dialect.toLowerCase()) } /** True when SQL text contains Jinja (`{{ }}`, `{% %}` or `{# #}`). */ diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index d8bd5a35a6..56da06e00d 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -46,8 +46,10 @@ export interface Rule { 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. + * engine only when that engine is listed in `worksOn` (dialect names as + * `run.ts` maps them: `postgres`, `tsql`, `databricks`, ...). An engine + * missing from it, or a rule with no `worksOn`, keeps the advice: it may be + * a real error on that engine. */ portability?: { worksOn?: string[] } /** Column-token pattern (first capture group is the column name) collected on @@ -2080,7 +2082,11 @@ 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, portability: {} }, + { + added: /\b(pivot|unpivot)\s*\(/i, + // No PIVOT/UNPIVOT on Postgres, MySQL, Trino or Athena. + portability: { worksOn: ["snowflake", "bigquery", "databricks", "redshift", "tsql", "oracle", "duckdb"] }, + }, { add: "from t pivot(sum(x) for k in ('a'))" }, { add: "sum(case when k='a' then x end)" }, ), @@ -2110,7 +2116,12 @@ 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, portability: {} }, + { + added: /interval\s+'\d+\s*\w+'/i, + // BigQuery, MySQL, T-SQL, Oracle, Trino and Athena need `INTERVAL 1 DAY` / + // `INTERVAL '1' DAY` (or have no interval literal). + portability: { worksOn: ["postgres", "redshift", "snowflake", "duckdb", "databricks"] }, + }, { add: "d + interval '1 day'" }, { add: "dateadd(day, 1, d)" }, ), diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 72506bdfde..70e3d3f72b 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -287,7 +287,8 @@ describe("portability noise", () => { 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) + // Support never established: the advice may be an error here, so it stays. + expect(isSuppressiblePortability(untagged, "snowflake")).toBe(false) }) test("catalog portability advice is recognised; core's dialect-aware check is not", () => { @@ -330,6 +331,44 @@ describe("portability noise", () => { // 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) }) + + test("PIVOT is kept on Postgres and a string interval literal on BigQuery; both drop where they work", 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 rules = async (sql: string, dialect: string) => { + const env = await runReview({ + changedFiles: [{ path: "models/m.sql", status: "added" as const, diff: `+${sql}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"], dialect }, + rubric: DEFAULT_RUBRIC, + mode: "comment" as const, + runner, + getContent: async () => sql, + suppressPortability: true, + }) + return env.findings.filter(isCatalogPortability).map((f) => (f.evidence?.result as any)?.rule) + } + const pivot = "select * from t pivot(sum(x) for k in ('a'))" + expect(await rules(pivot, "postgres")).toContain("pivot-portability") + expect(await rules(pivot, "snowflake")).not.toContain("pivot-portability") + const interval = "select d + interval '1 day' as next_day from t" + expect(await rules(interval, "bigquery")).toContain("interval-string-literal") + expect(await rules(interval, "postgres")).not.toContain("interval-string-literal") + }) }) describe("moved files", () => { From 2aa4fd1014c333d24246243661afd16b75309c79 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 16:05:04 +0530 Subject: [PATCH 15/81] fix(review): stop the summary at the first finding that does not fit, and budget its metadata - The budget loop skipped a bullet that did not fit and kept going, so a short suggestion could be listed while an earlier critical was hidden. It now stops at the first bullet that does not fit; a partly listed severity shows `k of N` in its heading, and the overflow line counts hidden findings per severity (`11 more finding(s) not shown (1 critical, 10 suggestion)`). - The fixed metadata bypassed the ~5K budget (and the no-findings branch returned before any check). Tier reasons, coverage notes, the AI-lane reason and the override reason now get a share of the budget each: whole reasons, paths and notes only, with `+N more`, and free text cut at a word boundary. Local output (`maxChars: Infinity`) is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 137 ++++++++++++------ .../test/altimate/review-noise.test.ts | 54 +++++++ 2 files changed, 149 insertions(+), 42 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 0d73434108..d7afa32651 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -59,7 +59,7 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s "", ) } - lines.push(...coverageNotes(env)) + lines.push(...coverageNotes(env, budget(maxChars, NOTES_SHARE))) // G1 (Round 18) — surface classifier reasons when --explain-tier populated // them, so a customer can see why the review ran at this tier. Also surfaces @@ -73,29 +73,27 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s // Pick an inline-code-span fence longer than any backtick run inside `r` // so a path like `packages/…/foo`bar`.sql` cannot terminate the span // (cubic-review P3). - const shown = env.tierReasons - .slice(0, RENDER_CAP) - .map((r) => { - const runs = r.match(/`+/g) - const maxRun = runs ? Math.max(...runs.map((run) => run.length)) : 0 - const fence = "`".repeat(maxRun + 1) - // If the reason itself starts/ends with a backtick, pad with a space so - // the leading/trailing backtick isn't glued to the fence. - const pad = /^`|`$/.test(r) ? " " : "" - return `${fence}${pad}${r}${pad}${fence}` - }) - .join(", ") - const overflow = - env.tierReasons.length > RENDER_CAP - ? ` (+${env.tierReasons.length - RENDER_CAP} more in verdict envelope)` - : "" - lines.push(`> 🧭 **Tier: ${env.tier}** — ${shown}${overflow}`, "") + const spans = env.tierReasons.slice(0, RENDER_CAP).map((r) => { + const runs = r.match(/`+/g) + const maxRun = runs ? Math.max(...runs.map((run) => run.length)) : 0 + const fence = "`".repeat(maxRun + 1) + // If the reason itself starts/ends with a backtick, pad with a space so + // the leading/trailing backtick isn't glued to the fence. + const pad = /^`|`$/.test(r) ? " " : "" + return `${fence}${pad}${r}${pad}${fence}` + }) + // Whole reasons only, within the tier line's share of the budget. + const prefix = `> 🧭 **Tier: ${env.tier}** — ` + const shown = takeWhole(spans, budget(maxChars, TIER_SHARE) - prefix.length - 60, ", ") + const rest = env.tierReasons.length - shown.length + const overflow = rest ? `${shown.length ? " " : ""}(+${rest} more in verdict envelope)` : "" + lines.push(`${prefix}${shown.join(", ")}${overflow}`, "") } const tail: string[] = [] if (env.override) { tail.push( - `> 🔓 **Break-glass override** by @${env.override.by}: ${env.override.reason}`, + `> 🔓 **Break-glass override** by @${env.override.by}: ${clip(env.override.reason, budget(maxChars, OVERRIDE_SHARE))}`, `> (would have been \`${env.override.priorVerdict}\`)`, "", ) @@ -116,37 +114,48 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s } // 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 + // Listing stops at the first bullet that does not fit, so a later, shorter + // finding is never shown while a more severe one is hidden. What does not fit + // is counted per severity, never silently dropped: the envelope keeps every + // finding. The reserve keeps room for the "… N more finding(s)" line. + const overflowReserve = 260 let used = [...lines, ...tail].join("\n").length + overflowReserve - let hidden = 0 + const hidden: Record = { critical: 0, warning: 0, suggestion: 0 } + let full = false 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 + const shown: string[] = [] + let shownCount = 0 + // Room for the heading in its longest form (`k of N`). + let headCost = `### ${SEVERITY_EMOJI[sev]} ${capitalize(sev)} (${items.length} of ${items.length})`.length + 3 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 + const cost = b.text.length + 1 + headCost + if (full || used + cost > maxChars) { + full = true + hidden[sev] += b.count continue } - if (!headed) { - lines.push(...heading) - headed = true - } - lines.push(b.text) + shown.push(b.text) + shownCount += b.count used += cost + headCost = 0 } - if (headed) lines.push("") + if (!shown.length) continue + const count = shownCount < items.length ? `${shownCount} of ${items.length}` : `${items.length}` + lines.push(`### ${SEVERITY_EMOJI[sev]} ${capitalize(sev)} (${count})`, "", ...shown, "") } - if (hidden) { + const hiddenTotal = hidden.critical + hidden.warning + hidden.suggestion + if (hiddenTotal) { + const bySeverity = (["critical", "warning", "suggestion"] as const) + .filter((sev) => hidden[sev]) + .map((sev) => `${hidden[sev]} ${sev}`) + .join(", ") lines.push( - `> … ${hidden} more finding(s) not shown to keep this comment short — the full list is in the verdict envelope ` + + `> … ${hiddenTotal} more finding(s) not shown (${bySeverity}) to keep this comment short — the full list is in the verdict envelope ` + "(`altimate review --json`, or the action's `--output` artifact).", "", ) @@ -154,6 +163,37 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s return [...lines, ...tail].join("\n") } +// Shares of the comment budget for the fixed metadata, so it never crowds out +// the findings or pushes the comment past the budget on its own. +const TIER_SHARE = 0.15 +const NOTES_SHARE = 0.25 +const OVERRIDE_SHARE = 0.1 + +/** `share` of a finite budget; unlimited stays unlimited. */ +function budget(maxChars: number, share: number): number { + return maxChars === Infinity ? Infinity : Math.floor(maxChars * share) +} + +/** The leading whole units whose `sep`-joined length fits in `max`. */ +function takeWhole(units: string[], max: number, sep: string): string[] { + const out: string[] = [] + let len = 0 + for (const u of units) { + const next = len + (out.length ? sep.length : 0) + u.length + if (next > max) break + out.push(u) + len = next + } + return out +} + +/** Free text cut at a word boundary to fit `max` (with `…`). */ +function clip(text: string, max: number): string { + if (text.length <= max) return text + const cut = text.slice(0, Math.max(0, max - 1)) + return `${cut.replace(/\s+\S*$/, "") || cut}…` +} + /** Backticked names blanked, so the same rule on different models/columns * normalizes to the same text. */ function blankNames(s: string): string { @@ -216,7 +256,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou * the advisory AI lane when it did not run. Kept separate from the lint-only * banner so one undecidable finding never mislabels a manifest-backed run. */ -export function coverageNotes(env: VerdictEnvelope): string[] { +export function coverageNotes(env: VerdictEnvelope, maxChars = Infinity): string[] { const notes: string[] = [] const undecided = env.findings.filter((f) => f.degraded).length if (undecided) notes.push(`${undecided} finding(s) could not be decided by the engine and are marked _unverified_.`) @@ -226,9 +266,15 @@ export function coverageNotes(env: VerdictEnvelope): string[] { const byReason = new Map() for (const u of unverified) byReason.set(u.reason, [...(byReason.get(u.reason) ?? []), u.path]) for (const [reason, paths] of byReason) { - const head = paths.slice(0, 5).map((p) => `\`${p}\``).join(", ") - const more = paths.length > 5 ? ` and ${paths.length - 5} more` : "" - notes.push(`${paths.length} model(s) not verified by the engine — ${reason}: ${head}${more}.`) + const label = `${paths.length} model(s) not verified by the engine — ${clip(reason, 200)}` + // Whole paths only: at most 5, and within an even share of the notes budget. + const shown = takeWhole( + paths.slice(0, 5).map((p) => `\`${p}\``), + maxChars / (byReason.size + 1) - label.length - 30, + ", ", + ) + const more = paths.length > shown.length ? `${shown.length ? " and " : " "}${paths.length - shown.length} more` : "" + notes.push(`${label}:${shown.length ? " " : ""}${shown.join(", ")}${more}.`) } notes.push("Run `dbt compile` (and compile the base into `target-base/`) for equivalence and lineage checks.") } @@ -241,9 +287,16 @@ export function coverageNotes(env: VerdictEnvelope): string[] { ) 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}` : ""}.`) + notes.push(`Advisory AI review ${what}${env.ai.reason ? `: ${clip(env.ai.reason, 200)}` : ""}.`) } - return notes.length ? [...notes.map((n) => `> ℹ️ ${n}`), ""] : [] + // Whole notes within the budget; the rest are counted. + const lines = takeWhole( + notes.map((n) => `> ℹ️ ${n}`), + maxChars - 80, + "\n", + ) + if (lines.length < notes.length) lines.push(`> ℹ️ +${notes.length - lines.length} more note(s) in the verdict envelope.`) + return lines.length ? [...lines, ""] : [] } /** GitHub `pulls.createReview` inline comments — only findings with a line. */ diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 70e3d3f72b..882a71ba6e 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -254,6 +254,60 @@ describe("summary grouping and budget", () => { // Local output is complete. expect(renderSummary(env, { maxChars: Infinity })).toContain("m199: distinct issue number 199") }) + + test("a critical that does not fit stops the listing: no later, shorter finding jumps ahead of it", () => { + const fs: Finding[] = [ + finding({ severity: "critical", category: "lineage_breakage", model: "a", file: "models/a.sql", title: "a: short critical" }), + finding({ + severity: "critical", + category: "lineage_breakage", + model: "b", + file: "models/b.sql", + title: "b: long critical", + body: "y".repeat(4_800), + }), + ...Array.from({ length: 10 }, (_, i) => + finding({ model: `s${i}`, file: `models/s${i}.sql`, title: `s${i}: short suggestion ${i}` }), + ), + ] + const md = renderSummary(buildEnvelope({ findings: fs, tier: "full", mode: "comment" })) + expect(md.length).toBeLessThanOrEqual(SUMMARY_BUDGET_CHARS) + expect(md).toContain("a: short critical") + expect(md).not.toContain("b: long critical") + expect(md).not.toContain("short suggestion") + expect(md).toContain("Critical (1 of 2)") + expect(md).not.toMatch(/### 💡 Suggestion/) + expect(md).toContain("11 more finding(s) not shown (1 critical, 10 suggestion)") + }) + + test("the metadata is budgeted too: a run with no findings and huge metadata stays within budget", () => { + const long = (tag: string, i: number) => `models/${"deeply/nested/".repeat(8)}${tag}_${i}.sql` + const env = buildEnvelope({ + findings: [], + tier: "full", + mode: "comment", + tierReasons: Array.from({ length: 40 }, (_, i) => `PII column in ${long("tier", i)}`), + scope: { + unverified: Array.from({ length: 30 }, (_, i) => ({ + path: long("unverified", i), + reason: `reason ${i % 3}: ${"no compiled SQL for the head ".repeat(10)}`, + })), + outOfScopeFiles: 4, + movedUnchangedFiles: 2, + } as any, + ai: { state: "error", reason: "z".repeat(2_000) } as any, + }) + const withOverride = { ...env, override: { by: "lead", reason: "because ".repeat(400), priorVerdict: "REQUEST_CHANGES" } } + for (const e of [env, withOverride as typeof env]) { + const md = renderSummary(e) + expect(md.length).toBeLessThanOrEqual(SUMMARY_BUDGET_CHARS) + expect(md).toContain("No issues found") + expect(md).toContain("more in verdict envelope)") + expect(md).toMatch(/\d+ model\(s\) not verified by the engine/) + // Local output keeps every reason. + expect(renderSummary(e, { maxChars: Infinity })).toContain(long("tier", 7)) + } + }) }) describe("portability noise", () => { From 18eb89dbb7aa5440cdb4f19bbaf4fcb0868f1407 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 16:05:11 +0530 Subject: [PATCH 16/81] test(review): cover deleted and patchless renamed files for inline anchors, and a run with nothing reviewable - `commentableLines` returns no line for a deleted file (`@@ -1,3 +0,0 @@`) or a missing patch; `postGitHubReview` drops the deleted file's comment and still attempts a pure rename that GitHub lists without a `patch`. - A PR that changes only non-dbt files approves with no findings and without the lint-only banner. Co-Authored-By: Claude Opus 5.5 --- .../test/altimate/review-noise.test.ts | 29 +++++++++++++++++++ .../opencode/test/altimate/review.test.ts | 22 ++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 882a71ba6e..66a8bf2b6d 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -70,6 +70,14 @@ describe("inline anchors", () => { expect([...commentableLines(d)].sort()).toEqual([1, 2]) }) + test("a deleted file has no commentable line; a pure rename without a patch has none either", () => { + const deleted = "diff --git a/models/old.sql b/models/old.sql\n--- a/models/old.sql\n+++ /dev/null\n@@ -1,3 +0,0 @@\n-select\n- id\n-from src\n" + expect(commentableLines(deleted).size).toBe(0) + expect(commentableLines("@@ -1,3 +0,0 @@\n-select\n- id\n-from src").size).toBe(0) + // GitHub lists a pure rename with no `patch` field. + expect(commentableLines(undefined).size).toBe(0) + }) + 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" }) @@ -562,6 +570,27 @@ describe("postGitHubReview", () => { expect(again.inlineSkippedAsPosted).toBe(1) }) + test("a deleted file gets no inline comment; a pure rename without a patch keeps its comments", async () => { + const env = buildEnvelope({ + findings: [ + finding({ file: "models/old.sql", model: "old", startLine: 2, title: "old: a" }), + finding({ file: "models/renamed.sql", model: "renamed", startLine: 5, title: "renamed: b" }), + ], + tier: "lite", + mode: "comment", + }) + const { octo, reviewCalls } = fakeOcto({ + files: [ + { filename: "models/old.sql", patch: "@@ -1,3 +0,0 @@\n-select\n- id\n-from src" }, + { filename: "models/renamed.sql" }, + ], + }) + await postGitHubReview(env, target, octo) + expect(reviewCalls[0].comments.map((c: { path: string; line: number }) => `${c.path}:${c.line}`)).toEqual([ + "models/renamed.sql:5", + ]) + }) + 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" })], diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 5667d08b33..d1bd48cc2a 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2995,6 +2995,28 @@ describe("orchestrate", () => { expect(env.summary.degraded).toBe(false) }) + test("a run with nothing reviewable approves without findings or the lint-only banner", async () => { + // Only non-dbt files changed: nothing reaches a lane, nothing resolves + // against a manifest, and that is not a lint-only run. + const env = await runReview({ + changedFiles: [ + { path: "README.md", status: "modified", diff: "+docs\n" }, + { path: ".github/workflows/ci.yml", status: "modified", diff: "+on: push\n" }, + ], + config: DEFAULT_REVIEW_CONFIG, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: fakeRunner({}), + getContent: content("select 1"), + }) + expect(env.findings).toEqual([]) + expect(env.verdict).toBe("APPROVE") + expect(env.summary.degraded).toBe(false) + const md = renderSummary(env) + expect(md).not.toContain("Lint-only run") + expect(md).toContain("No issues found") + }) + test("manifest availability errors degrade safely instead of aborting the review", async () => { const files: ChangedFile[] = [{ path: "models/staging/stg_x.sql", status: "modified", diff: "+select 1\n" }] const runner: ReviewRunner = { From f25ae0ac3eb39972207349aae37c9fe477d799e0 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 17:36:22 +0530 Subject: [PATCH 17/81] fix(review): resolve PII exposure by source table, qualifier, subquery and compiled base MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The base-exposure check compared bare column names, so several head changes that newly expose PII were treated as already exposed: - `rawColumnExposures` / `finalOutputs` now return `source.column` refs. A base `c.ssn` (customers) no longer hides a new `s.ssn as spouse_ssn` (spouses), nor `c.email` a new `e.email as rep_email` (employees). - Each FROM/JOIN source is recorded with its alias, and a qualified column resolves through that source only, so `m.home_address` (masked CTE) → `c.home_address` (table) and `k.ssn` (masked CTE) → `r.ssn` (raw CTE) are reported. Unqualified columns keep resolving through any CTE that outputs them; several tables give one combined ref. A qualifier that matches no source gets a ref that matches nothing, so it is reported. - FROM subqueries are sources under their alias and resolve like CTEs. - A non-raw head expression under a name the base masked is base-exposed only when it is computed the same way (same item text, same CTE/subquery text): `md5(x) as x` → `lower(x) as x` is reported. - Base outputs come from the engine's base SQL (compiled, or raw only when it has no Jinja), never the union of raw and compiled, so a `{% if %}` branch the target never renders no longer credits the base with raw `ssn`. - The regex twins check the head's resolved source for the column too. - Head outputs are parsed once per file, and `byScope` is built with push. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 96 +++++--- .../src/altimate/review/rule-catalog.ts | 229 ++++++++++++++---- .../test/altimate/review-rule-catalog.test.ts | 44 +++- .../opencode/test/altimate/review.test.ts | 133 ++++++++++ 4 files changed, 410 insertions(+), 92 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index c593a544e5..54930160fa 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -14,7 +14,14 @@ 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 SelectItem, type SelectItemColumn, finalOutputs, normalizeSelectLine, selectItems } from "./rule-catalog" +import { + type FinalOutputs, + type SelectItem, + type SelectItemColumn, + finalOutputs, + normalizeSelectLine, + selectItems, +} from "./rule-catalog" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult, safeReason } from "./ai-review" /** @@ -1215,49 +1222,66 @@ export async function runReview(input: OrchestrateInput): Promise>() - // Per file, the base model's final output (raw and compiled base SQL, each - // parsed on its own): every output name, and the source columns each exposes RAW. - const baseOutputsByFile = new Map>() - const baseOutputs = (file: string) => { - let outputs = baseOutputsByFile.get(file) - if (!outputs) { + // Per file, the final output of the base and head models, parsed from the SQL + // the engine reads (compiled, or raw only when it holds no Jinja): a raw Jinja + // base would credit it with every `{% if %}` branch, including ones the target + // never renders. No engine SQL → nothing is known exposed. + const outputsByFile = new Map() + const outputs = (file: string, side: "old" | "new") => { + const key = `${side}\u0000${file}` + let parsed = outputsByFile.get(key) + if (!parsed) { const ctx = ctxByPath.get(file) - outputs = { raw: new Map(), names: new Set() } - for (const sql of new Set([ctx?.oldSql, ctx?.engineOldSql].filter((x): x is string => !!x))) { - const parsed = finalOutputs(sql) - for (const n of parsed.names) outputs.names.add(n) - for (const [n, cols] of parsed.raw) outputs.raw.set(n, new Set([...(outputs.raw.get(n) ?? []), ...cols])) - } - baseOutputsByFile.set(file, outputs) + parsed = finalOutputs((side === "old" ? ctx?.engineOldSql : ctx?.engineNewSql) ?? "") + outputsByFile.set(key, parsed) } - return outputs + return parsed + } + // `source.column` refs the base exposed raw under a name its PII detection reported. + const baseRawPii = (file: string) => { + const basePii = basePiiColumnsByFile.get(file) + const refs = new Set() + if (!basePii) return refs + const raw = outputs(file, "old").raw + for (const name of basePii) for (const ref of raw.get(name) ?? []) refs.add(ref) + return refs } - // `detectPii` reports OUTPUT names (`c.ssn as tax_ref` → `tax_ref`): a SOURCE - // column is already exposed only when a base PII output exposes that same column - // RAW in the base's final projection, under its own name or an alias (`c.ssn as - // tax_ref` → `c.ssn as tax_id` re-exposes nothing new). An alias alone is not + // A regex twin's SOURCE column (`ssn`, with its output alias when it has one) is + // already exposed only when the head reads it raw from sources that a base PII + // output also exposed raw: same table and column (`c.ssn` → `cust.ssn` on + // `customers` is not new; `s.ssn` from `spouses` is). An alias alone is not // proof (`c.email as contact` → `c.ssn as contact` newly exposes `ssn`), and // neither is a base output that only masks the column (`sha2(c.ssn) as ssn_hash`) - // or a CTE's own alias that never reaches the final select. - const isBaseExposed = (file: string, column: string) => { - const basePii = basePiiColumnsByFile.get(file) - if (!basePii) return false - const exposures = baseOutputs(file).raw - return [...basePii].some((name) => !!exposures.get(name)?.has(column)) + // or a CTE's own alias that never reaches the final select. A column the head's + // final output doesn't expose raw under that name is reported. + const isBaseExposed = (file: string, column: string, alias?: string) => { + const refs = [...(outputs(file, "new").raw.get(alias ?? column) ?? [])].filter((r) => r.endsWith(`.${column}`)) + if (!refs.length) return false + const exposed = baseRawPii(file) + return refs.every((r) => exposed.has(r)) } // A head PII output name the base already exposed. When the head selects a - // column raw under it, that same source column must be raw in the base's final - // output (base `md5(home_address) as home_address` → head `home_address` is new). - // A head output that is not a raw column exposes no new raw value when the base - // had the name. A name the head's final select doesn't resolve (`select *` from a - // table) counts as base-exposed only when the base had it and did not mask it. + // column raw under it, the base must expose that same source column raw (base + // `md5(home_address) as home_address` → head `home_address` is new). A head + // output that is not a raw column is base-exposed when the base exposed that + // name raw, or computes it the same way (same item text, same CTEs/subqueries + // read): `md5(x) as x` → `lower(x) as x` unmasks. A name the head's final select doesn't resolve + // (`select *` from a table) counts as base-exposed only when the base had it and + // did not mask it. const isBaseExposedOutput = (file: string, name: string, basePii: Set) => { - const head = finalOutputs(ctxByPath.get(file)?.engineNewSql ?? "") + const head = outputs(file, "new") const rawColumns = head.raw.get(name) - if (rawColumns?.size) return [...rawColumns].every((col) => isBaseExposed(file, col)) + if (rawColumns?.size) { + const exposed = baseRawPii(file) + return [...rawColumns].every((ref) => exposed.has(ref)) + } if (!basePii.has(name)) return false - if (head.names.has(name)) return true - const base = baseOutputs(file) + const base = outputs(file, "old") + if (head.names.has(name)) { + if (base.raw.has(name)) return true + const baseSigs = base.signatures.get(name) + return !!baseSigs && [...(head.signatures.get(name) ?? [])].every((sig) => baseSigs.has(sig)) + } return !base.names.has(name) || base.raw.has(name) } for (const ctx of ctxByPath.values()) { @@ -1507,12 +1531,12 @@ export async function runReview(input: OrchestrateInput): Promise isReindented(f.file, i.line) || isBaseExposed(f.file, i.column))) return false + if (items.length && items.every((i) => isReindented(f.file, i.line) || isBaseExposed(f.file, i.column, i.alias))) 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 56da06e00d..21a43911ca 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -182,8 +182,9 @@ export function selectItemColumns(line: string, tokenRe: RegExp): SelectItemColu // One identifier segment: bare, double-quoted or backtick-quoted. const SEGMENT = String.raw`(?:[A-Za-z_][\w$]*|"[^"]+"|` + "`[^`]+`)" -// A column reference, optionally table-qualified (`c.ssn`, `"c"."ssn"`); group 1 is the column. -const COLUMN_REF = String.raw`(?:${SEGMENT}\s*\.\s*)*(${SEGMENT})` +// A column reference, optionally table-qualified (`c.ssn`, `"c"."ssn"`); group 1 is +// the qualifier's last segment (the table or its alias), group 2 the column. +const COLUMN_REF = String.raw`(?:(?:${SEGMENT}\s*\.\s*)*(${SEGMENT})\s*\.\s*)?(${SEGMENT})` // Select-item expressions that expose a column RAW: a bare reference, or one only // cast to a type (`cast(c.ssn as varchar)`, `c.ssn::varchar(20)`). const RAW_COLUMN_EXPRS = [ @@ -212,6 +213,8 @@ export interface SelectItem { name?: string /** The column the item exposes RAW (bare or qualified reference, or only cast). */ rawColumn?: string + /** The qualifier of `rawColumn` (`c` in `c.ssn`): a FROM/JOIN alias or table name. */ + rawQualifier?: string /** Whitespace-normalised item text, for comparing one item across base and head. */ text: string /** `final` for the outermost query, the CTE name for a CTE body, `>sub` for a nested query. */ @@ -241,7 +244,7 @@ function maskSql(sql: string): string { const isWordChar = (c: string | undefined) => !!c && /[\w$."`]/.test(c) -function describeItem(raw: string): Pick { +function describeItem(raw: string): Pick { const text = raw .replace(/\s+/g, " ") .replace(/\(\s+/g, "(") @@ -254,19 +257,43 @@ function describeItem(raw: string): Pick re.exec(expr)?.[1]).find(Boolean) - const rawColumn = column ? unquote(column) : undefined - return { name: alias ? unquote(alias) : rawColumn, rawColumn, text } + const ref = RAW_COLUMN_EXPRS.map((re) => re.exec(expr)).find(Boolean) + const rawColumn = ref ? unquote(ref[2]) : undefined + const rawQualifier = ref?.[1] ? unquote(ref[1]) : undefined + return { name: alias ? unquote(alias) : rawColumn, rawColumn, rawQualifier, text } } // Words that end a FROM clause's table list at its own nesting level. const FROM_LIST_END = /^(where|group|order|limit|qualify|having|union|intersect|except|minus|window|fetch|offset|on|using)\b/i const SET_OPERATOR = /^(union|intersect|except|minus)\b/i +// Words after a FROM/JOIN source that are not its alias. +const NOT_A_SOURCE_ALIAS = new Set( + "on using where join left right inner outer full cross natural group order limit qualify having union intersect except minus window fetch offset lateral pivot unpivot tablesample sample for at before changes match_recognize with".split( + " ", + ), +) + +/** One FROM/JOIN source of a select: a table (last name segment), a CTE, or a + * FROM subquery (named by its scope), with the alias it is read under. */ +interface Source { + name: string + alias?: string +} interface ParsedSelects { items: SelectItem[] - /** Per `scope#branch`, the table or CTE names its FROM / JOIN clauses read. */ - sources: Map + /** Per `scope#branch`, the sources its FROM / JOIN clauses read. */ + sources: Map +} + +/** Offset of the `)` closing the `(` at `open` in masked SQL, or the end. */ +function closingParen(s: string, open: number): number { + let depth = 0 + for (let i = open; i < s.length; i++) { + if (s[i] === "(") depth++ + else if (s[i] === ")" && --depth === 0) return i + } + return s.length } function parseSelects(sql: string): ParsedSelects { @@ -284,7 +311,11 @@ function parseSelects(sql: string): ParsedSelects { return lo + 1 } const items: SelectItem[] = [] - const sources = new Map() + const sources = new Map() + // The scope each nested query's `(` opens, so a FROM subquery is a named source. + const parenScope = new Map() + // Each select's scope, branch and the offset its select list ends at. + const selects: Array<{ scope: string; branch: number; end: number }> = [] const scopes: string[] = ["final"] const branches = new Map() const cteHead = new RegExp(String.raw`(${SEGMENT})\s+as\s*(?:(?:not\s+)?materialized\s*)?$`, "i") @@ -298,8 +329,10 @@ function parseSelects(sql: string): ParsedSelects { // A CTE body is named by its CTE; a nested query gets its own scope; any // other parenthesis (a call, a grouping) stays in its parent's scope. if (cte && !/^as$/i.test(cte[1])) scopes.push(unquote(cte[1])) - else if (/^[\s(]*select\b/i.test(s.slice(i + 1, i + 200))) scopes.push(`${parent}>sub${++nested}`) - else scopes.push(parent) + else if (/^[\s(]*select\b/i.test(s.slice(i + 1, i + 200))) { + scopes.push(`${parent}>sub${++nested}`) + parenScope.set(i, scopes[scopes.length - 1]) + } else scopes.push(parent) continue } if (c === ")") { @@ -344,11 +377,16 @@ function parseSelects(sql: string): ParsedSelects { break } } - // Tables read at this select's own level: the name after `from`, `join`, or a - // `,` inside a FROM list, up to the end of the select (`)`, `;`, a set operator). - const read: string[] = [] + selects.push({ scope, branch, end }) + } + // Sources read at each select's own level: the table, CTE or subquery after + // `from`, `join`, or a `,` inside a FROM list, with its alias, up to the end of + // the select (`)`, `;`, a set operator). + const aliasRe = new RegExp(String.raw`^\s+(?:as\s+)?(${SEGMENT})`, "i") + for (const { scope, branch, end } of selects) { + const read: Source[] = [] let inFrom = false - depth = 0 + let depth = 0 for (let j = end; j < s.length; j++) { const d = s[j] if (depth === 0 && (d === ")" || d === ";")) break @@ -360,8 +398,28 @@ function parseSelects(sql: string): ParsedSelects { const kw = boundary ? /^(from|join)\b/i.exec(s.slice(j, j + 5)) : null if (kw || (inFrom && d === ",")) { const after = j + (kw ? kw[0].length : 1) - const ref = tableRef.exec(s.slice(after, after + 300)) - if (ref) read.push(unquote(ref[1].split(".").pop()!.trim())) + const lead = after + (/^\s*/.exec(s.slice(after))?.[0].length ?? 0) + let name: string | undefined + let rest = lead + if (s[lead] === "(") { + // A FROM subquery is a source under its alias; any other parenthesis + // (a parenthesised join) names no source here. + name = parenScope.get(lead) + rest = closingParen(s, lead) + 1 + } else { + const ref = tableRef.exec(s.slice(after, after + 300)) + if (ref) { + const last = ref[1].split(".").pop()!.trim() + const at = after + ref[0].length - last.length + // A Jinja `{{ ref('x') }}` is masked to underscores: name it by its source text. + name = /^_+$/.test(last) ? sql.slice(at, at + last.length).replace(/\s+/g, "").toLowerCase() : unquote(last) + rest = after + ref[0].length + } + } + if (name) { + const alias = aliasRe.exec(s.slice(rest, rest + 200))?.[1] + read.push(alias && !NOT_A_SOURCE_ALIAS.has(unquote(alias)) ? { name, alias: unquote(alias) } : { name }) + } inFrom = true j = after - 1 } else if (boundary && FROM_LIST_END.test(s.slice(j, j + 10))) inFrom = false @@ -383,67 +441,142 @@ export function selectItems(sql: string): SelectItem[] { const STAR = new RegExp(String.raw`^(?:${SEGMENT}\.)*\*$`) +/** The model's final output, as `finalOutputs` resolves it. */ +export interface FinalOutputs { + /** Per output name, the `source.column` refs it exposes RAW (see `rawColumnExposures`). */ + raw: Map> + /** Every output name the final projection resolves. */ + names: Set + /** Per output name, a signature of how it is computed: the item text 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> +} + +interface ScopeOutputs extends FinalOutputs { + /** `*` items, whose columns pass through unnamed (`select * from customers`). */ + stars: Array<{ branch: number; qualifier?: string }> + /** Every item's text, and that of every scope it reads. */ + body: string +} + /** * Per output name of the model (its FINAL projection, never a CTE's or a * nested query's own aliases), the source columns it exposes RAW under that - * name (`c.ssn as tax_ref` → `tax_ref: {ssn}`, bare `ssn` → `ssn: {ssn}`). - * A final item that reads a CTE takes the CTE's exposure for that column - * (`select contact from b` with `b` = `select email as contact` → `contact: - * {email}`), and `*` over CTEs takes all of theirs. A later set-operation - * branch takes the first branch's name at the same position. An item that - * wraps the column in any other function or expression (`sha2(c.ssn)`, - * `left(c.ssn, 4)`, `case …`, `a || b`) exposes nothing raw and is left out. + * name, each as `source.column` where the source is the table (last name + * segment) the column is read from: `c.ssn as tax_ref` with `customers c` → + * `tax_ref: {customers.ssn}`, so the same column name from another table + * (`s.ssn` with `spouses s`) is a different exposure. A qualifier resolves + * through its own FROM/JOIN source only; a column read from a CTE or a FROM + * subquery takes that scope's exposure for it (masked there → nothing raw), and + * `*` over them takes all of theirs. An unqualified column resolves through the + * CTEs/subqueries that output it, else the single table read (several tables → + * one combined `a|b.column` ref). A qualifier that matches no source gets a ref + * that matches nothing on the other side. A later set-operation branch takes the + * first branch's name at the same position. An item that wraps the column in any + * other function or expression (`sha2(c.ssn)`, `left(c.ssn, 4)`, `case …`, + * `a || b`) exposes nothing raw and is left out. */ export function rawColumnExposures(sql: string): Map> { return finalOutputs(sql).raw } -/** The model's final output: every name it resolves (`names`) and, per name, the - * source columns exposed raw under it (`raw`, as `rawColumnExposures`). */ -export function finalOutputs(sql: string): { raw: Map>; names: Set } { +let unresolvedRefs = 0 + +/** The model's final output: every name it resolves, the source columns each + * exposes raw (as `rawColumnExposures`), and how each is computed. */ +export function finalOutputs(sql: string): FinalOutputs { const { items, sources } = parseSelects(sql) const byScope = new Map() - for (const item of items) byScope.set(item.scope, [...(byScope.get(item.scope) ?? []), item]) - const memo = new Map>; names: Set }>() - const resolve = (scope: string, seen: Set) => { + for (const item of items) { + const list = byScope.get(item.scope) + if (list) list.push(item) + else byScope.set(item.scope, [item]) + } + // A ref no source explains: unique, so it is never "already exposed". + const unresolved = (col: string) => new Set([`?${++unresolvedRefs}.${col}`]) + const union = (sets: Iterable>) => { + const out = new Set() + for (const set of sets) for (const x of set) out.add(x) + return out + } + const memo = new Map() + const isDerived = (src: Source, scope: string, seen: Set) => + src.name !== scope && byScope.has(src.name) && !seen.has(src.name) + // The `source.column` refs a column read in `scope#branch` resolves to. + const resolveRef = (scope: string, branch: number, qualifier: string | undefined, col: string, seen: Set) => { + const srcs = sources.get(`${scope}#${branch}`) ?? [] + const inner = new Set([...seen, scope]) + const fromSource = (src: Source): Set => { + if (!isDerived(src, scope, seen)) return byScope.has(src.name) ? unresolved(col) : new Set([`${src.name}.${col}`]) + const out = resolve(src.name, inner) + if (out.names.has(col)) return out.raw.get(col) ?? new Set() + if (out.stars.length) return union(out.stars.map((st) => resolveRef(src.name, st.branch, st.qualifier, col, inner))) + return unresolved(col) + } + if (qualifier) { + const src = + srcs.find((x) => x.alias === qualifier) ?? + srcs.find((x) => !x.alias && x.name === qualifier) ?? + srcs.find((x) => x.name === qualifier) + return src ? fromSource(src) : unresolved(col) + } + const named = srcs.filter((x) => isDerived(x, scope, seen) && resolve(x.name, inner).names.has(col)) + if (named.length) return union(named.map(fromSource)) + const open = srcs.filter((x) => + isDerived(x, scope, seen) ? resolve(x.name, inner).stars.length > 0 : !byScope.has(x.name), + ) + if (open.length === 1) return fromSource(open[0]) + if (open.length > 1) return new Set([`${[...new Set(open.map((x) => x.name))].sort().join("|")}.${col}`]) + return unresolved(col) + } + const resolve = (scope: string, seen: Set): ScopeOutputs => { const cached = memo.get(scope) if (cached) return cached + const inner = new Set([...seen, scope]) const raw = new Map>() const names = new Set() - const add = (name: string, cols: Iterable) => { - const set = raw.get(name) ?? new Set() - for (const col of cols) set.add(col) - raw.set(name, set) + const signatures = new Map>() + const stars: ScopeOutputs["stars"] = [] + const addTo = (map: Map>, name: string, values: Iterable) => { + const set = map.get(name) ?? new Set() + for (const v of values) set.add(v) + map.set(name, set) } const scopeItems = byScope.get(scope) ?? [] const firstNames = new Map(scopeItems.filter((i) => i.branch === 0).map((i) => [i.position, i.name])) + const readBodies = new Set() for (const item of scopeItems) { - const ctes = (sources.get(`${scope}#${item.branch}`) ?? []) - .filter((src) => src !== scope && byScope.has(src) && !seen.has(src)) - .map((src) => resolve(src, new Set([...seen, scope]))) + 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)) { - for (const cte of ctes) { - for (const n of cte.names) names.add(n) - for (const [n, cols] of cte.raw) add(n, cols) + const qualifier = /([^.]+)\.\*$/.exec(item.text)?.[1] + const q = qualifier ? unquote(qualifier) : undefined + stars.push({ branch: item.branch, qualifier: q }) + for (const src of derived) { + if (q && src.alias !== q && src.name !== q) continue + 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}`)) } continue } const name = item.branch === 0 ? item.name : firstNames.get(item.position) if (!name) continue names.add(name) - if (!item.rawColumn) continue - // A column a source CTE outputs resolves through that CTE (masked there → - // nothing raw); one no CTE outputs comes straight from a table. - const via = ctes.filter((cte) => cte.names.has(item.rawColumn!)) - if (via.length) add(name, via.flatMap((cte) => [...(cte.raw.get(item.rawColumn!) ?? [])])) - else add(name, [item.rawColumn]) + addTo(signatures, name, [`${item.text.toLowerCase()}\u0001${bodies.join("\u0002")}`]) + if (item.rawColumn) addTo(raw, name, resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen)) } for (const [n, cols] of raw) if (!cols.size) raw.delete(n) - const result = { raw, names } + const body = [scopeItems.map((i) => i.text.toLowerCase()).join(","), ...[...readBodies].sort()].join("\u0003") + const result = { raw, names, signatures, stars, body } memo.set(scope, result) return result } - return resolve("final", new Set()) + const { raw, names, signatures } = resolve("final", new Set()) + return { raw, names, signatures } } /** A diff line with comments and whitespace normalised (and a leading/trailing diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index c4634d00f0..8233a2bb81 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -47,7 +47,7 @@ describe("rawColumnExposures", () => { const asObject = (m: Map>) => Object.fromEntries([...m].map(([k, v]) => [k, [...v].sort()])) test("reads the final projection only, not a CTE's own aliases", () => { const sql = "with h as (\n select ssn as contact\n from customers\n)\nselect c.email as contact from customers c" - expect(asObject(rawColumnExposures(sql))).toEqual({ contact: ["email"] }) + expect(asObject(rawColumnExposures(sql))).toEqual({ contact: ["customers.email"] }) }) test("resolves a final column through the CTE it reads, and `*` over a CTE", () => { const sql = [ @@ -55,28 +55,56 @@ describe("rawColumnExposures", () => { "final as (select id, sha2(phone) as phone, ssn, email as contact from src)", "select * from final", ].join("\n") - expect(asObject(rawColumnExposures(sql))).toEqual({ id: ["id"], ssn: ["ssn"], contact: ["email"] }) + expect(asObject(rawColumnExposures(sql))).toEqual({ + id: ["{{ref('customers')}}.id"], + ssn: ["{{ref('customers')}}.ssn"], + contact: ["{{ref('customers')}}.email"], + }) expect(asObject(rawColumnExposures("with b as (select email as contact from c) select contact from b"))).toEqual({ - contact: ["email"], + contact: ["c.email"], }) }) test("parses a select item whose alias is on another line", () => { const sql = "select c.customer_id,\n c.ssn\n as tax_ref\nfrom customers c" - expect(asObject(rawColumnExposures(sql))).toEqual({ customer_id: ["customer_id"], tax_ref: ["ssn"] }) + expect(asObject(rawColumnExposures(sql))).toEqual({ customer_id: ["customers.customer_id"], tax_ref: ["customers.ssn"] }) }) test("accepts quoted identifiers", () => { - expect(asObject(rawColumnExposures('select "c"."ssn" as "tax_ref" from customers "c"'))).toEqual({ tax_ref: ["ssn"] }) + expect(asObject(rawColumnExposures('select "c"."ssn" as "tax_ref" from customers "c"'))).toEqual({ tax_ref: ["customers.ssn"] }) }) test("accepts an alias without AS, and not a trailing keyword", () => { const sql = "select c.ssn tax_ref, cast(c.dob as date) dob_day, case when x then y end, sha2(c.email) em from c" - expect(asObject(rawColumnExposures(sql))).toEqual({ tax_ref: ["ssn"], dob_day: ["dob"] }) + expect(asObject(rawColumnExposures(sql))).toEqual({ tax_ref: ["c.ssn"], dob_day: ["c.dob"] }) }) test("names a later set-operation branch by the first branch's position", () => { const sql = "select id, ssn as tax_ref from a\nunion all\nselect id, email from b" - expect(asObject(rawColumnExposures(sql))).toEqual({ id: ["id"], tax_ref: ["email", "ssn"] }) + expect(asObject(rawColumnExposures(sql))).toEqual({ id: ["a.id", "b.id"], tax_ref: ["a.ssn", "b.email"] }) + }) + test("keeps the source table, so a same-named column from another table is distinct", () => { + const sql = "select c.ssn, s.ssn as spouse_ssn, schema1.employees.email from customers c, schema1.employees join spouses as s on true" + expect(asObject(rawColumnExposures(sql))).toEqual({ + ssn: ["customers.ssn"], + spouse_ssn: ["spouses.ssn"], + email: ["employees.email"], + }) + }) + test("resolves a qualifier through its own source only", () => { + const sql = [ + "with r as (select customer_id, ssn from customers),", + "k as (select customer_id, sha2(ssn) as ssn from customers)", + "select r.ssn as a, k.ssn as b, c.ssn as d from r join k on true join customers c on true", + ].join("\n") + expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["customers.ssn"], d: ["customers.ssn"] }) + // An unknown qualifier never matches anything: it resolves to a unique ref. + expect([...(rawColumnExposures("select x.ssn from customers c").get("ssn") ?? [])][0]).toMatch(/^\?\d+\.ssn$/) + }) + test("resolves through a FROM subquery under its alias", () => { + expect(asObject(rawColumnExposures("select s.ssn, s.email from (select sha2(ssn) as ssn, email from customers) s"))).toEqual({ + email: ["customers.email"], + }) + expect(asObject(rawColumnExposures("select ssn from (select * from customers) as s"))).toEqual({ ssn: ["customers.ssn"] }) }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" - expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["ssn"], c: ["email"] }) + expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) }) }) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index d1bd48cc2a..4ac7e93134 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2402,6 +2402,139 @@ describe("orchestrate", () => { expect(reindented.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) }) + // Runs one model through every PII path (the broad fallback, the default + // tier, the regex twins) and returns, per reviewers setting, the PII findings. + const piiRuns = async ( + head: string, + base: string, + diff: string, + cols: string[], + compiled?: { head: string; base: string }, + ) => { + const out: Array<{ reviewers: string[]; env: Awaited> }> = [] + for (const reviewers of [["pii_exposure"], [], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(cols), + getContent: content(head, base), + ...(compiled ? { getCompiled: async (_f: string, side: "old" | "new") => (side === "new" ? compiled.head : compiled.base) } : {}), + }) + out.push({ reviewers, env }) + } + return out + } + // Every run reports the PII: critical with REQUEST_CHANGES where the broad lane + // runs. The regex twins alone (`dbt_patterns`) rate `email` a warning by design, + // and match only a line that starts with an item from their fixed column list. + const expectReportedPii = ( + runs: Awaited>, + broadColumns: string[], + twins: "critical" | "warning" | "none" = "critical", + ) => { + for (const { reviewers, env } of runs) { + if (reviewers[0] === "dbt_patterns" && twins === "none") continue + const pii = env.findings.filter((f) => f.category === "pii_exposure") + expect({ reviewers, reported: pii.length > 0 }).toEqual({ reviewers, reported: true }) + if (reviewers[0] === "dbt_patterns" && twins === "warning") continue + expect({ reviewers, critical: pii.some((f) => f.severity === "critical") }).toEqual({ reviewers, critical: true }) + expect({ reviewers, verdict: env.verdict }).toEqual({ reviewers, verdict: "REQUEST_CHANGES" }) + if (reviewers[0] === "pii_exposure") { + const broad = env.findings.filter((f) => f.evidence?.tool === "schema.detect_pii") + expect(broad.map((f) => (f.evidence?.result as any)?.columns)).toEqual([broadColumns]) + } + } + } + + test("a same-named PII column from a different source is new exposure", async () => { + // Base exposes `c.ssn` (customers); head adds `s.ssn as spouse_ssn` (spouses). + const base = "select c.customer_id,\n c.ssn\nfrom customers c\njoin spouses s on s.customer_id = c.customer_id" + const head = base.replace(" c.ssn\n", " c.ssn,\n s.ssn as spouse_ssn\n") + expectReportedPii(await piiRuns(head, base, "- c.ssn\n+ c.ssn,\n+ s.ssn as spouse_ssn\n", ["ssn"]), ["spouse_ssn"]) + const baseE = "select c.customer_id,\n c.email\nfrom customers c\njoin employees e on e.id = c.rep_id" + const headE = baseE.replace(" c.email\n", " c.email,\n e.email as rep_email\n") + expectReportedPii( + await piiRuns(headE, baseE, "- c.email\n+ c.email,\n+ e.email as rep_email\n", ["email"]), + ["rep_email"], + "warning", + ) + // Control: the same source under a new table alias is not new exposure. + const renamed = base.replace(/\bc\./g, "cust.").replace("customers c", "customers cust") + for (const { env } of await piiRuns(renamed, base, "- c.ssn\n+ cust.ssn\n", ["ssn"])) + expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + }) + + test("a head expression that unmasks a name the base masked is reported", async () => { + for (const [from, to, col] of [ + ["md5(home_address) as home_address", "lower(home_address) as home_address", "home_address"], + ["sha2(ssn) as ssn", "lower(ssn) as ssn", "ssn"], + ]) { + const base = `select customer_id,\n ${from}\nfrom customers` + const runs = await piiRuns(base.replace(from, to), base, `- ${from}\n+ ${to}\n`, [col]) + const broad = runs[0].env.findings.filter((f) => f.evidence?.tool === "schema.detect_pii") + expect(broad.map((f) => (f.evidence?.result as any)?.columns)).toEqual([[col]]) + expect(broad[0].severity).toBe("critical") + // Control: the same masked item, untouched, next to an unrelated change. + const touched = base.replace("customer_id,", "customer_id, region,") + const quiet = await piiRuns(touched, base, "-select customer_id,\n+select customer_id, region,\n", [col]) + expect(quiet[0].env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + } + }) + + test("a qualified reference resolves through its own source, not any CTE with that column", async () => { + // Base reads `home_address` masked from CTE `m`; head reads it raw from `customers c`. + const base = [ + "with m as (select customer_id, md5(home_address) as home_address from customers)", + "select m.customer_id, m.home_address", + "from m join customers c on c.customer_id = m.customer_id", + ].join("\n") + const head = base.replace("m.home_address", "c.home_address") + const runs = await piiRuns(head, base, "-select m.customer_id, m.home_address\n+select m.customer_id, c.home_address\n", [ + "home_address", + ]) + expectReportedPii(runs, ["home_address"], "none") + // Reverse: two CTEs output `ssn`, one raw and one masked; head switches to the raw one. + const base2 = [ + "with r as (select customer_id, ssn from customers),", + "k as (select customer_id, sha2(ssn) as ssn from customers)", + "select r.customer_id, k.ssn", + "from r join k on k.customer_id = r.customer_id", + ].join("\n") + const head2 = base2.replace("k.ssn\n", "r.ssn\n") + const runs2 = await piiRuns(head2, base2, "-select r.customer_id, k.ssn\n+select r.customer_id, r.ssn\n", ["ssn"]) + expectReportedPii(runs2, ["ssn"], "none") + }) + + test("a FROM subquery is a source: a column it masked is not credited as raw", async () => { + const base = "select s.customer_id, s.ssn\nfrom (select customer_id, sha2(ssn) as ssn from customers) s" + const head = "select customer_id, ssn\nfrom customers" + const runs = await piiRuns(head, base, `-${base.split("\n")[0]}\n+${head.split("\n")[0]}\n`, ["ssn"]) + expectReportedPii(runs, ["ssn"], "none") + // Control: the subquery exposed it raw, so reading the table directly is not new. + const rawBase = base.replace("sha2(ssn) as ssn", "ssn") + const quiet = await piiRuns(head, rawBase, `-${rawBase.split("\n")[0]}\n+${head.split("\n")[0]}\n`, ["ssn"]) + expect(quiet[0].env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + }) + + test("base exposure comes from the compiled base, not a Jinja branch the target never renders", async () => { + const rawBase = [ + "select customer_id,", + "{% if target.name == 'dev' %} ssn,", + "{% else %} sha2(ssn) as ssn,", + "{% endif %} region", + "from customers", + ].join("\n") + const compiledBase = "select customer_id,\n sha2(ssn) as ssn,\n region\nfrom customers" + const head = "select customer_id,\n ssn,\n region\nfrom customers" + const runs = await piiRuns(head, rawBase, "-{% if target.name == 'dev' %} ssn,\n+ ssn,\n", ["ssn"], { + head, + base: compiledBase, + }) + expectReportedPii(runs, ["ssn"]) + }) + test("a PII line moved from a CTE into the final select is not a reindent", async () => { // ` email,` leaves the CTE and the same text lands in the final select: the // model's output now carries `email`, though the line matches a removed one. From 55f1f9115642f3b6b65e3d392e9213fcb22f4eb6 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 17:36:44 +0530 Subject: [PATCH 18/81] fix(review): stop flagging the ANSI `interval '30' day` as a string interval literal The `interval-string-literal` regex accepted `'\d+\s*\w+'`, which matches `'30'` (`3` + `0`), so the ANSI `interval '30' day` / `interval '12' month` was flagged on Trino, Athena, BigQuery, Oracle and MySQL, where it is the correct form. It now needs whitespace and a unit inside the quotes (`'1 day'`). The rule's counter-example is `d - interval '30' day`, and the noise test checks the ANSI form on those engines. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/rule-catalog.ts | 5 +++-- packages/opencode/test/altimate/review-noise.test.ts | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 21a43911ca..40be0c9286 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -2250,13 +2250,14 @@ const STYLE: Rule[] = [ "string interval literal portability", "`interval '1 day'` literal syntax differs across warehouses; prefer dateadd/date_add functions.", { - added: /interval\s+'\d+\s*\w+'/i, + // The unit inside the quotes (`'1 day'`), not the ANSI `interval '30' day`. + added: /interval\s+'\d+\s+[a-z]+'/i, // BigQuery, MySQL, T-SQL, Oracle, Trino and Athena need `INTERVAL 1 DAY` / // `INTERVAL '1' DAY` (or have no interval literal). portability: { worksOn: ["postgres", "redshift", "snowflake", "duckdb", "databricks"] }, }, { add: "d + interval '1 day'" }, - { add: "dateadd(day, 1, d)" }, + { add: "d - interval '30' day" }, ), r( "date-plus-int", diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 66a8bf2b6d..9a16fd690b 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -430,6 +430,10 @@ describe("portability noise", () => { const interval = "select d + interval '1 day' as next_day from t" expect(await rules(interval, "bigquery")).toContain("interval-string-literal") expect(await rules(interval, "postgres")).not.toContain("interval-string-literal") + // The ANSI form (`interval '30' day`) is what those engines want: never flagged. + for (const ansi of ["select d - interval '30' day as d30 from t", "select d + interval '12' month as d12 from t"]) + for (const dialect of ["trino", "athena", "bigquery", "oracle", "mysql"]) + expect(await rules(ansi, dialect)).not.toContain("interval-string-literal") }) }) From 075fcee093e1afcf5322017cf14530c8408dcb8e Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 17:37:29 +0530 Subject: [PATCH 19/81] fix(review): clip summary bullet bodies so a long finding cannot hide every title MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bullet bodies were not clipped, so one critical with a ~4.8k-char body used up the summary budget and the gate comment said "Changes requested — 1 critical" while listing nothing. Budgeted output now clips each bullet body to 600 chars (at a word boundary); local output (`maxChars: Infinity`) keeps whole bodies. The stop-at-first-misfit test now uses twelve long criticals, since a single 4.8k-char body fits once clipped; a new test covers the lone huge critical. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 10 +++- .../test/altimate/review-noise.test.ts | 55 ++++++++++++++----- 2 files changed, 50 insertions(+), 15 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index d7afa32651..e5c695dd77 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -209,7 +209,13 @@ function groupKeyTitle(f: Finding): string { /** 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. */ +// A budgeted bullet's body is clipped to this, so one long finding cannot fill +// the comment and hide the titles of the most severe findings. +const BULLET_BODY_MAX = 600 + function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; count: number }> { + // Budgeted (grouped) output clips bodies; local output keeps them whole. + const bodyOf = (text: string) => (group ? clip(text, BULLET_BODY_MAX) : text) const groups = new Map() for (const f of items) { // The body is part of the key: one rule with different messages (e.g. a @@ -229,7 +235,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou 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 body = bodyOf(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: @@ -242,7 +248,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou for (const f of g) { const loc = f.file + (f.startLine ? `:${f.startLine}` : "") out.push({ - text: `- **${f.title}** \n ${oneLine(f.body)} \n \`${loc}\`${f.degraded ? " · _unverified_" : ""} · ${f.category}`, + text: `- **${f.title}** \n ${bodyOf(oneLine(f.body))} \n \`${loc}\`${f.degraded ? " · _unverified_" : ""} · ${f.category}`, count: 1, }) } diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 9a16fd690b..06fff8e927 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -264,28 +264,57 @@ describe("summary grouping and budget", () => { }) test("a critical that does not fit stops the listing: no later, shorter finding jumps ahead of it", () => { + // Twelve criticals with long bodies (each clipped, still ~700 chars) cannot + // all fit; the short suggestions after them must not be listed instead. const fs: Finding[] = [ - finding({ severity: "critical", category: "lineage_breakage", model: "a", file: "models/a.sql", title: "a: short critical" }), - finding({ - severity: "critical", - category: "lineage_breakage", - model: "b", - file: "models/b.sql", - title: "b: long critical", - body: "y".repeat(4_800), - }), + ...Array.from({ length: 12 }, (_, i) => + finding({ + severity: "critical", + category: "lineage_breakage", + model: `c${i}`, + file: `models/c${i}.sql`, + title: `c${i}: long critical`, + body: `issue ${i} `.repeat(600), + }), + ), ...Array.from({ length: 10 }, (_, i) => finding({ model: `s${i}`, file: `models/s${i}.sql`, title: `s${i}: short suggestion ${i}` }), ), ] const md = renderSummary(buildEnvelope({ findings: fs, tier: "full", mode: "comment" })) expect(md.length).toBeLessThanOrEqual(SUMMARY_BUDGET_CHARS) - expect(md).toContain("a: short critical") - expect(md).not.toContain("b: long critical") + expect(md).toContain("c0: long critical") + expect(md).not.toContain("c11: long critical") expect(md).not.toContain("short suggestion") - expect(md).toContain("Critical (1 of 2)") + const shown = Number(/Critical \((\d+) of 12\)/.exec(md)?.[1]) + expect(shown).toBeGreaterThanOrEqual(3) expect(md).not.toMatch(/### 💡 Suggestion/) - expect(md).toContain("11 more finding(s) not shown (1 critical, 10 suggestion)") + expect(md).toContain(`${22 - shown} more finding(s) not shown (${12 - shown} critical, 10 suggestion)`) + }) + + test("a critical with a huge body is still listed: bullet bodies are clipped", () => { + // One critical whose body alone would fill the budget: the gate comment must + // not say "Changes requested — 1 critical" while listing nothing. + const fs: Finding[] = [ + finding({ + severity: "critical", + category: "pii_exposure", + model: "b", + file: "models/b.sql", + title: "b: exposes PII column (ssn)", + body: "y".repeat(4_800), + }), + ] + const md = renderSummary(buildEnvelope({ findings: fs, tier: "full", mode: "gate" })) + expect(md.length).toBeLessThanOrEqual(SUMMARY_BUDGET_CHARS) + expect(md).toContain("b: exposes PII column (ssn)") + expect(md).toContain("Critical (1)") + expect(md).not.toContain("more finding(s) not shown") + expect(md).not.toContain("y".repeat(700)) + // Local output keeps the whole body. + expect(renderSummary(buildEnvelope({ findings: fs, tier: "full", mode: "gate" }), { maxChars: Infinity })).toContain( + "y".repeat(4_800), + ) }) test("the metadata is budgeted too: a run with no findings and huge metadata stays within budget", () => { From d272b58ce565cbcfc749e99f49908b86b9b4e222 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Wed, 25 Nov 2026 17:40:04 +0530 Subject: [PATCH 20/81] fix(review): report PII outputs the parser cannot resolve instead of assuming the base exposed them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A head PII name the final select did not resolve counted as base-exposed whenever the base did not resolve it either. That was meant for `select *` from a table, but also hid unmaskings in shapes the parser does not model: - A top-level parenthesised set operation (`(select …) union all (select …)`) has no final items, so it now counts as unresolved and is reported unless the final select passes columns through a plain `*` (`passthrough`). - A CTE with a column list (`with m (id, tax) as (…)`) was read as a table `m`, so `m.tax` matched on both sides. It is now a CTE; the renamed column resolves to nothing known and is reported. - BigQuery `select * except (ssn)` was split at `except` as a set operation, leaving a plain `*`. It is now one item, not a passthrough star. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 9 +++++--- .../src/altimate/review/rule-catalog.ts | 23 +++++++++++++++---- .../test/altimate/review-rule-catalog.test.ts | 18 ++++++++++++++- .../opencode/test/altimate/review.test.ts | 22 ++++++++++++++++++ 4 files changed, 63 insertions(+), 9 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 54930160fa..f674cbc2bc 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1266,8 +1266,8 @@ export async function runReview(input: OrchestrateInput): Promise) => { const head = outputs(file, "new") const rawColumns = head.raw.get(name) @@ -1282,7 +1282,10 @@ export async function runReview(input: OrchestrateInput): Promise baseSigs.has(sig)) } - return !base.names.has(name) || base.raw.has(name) + // Unresolved only through a plain `*`: a shape the parser does not model (a + // parenthesised top-level union, `* except (…)`) is reported. + if (!head.passthrough) return false + return base.raw.has(name) || (!base.names.has(name) && base.passthrough) } for (const ctx of ctxByPath.values()) { const tasks: Promise[] = [] diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 40be0c9286..926c1cf894 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -318,7 +318,12 @@ function parseSelects(sql: string): ParsedSelects { const selects: Array<{ scope: string; branch: number; end: number }> = [] const scopes: string[] = ["final"] const branches = new Map() - const cteHead = new RegExp(String.raw`(${SEGMENT})\s+as\s*(?:(?:not\s+)?materialized\s*)?$`, "i") + // `name as (`, or `name (col, …) as (`: a column list still names the CTE, whose + // outputs then keep the body's own names (so a renamed column resolves to nothing). + const cteHead = new RegExp( + String.raw`(${SEGMENT})\s*(?:\([^()]*\)\s*)?\s+as\s*(?:(?:not\s+)?materialized\s*)?$`, + "i", + ) const tableRef = new RegExp(String.raw`^\s*((?:${SEGMENT}\s*\.\s*)*${SEGMENT})`, "i") let nested = 0 for (let i = 0; i < s.length; i++) { @@ -371,7 +376,13 @@ function parseSelects(sql: string): ParsedSelects { else if (depth === 0 && d === ",") { push(j) itemStart = j + 1 - } else if (depth === 0 && !isWordChar(s[j - 1]) && SELECT_LIST_END.test(s.slice(j, j + 10))) { + } else if ( + depth === 0 && + !isWordChar(s[j - 1]) && + SELECT_LIST_END.test(s.slice(j, j + 10)) && + // `* except (…)` (BigQuery) is one item, not a set operation. + !(/^except\b/i.test(s.slice(j, j + 7)) && /\*\s*$/.test(s.slice(itemStart, j))) + ) { push(j) end = j break @@ -447,13 +458,15 @@ export interface FinalOutputs { raw: Map> /** Every output name the final projection resolves. */ names: Set + /** The final projection has a plain `*`, so it also passes through unnamed columns. */ + passthrough: boolean /** Per output name, a signature of how it is computed: the item text 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> } -interface ScopeOutputs extends FinalOutputs { +interface ScopeOutputs extends Omit { /** `*` items, whose columns pass through unnamed (`select * from customers`). */ stars: Array<{ branch: number; qualifier?: string }> /** Every item's text, and that of every scope it reads. */ @@ -575,8 +588,8 @@ export function finalOutputs(sql: string): FinalOutputs { memo.set(scope, result) return result } - const { raw, names, signatures } = resolve("final", new Set()) - return { raw, names, signatures } + const { raw, names, signatures, stars } = resolve("final", new Set()) + return { raw, names, signatures, passthrough: stars.length > 0 } } /** A diff line with comments and whitespace normalised (and a leading/trailing diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 8233a2bb81..fbf0e6a250 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -1,5 +1,12 @@ import { describe, test, expect } from "bun:test" -import { CATALOG, ruleMatches, inputFromExample, rawColumnExposures, selectItemColumns } from "../../src/altimate/review/rule-catalog" +import { + CATALOG, + ruleMatches, + inputFromExample, + finalOutputs, + rawColumnExposures, + selectItemColumns, +} from "../../src/altimate/review/rule-catalog" describe("rule catalog (self-verifying scenario corpus)", () => { test("every rule fires on its example and stays clean on its counter", () => { @@ -103,6 +110,15 @@ describe("rawColumnExposures", () => { }) expect(asObject(rawColumnExposures("select ssn from (select * from customers) as s"))).toEqual({ ssn: ["customers.ssn"] }) }) + test("only a plain `*` passes columns through; `* except (…)` does not", () => { + expect(finalOutputs("select * from customers").passthrough).toBe(true) + expect(finalOutputs("select c.* from customers c").passthrough).toBe(true) + expect(finalOutputs("select * except (ssn) from customers").passthrough).toBe(false) + }) + test("a CTE with a column list is still a CTE: a renamed column resolves to nothing known", () => { + const sql = "with m (id, tax) as (select customer_id, ssn from customers)\nselect tax as ssn from m" + expect([...(rawColumnExposures(sql).get("ssn") ?? [])][0]).toMatch(/^\?\d+\.tax$/) + }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 4ac7e93134..5f2584f9d5 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2535,6 +2535,28 @@ describe("orchestrate", () => { expectReportedPii(runs, ["ssn"]) }) + test("query shapes the parser does not model are reported, not assumed exposed", async () => { + const cases: Array<[string, string]> = [ + // Top-level parenthesised set operation: the final select has no items of its own. + [ + "(select customer_id, sha2(ssn) as ssn from a)\nunion all\n(select customer_id, sha2(ssn) as ssn from b)", + "(select customer_id, ssn from a)\nunion all\n(select customer_id, ssn from b)", + ], + // A CTE column list renames the body's outputs. + [ + "with m (id, tax) as (select customer_id, sha2(ssn) from customers)\nselect id, tax as ssn from m", + "with m (id, tax) as (select customer_id, ssn from customers)\nselect id, tax as ssn from m", + ], + ] + for (const [base, head] of cases) { + const runs = await piiRuns(head, base, `-${base.split("\n").pop()}\n+${head.split("\n").pop()}\n`, ["ssn"]) + expectReportedPii(runs, ["ssn"], "none") + } + // Control: a plain `select *` on both sides is not new exposure. + const star = await piiRuns("select *\nfrom customers", "select * from customers", "-select * from customers\n+select *\n", ["ssn"]) + expect(star[0].env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + }) + test("a PII line moved from a CTE into the final select is not a reindent", async () => { // ` email,` leaves the CTE and the same text lands in the final select: the // model's output now carries `email`, though the line matches a removed one. From 619331adda6dd889ec018881d857019e5baa3a27 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:11:52 +0530 Subject: [PATCH 21/81] fix(review): give the root query a scope no CTE can share, so a CTE named `final` stays a CTE The outermost select was keyed `final`, the same key a CTE named `final` (the dbt style guide's last CTE) pushed, so the CTE body became branch 0 of the model's output: the outer select took the CTE's names by position and a base that masks a column inside `final` looked raw. The root scope is now `ROOT_SCOPE`, which no identifier unquotes to. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/rule-catalog.ts | 12 ++++++++---- .../test/altimate/review-rule-catalog.test.ts | 17 +++++++++++++++++ packages/opencode/test/altimate/review.test.ts | 12 ++++++++++++ 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 926c1cf894..6f8e20fe2c 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -207,6 +207,10 @@ const SELECT_LIST_END = const unquote = (s: string) => s.replace(/^["`]|["`]$/g, "").toLowerCase() +/** Scope key of the model's outermost query. No identifier unquotes to it, so a + * CTE named `final` (the dbt style guide's last CTE) keeps its own scope. */ +export const ROOT_SCOPE = "\u0000root" + /** One item of a select list, located in its query scope. */ export interface SelectItem { /** Output name: the alias (with or without `AS`) or a bare column's own name. */ @@ -217,7 +221,7 @@ export interface SelectItem { rawQualifier?: string /** Whitespace-normalised item text, for comparing one item across base and head. */ text: string - /** `final` for the outermost query, the CTE name for a CTE body, `>sub` for a nested query. */ + /** `ROOT_SCOPE` for the outermost query, the CTE name for a CTE body, `>sub` for a nested query. */ scope: string /** Which `UNION`/`INTERSECT`/`EXCEPT` branch of its scope (0 for the first select). */ branch: number @@ -316,7 +320,7 @@ function parseSelects(sql: string): ParsedSelects { const parenScope = new Map() // Each select's scope, branch and the offset its select list ends at. const selects: Array<{ scope: string; branch: number; end: number }> = [] - const scopes: string[] = ["final"] + const scopes: string[] = [ROOT_SCOPE] const branches = new Map() // `name as (`, or `name (col, …) as (`: a column list still names the CTE, whose // outputs then keep the body's own names (so a renamed column resolves to nothing). @@ -443,7 +447,7 @@ function parseSelects(sql: string): ParsedSelects { /** * Every select list in `sql`, item by item, with the query scope each belongs * to. Scope is what separates a CTE's `ssn as contact` from the final select's - * `email as contact`: only `final` items are the model's output. Items are + * `email as contact`: only `ROOT_SCOPE` items are the model's output. Items are * parsed across lines, so a multi-line expression or alias is one item. */ export function selectItems(sql: string): SelectItem[] { @@ -588,7 +592,7 @@ export function finalOutputs(sql: string): FinalOutputs { memo.set(scope, result) return result } - const { raw, names, signatures, stars } = resolve("final", new Set()) + const { raw, names, signatures, stars } = resolve(ROOT_SCOPE, new Set()) return { raw, names, signatures, passthrough: stars.length > 0 } } diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index fbf0e6a250..11acdb1893 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -119,6 +119,23 @@ describe("rawColumnExposures", () => { const sql = "with m (id, tax) as (select customer_id, ssn from customers)\nselect tax as ssn from m" expect([...(rawColumnExposures(sql).get("ssn") ?? [])][0]).toMatch(/^\?\d+\.tax$/) }) + test("a CTE named `final` is a CTE, not the model's output", () => { + // The outer `b` is the output; the CTE outputs no `b`, so it resolves to nothing known. + const lost = finalOutputs("with final as (select a from t) select b from final") + expect([...lost.names]).toEqual(["b"]) + expect([...lost.raw.keys()]).toEqual(["b"]) + expect([...lost.raw.get("b")!][0]).toMatch(/^\?\d+\.b$/) + // Masked in the CTE, selected by name or through `*`: nothing raw. + const masked = "with final as (select id, md5(email) as email from customers) select id, email from final" + expect(asObject(rawColumnExposures(masked))).toEqual({ id: ["customers.id"] }) + expect(asObject(rawColumnExposures(masked.replace("select id, email from final", "select * from final")))).toEqual({ + id: ["customers.id"], + }) + // Masked in the outer list: nothing raw, and the outer names are the outputs. + const outer = "with final as (select id, email from customers) select id, md5(email) as email_hash from final" + expect(asObject(rawColumnExposures(outer))).toEqual({ id: ["customers.id"] }) + expect([...finalOutputs(outer).names].sort()).toEqual(["email_hash", "id"]) + }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 5f2584f9d5..bce86705f6 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2507,6 +2507,18 @@ describe("orchestrate", () => { expectReportedPii(runs2, ["ssn"], "none") }) + test("a CTE named `final` does not make a masked base look raw", async () => { + // The dbt style guide's last CTE is `final`: the base masks `email` in it. + const base = "with final as (select customer_id, md5(email) as email from customers)\nselect customer_id, email from final" + // Dropping the CTE and selecting `email` raw unmasks it. + const head = "select customer_id, email\nfrom customers" + expectReportedPii(await piiRuns(head, base, `-${base.split("\n")[1]}\n+${head.split("\n")[0]}\n`, ["email"]), ["email"], "none") + // Control: an unrelated edit that keeps the masked `final` CTE exposes nothing new. + const touched = base.replace("select customer_id, email from final", "select customer_id, email\nfrom final") + const quiet = await piiRuns(touched, base, "-select customer_id, email from final\n+select customer_id, email\n+from final\n", ["email"]) + for (const { env } of quiet) expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + }) + test("a FROM subquery is a source: a column it masked is not credited as raw", async () => { const base = "select s.customer_id, s.ssn\nfrom (select customer_id, sha2(ssn) as ssn from customers) s" const head = "select customer_id, ssn\nfrom customers" From 81259a4ead62a7cdbdf5cc2f3f4b85cda925b19c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:15:07 +0530 Subject: [PATCH 22/81] fix(review): judge a computed head output by the source columns it reads, and keep literals in signatures A head PII output that is not a raw column was treated as already exposed whenever the base exposed that name raw, so base `email` -> head `lower(ssn) as email` (or `c.ssn` -> `lower(s.ssn) as ssn` from `spouses`) went unreported: neither regex twin matches a line starting with a call, and the classifier skips a name that is not new. `finalOutputs` now records, per output name, every `source.column` its value is computed from (`reads`), resolved through qualifiers, CTEs and subqueries like `raw`. The fallback treats a computed output as base-exposed only when every column it reads is one a base PII output exposed raw, or when the base computes it identically. Signatures now keep string-literal text, so changing a masking regex is a different computation. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 12 +- .../src/altimate/review/rule-catalog.ts | 110 +++++++++++++++--- .../test/altimate/review-rule-catalog.test.ts | 18 +++ .../opencode/test/altimate/review.test.ts | 24 ++++ 4 files changed, 141 insertions(+), 23 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index f674cbc2bc..ceebb50761 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1263,9 +1263,11 @@ export async function runReview(input: OrchestrateInput): Promise) => { @@ -1278,7 +1280,9 @@ export async function runReview(input: OrchestrateInput): Promise exposed.has(ref))) return true const baseSigs = base.signatures.get(name) return !!baseSigs && [...(head.signatures.get(name) ?? [])].every((sig) => baseSigs.has(sig)) } diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 6f8e20fe2c..07499690a7 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -221,6 +221,12 @@ export interface SelectItem { rawQualifier?: string /** Whitespace-normalised item text, for comparing one item across base and head. */ text: string + /** As `text`, with string-literal contents kept: `regexp_replace(ssn, '\\d', '*')` + * and `regexp_replace(ssn, '^$', '*')` differ here. */ + exact: string + /** For an item that is not a raw column, every column reference its expression + * reads (outside `over (…)`, `filter (…)` and `within group (…)`). */ + reads?: Array<{ qualifier?: string; column: string }> /** `ROOT_SCOPE` for the outermost query, the CTE name for a CTE body, `>sub` for a nested query. */ scope: string /** Which `UNION`/`INTERSECT`/`EXCEPT` branch of its scope (0 for the first select). */ @@ -238,23 +244,58 @@ export interface SelectItem { * still map to source lines. One left-to-right pass, so `--` inside a literal or * a quote inside a comment is not misread. */ -function maskSql(sql: string): string { +function maskSql(sql: string, keepLiterals = false): string { return sql.replace(/\{#[\s\S]*?#\}|\{%[\s\S]*?%\}|\{\{[\s\S]*?\}\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'/g, (m) => { if (m.startsWith("{{")) return m.replace(/[^\n]/g, "_") - if (m.startsWith("'")) return `'${m.slice(1, -1).replace(/[^\n]/g, " ")}'` + if (m.startsWith("'")) return keepLiterals ? m : `'${m.slice(1, -1).replace(/[^\n]/g, " ")}'` return m.replace(/[^\n]/g, " ") }) } const isWordChar = (c: string | undefined) => !!c && /[\w$."`]/.test(c) -function describeItem(raw: string): Pick { - const text = raw +const normalizeItem = (raw: string) => + raw .replace(/\s+/g, " ") .replace(/\(\s+/g, "(") .replace(/\s+([),])/g, "$1") .replace(/\s*\.\s*/g, ".") .trim() + +// Words in an expression that are syntax, never a column. +const EXPR_KEYWORDS = new Set( + "and or not is null true false case when then else end as in like ilike rlike regexp similar escape between distinct all any some exists over partition by order asc desc nulls first last rows range groups unbounded preceding following current row filter within group interval from for at time zone collate both leading trailing using separator respect ignore cast try_cast".split( + " ", + ), +) +const COLUMN_TOKEN = new RegExp(String.raw`(? { + let e = expr.replace(/'(?:[^']|'')*'/g, " ") + // `over (…)` / `filter (…)` / `within group (…)`: cut each clause to its `)`. + for (let m = /\b(?:over|filter|within\s+group)\s*\(/i.exec(e); m; m = /\b(?:over|filter|within\s+group)\s*\(/i.exec(e)) { + const open = m.index + m[0].length - 1 + e = e.slice(0, m.index) + " " + e.slice(closingParen(e, open) + 1) + } + e = e + .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 }> = [] + 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 }) + } + return out +} + +function describeItem(raw: string): Pick { + const text = normalizeItem(raw) let expr = text let alias: string | undefined const explicit = EXPLICIT_ALIAS.exec(text) @@ -264,7 +305,8 @@ function describeItem(raw: string): Pick re.exec(expr)).find(Boolean) const rawColumn = ref ? unquote(ref[2]) : undefined const rawQualifier = ref?.[1] ? unquote(ref[1]) : undefined - return { name: alias ? unquote(alias) : rawColumn, rawColumn, rawQualifier, text } + const name = alias ? unquote(alias) : rawColumn + return ref ? { name, rawColumn, rawQualifier, text } : { name, text, reads: columnReads(expr) } } // Words that end a FROM clause's table list at its own nesting level. @@ -302,6 +344,7 @@ function closingParen(s: string, open: number): number { 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) const lineOf = (offset: number) => { @@ -366,7 +409,15 @@ function parseSelects(sql: string): ParsedSelects { if (!raw.trim()) return const first = itemStart + (raw.length - raw.trimStart().length) const last = itemStart + raw.trimEnd().length - 1 - items.push({ ...describeItem(raw), scope, branch, position: position++, startLine: lineOf(first), endLine: lineOf(last) }) + items.push({ + ...describeItem(raw), + exact: normalizeItem(withLiterals.slice(itemStart, stop)), + scope, + branch, + position: position++, + startLine: lineOf(first), + endLine: lineOf(last), + }) } for (let j = start; j <= s.length; j++) { const d = s[j] @@ -464,10 +515,14 @@ export interface FinalOutputs { names: Set /** The final projection has a plain `*`, so it also passes through unnamed columns. */ passthrough: boolean - /** Per output name, a signature of how it is computed: the item text 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. */ + /** Per output name, a signature of how it is computed: the item text (string + * literals included) 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, 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> } interface ScopeOutputs extends Omit { @@ -520,15 +575,24 @@ export function finalOutputs(sql: string): FinalOutputs { const memo = new Map() const isDerived = (src: Source, scope: string, seen: Set) => src.name !== scope && byScope.has(src.name) && !seen.has(src.name) - // The `source.column` refs a column read in `scope#branch` resolves to. - const resolveRef = (scope: string, branch: number, qualifier: string | undefined, col: string, seen: Set) => { + // The `source.column` refs a column read in `scope#branch` resolves to: those + // it exposes raw (`key: "raw"`; a column a CTE computes is none), or every one + // its value is computed from (`key: "reads"`). + const resolveRef = ( + scope: string, + branch: number, + qualifier: string | undefined, + col: string, + seen: Set, + key: "raw" | "reads" = "raw", + ): Set => { const srcs = sources.get(`${scope}#${branch}`) ?? [] const inner = new Set([...seen, scope]) const fromSource = (src: Source): Set => { if (!isDerived(src, scope, seen)) return byScope.has(src.name) ? unresolved(col) : new Set([`${src.name}.${col}`]) const out = resolve(src.name, inner) - if (out.names.has(col)) return out.raw.get(col) ?? new Set() - if (out.stars.length) return union(out.stars.map((st) => resolveRef(src.name, st.branch, st.qualifier, col, inner))) + if (out.names.has(col)) return out[key].get(col) ?? new Set() + if (out.stars.length) return union(out.stars.map((st) => resolveRef(src.name, st.branch, st.qualifier, col, inner, key))) return unresolved(col) } if (qualifier) { @@ -554,6 +618,7 @@ export function finalOutputs(sql: string): FinalOutputs { const raw = new Map>() const names = new Set() const signatures = new Map>() + const reads = new Map>() const stars: ScopeOutputs["stars"] = [] const addTo = (map: Map>, name: string, values: Iterable) => { const set = map.get(name) ?? new Set() @@ -577,23 +642,30 @@ 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, cols] of out.reads) addTo(reads, n, cols) } continue } const name = item.branch === 0 ? item.name : firstNames.get(item.position) if (!name) continue names.add(name) - addTo(signatures, name, [`${item.text.toLowerCase()}\u0001${bodies.join("\u0002")}`]) - if (item.rawColumn) addTo(raw, name, resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen)) + addTo(signatures, name, [`${item.exact.toLowerCase()}\u0001${bodies.join("\u0002")}`]) + if (item.rawColumn) { + addTo(raw, name, resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen)) + addTo(reads, name, resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen, "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")) + } } for (const [n, cols] of raw) if (!cols.size) raw.delete(n) - const body = [scopeItems.map((i) => i.text.toLowerCase()).join(","), ...[...readBodies].sort()].join("\u0003") - const result = { raw, names, signatures, stars, body } + const body = [scopeItems.map((i) => i.exact.toLowerCase()).join(","), ...[...readBodies].sort()].join("\u0003") + const result = { raw, names, signatures, reads, stars, body } memo.set(scope, result) return result } - const { raw, names, signatures, stars } = resolve(ROOT_SCOPE, new Set()) - return { raw, names, signatures, passthrough: stars.length > 0 } + const { raw, names, signatures, reads, stars } = resolve(ROOT_SCOPE, new Set()) + return { raw, names, signatures, reads, passthrough: stars.length > 0 } } /** A diff line with comments and whitespace normalised (and a leading/trailing diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 11acdb1893..ead0aa0772 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -136,6 +136,24 @@ describe("rawColumnExposures", () => { expect(asObject(rawColumnExposures(outer))).toEqual({ id: ["customers.id"] }) expect([...finalOutputs(outer).names].sort()).toEqual(["email_hash", "id"]) }) + test("`reads` lists the source columns a computed output is built from", () => { + const sql = [ + "with k as (select customer_id, sha2(ssn) as ssn from customers)", + "select lower(s.ssn) as a,", + " case when c.active is not null then cast(c.email as varchar(20)) else 'n/a' end as b,", + " first_value(c.phone) over (partition by c.customer_id order by c.updated_at) as d,", + " upper(k.ssn) as e, 'x' as f", + "from customers c join spouses s on true join k on true", + ].join("\n") + const reads = Object.fromEntries([...finalOutputs(sql).reads].map(([k, v]) => [k, [...v].sort()])) + expect(reads).toEqual({ + a: ["spouses.ssn"], + b: ["customers.active", "customers.email"], + d: ["customers.phone"], + e: ["customers.ssn"], + f: [], + }) + }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index bce86705f6..6c28ab1d77 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2483,6 +2483,30 @@ describe("orchestrate", () => { } }) + test("a computed head output under a name the base exposed raw is reported when it reads a new source", async () => { + // Base `email` raw → head `lower(ssn) as email`: the name was exposed, its source is new. + const base = "select customer_id,\n email\nfrom customers" + const head = "select customer_id,\n lower(ssn) as email\nfrom customers" + expectReportedPii(await piiRuns(head, base, "- email\n+ lower(ssn) as email\n", ["email"]), ["email"], "none") + // Base `c.ssn` → head `lower(s.ssn) as ssn` from `spouses`. + const baseS = "select c.customer_id,\n c.ssn\nfrom customers c\njoin spouses s on s.customer_id = c.customer_id" + const headS = baseS.replace(" c.ssn\n", " lower(s.ssn) as ssn\n") + expectReportedPii(await piiRuns(headS, baseS, "- c.ssn\n+ lower(s.ssn) as ssn\n", ["ssn"]), ["ssn"], "none") + // Control: a function over the same raw column is not new exposure. + const lowered = await piiRuns(base.replace(" email", " lower(email) as email"), base, "- email\n+ lower(email) as email\n", ["email"]) + for (const { env } of lowered) expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + }) + + test("a changed literal in a masking expression is a different computation", async () => { + const from = "regexp_replace(ssn, '\\d', '*') as ssn" + const to = "regexp_replace(ssn, '^$', '*') as ssn" + const sql = (item: string) => `select customer_id,\n ${item}\nfrom customers` + expectReportedPii(await piiRuns(sql(to), sql(from), `- ${from}\n+ ${to}\n`, ["ssn"]), ["ssn"], "none") + // Control: the same masking expression, unchanged, next to an unrelated edit. + const quiet = await piiRuns(sql(from).replace("customer_id,", "customer_id, region,"), sql(from), "-select customer_id,\n+select customer_id, region,\n", ["ssn"]) + for (const { env } of quiet) expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + }) + test("a qualified reference resolves through its own source, not any CTE with that column", async () => { // Base reads `home_address` masked from CTE `m`; head reads it raw from `customers c`. const base = [ From fa570f820eebef98e210e20b431a61f66b4fc4dc Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:16:20 +0530 Subject: [PATCH 23/81] fix(review): credit columns a base `select *` passed through, and match an unqualified column across an added join - A base `select * from customers` named no outputs, so expanding it into an explicit list reported every pre-existing PII column as new. `finalOutputs` now exposes `starRaw(column)`, the raw refs the final `*` items pass a column through as, and the base's PII refs include them for a base PII name the final select does not name. A `*` over a CTE that masks the column still credits nothing. - An unqualified column over a join resolves to a combined `a|b.col` ref, which never matched the base's single-table ref, so adding a join reported the column as new. `refCovered` matches a combined ref to a single-table ref of one of its members (and the reverse); two combined refs match only if equal. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 22 ++++++--- .../src/altimate/review/rule-catalog.ts | 32 ++++++++++++- .../test/altimate/review-rule-catalog.test.ts | 15 +++++++ .../opencode/test/altimate/review.test.ts | 45 +++++++++++++++++++ 4 files changed, 107 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index ceebb50761..f6d0ce5e04 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -19,6 +19,7 @@ import { type SelectItem, type SelectItemColumn, finalOutputs, + refCovered, normalizeSelectLine, selectItems, } from "./rule-catalog" @@ -1237,13 +1238,22 @@ export async function runReview(input: OrchestrateInput): Promise>() const baseRawPii = (file: string) => { + const cached = baseRawPiiByFile.get(file) + if (cached) return cached const basePii = basePiiColumnsByFile.get(file) const refs = new Set() if (!basePii) return refs - const raw = outputs(file, "old").raw - for (const name of basePii) for (const ref of raw.get(name) ?? []) refs.add(ref) + const base = outputs(file, "old") + for (const name of basePii) { + for (const ref of base.raw.get(name) ?? []) refs.add(ref) + if (!base.names.has(name) && base.passthrough) for (const ref of base.starRaw(name)) refs.add(ref) + } + baseRawPiiByFile.set(file, refs) return refs } // A regex twin's SOURCE column (`ssn`, with its output alias when it has one) is @@ -1258,7 +1268,7 @@ export async function runReview(input: OrchestrateInput): Promise r.endsWith(`.${column}`)) if (!refs.length) return false const exposed = baseRawPii(file) - return refs.every((r) => exposed.has(r)) + return refs.every((r) => refCovered(r, exposed)) } // A head PII output name the base already exposed. When the head selects a // column raw under it, the base must expose that same source column raw (base @@ -1275,14 +1285,14 @@ export async function runReview(input: OrchestrateInput): Promise exposed.has(ref)) + return [...rawColumns].every((ref) => refCovered(ref, exposed)) } if (!basePii.has(name)) return false const base = outputs(file, "old") if (head.names.has(name)) { const exposed = baseRawPii(file) const reads = head.reads.get(name) - if (reads && [...reads].every((ref) => exposed.has(ref))) return true + if (reads && [...reads].every((ref) => refCovered(ref, exposed))) return true const baseSigs = base.signatures.get(name) return !!baseSigs && [...(head.signatures.get(name) ?? [])].every((sig) => baseSigs.has(sig)) } diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 07499690a7..d0fb3c2a62 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -515,6 +515,10 @@ export interface FinalOutputs { names: Set /** The final projection has a plain `*`, so it also passes through unnamed columns. */ passthrough: boolean + /** The `source.column` refs the final projection's plain `*` items expose raw + * for a column they pass through unnamed (`select * from customers` → + * `ssn: {customers.ssn}`; a CTE that masks it → none). */ + starRaw: (column: string) => Set /** Per output name, a signature of how it is computed: the item text (string * literals included) 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. */ @@ -555,6 +559,30 @@ export function rawColumnExposures(sql: string): Map> { let unresolvedRefs = 0 +const splitRef = (ref: string) => { + const dot = ref.lastIndexOf(".") + return { tables: ref.slice(0, dot).split("|"), column: ref.slice(dot + 1) } +} + +/** + * `ref` is one of the `exposed` source columns. An unqualified column read over + * several tables (`customers|orders.email`, see `rawColumnExposures`) comes from + * exactly one of them (the query would be ambiguous otherwise), so it matches a + * single-table ref to one of its members, and the reverse. Two combined refs + * match only when equal. + */ +export function refCovered(ref: string, exposed: Set): boolean { + if (exposed.has(ref)) return true + const r = splitRef(ref) + for (const e of exposed) { + const x = splitRef(e) + if (x.column !== r.column) continue + if (r.tables.length > 1 && x.tables.length === 1 && r.tables.includes(x.tables[0])) return true + if (r.tables.length === 1 && x.tables.length > 1 && x.tables.includes(r.tables[0])) return true + } + return false +} + /** The model's final output: every name it resolves, the source columns each * exposes raw (as `rawColumnExposures`), and how each is computed. */ export function finalOutputs(sql: string): FinalOutputs { @@ -665,7 +693,9 @@ export function finalOutputs(sql: string): FinalOutputs { return result } const { raw, names, signatures, reads, stars } = resolve(ROOT_SCOPE, new Set()) - return { raw, names, signatures, reads, passthrough: stars.length > 0 } + const starRaw = (column: string) => + union(stars.map((st) => resolveRef(ROOT_SCOPE, st.branch, st.qualifier, column, new Set()))) + return { raw, names, signatures, reads, passthrough: stars.length > 0, starRaw } } /** A diff line with comments and whitespace normalised (and a leading/trailing diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index ead0aa0772..dff5731916 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -5,6 +5,7 @@ import { inputFromExample, finalOutputs, rawColumnExposures, + refCovered, selectItemColumns, } from "../../src/altimate/review/rule-catalog" @@ -154,6 +155,20 @@ describe("rawColumnExposures", () => { f: [], }) }) + test("`starRaw` resolves a column a plain `*` passes through", () => { + expect([...finalOutputs("select * from customers").starRaw("ssn")]).toEqual(["customers.ssn"]) + expect([...finalOutputs("select c.* from customers c join orders o on true").starRaw("ssn")]).toEqual(["customers.ssn"]) + // A CTE that masks it exposes nothing raw through `*`. + const masked = "with m as (select customer_id, sha2(ssn) as ssn from customers) select * from m" + expect([...finalOutputs(masked).starRaw("ssn")]).toEqual([]) + }) + test("`refCovered` matches an unqualified column over a join to its single-table ref", () => { + expect(refCovered("customers|orders.email", new Set(["customers.email"]))).toBe(true) + expect(refCovered("customers.email", new Set(["customers|orders.email"]))).toBe(true) + expect(refCovered("customers|orders.email", new Set(["spouses.email"]))).toBe(false) + expect(refCovered("customers|orders.email", new Set(["customers.ssn"]))).toBe(false) + expect(refCovered("a|b.email", new Set(["b|c.email"]))).toBe(false) + }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 6c28ab1d77..a266ac6b3a 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2507,6 +2507,51 @@ describe("orchestrate", () => { for (const { env } of quiet) expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) }) + test("expanding a base `select *` into explicit columns is not new exposure", async () => { + // detectPii sees the table's columns through `*`, as the real engine does with a schema. + const PII = ["email", "ssn"] + const runner: ReviewRunner = { + ...piiRunner(PII), + async detectPii(sql: string) { + return { columns: PII.filter((c) => sql.includes(c) || /select\s+\*\s+from\s+customers/i.test(sql)) } + }, + } + const base = "select * from customers" + const run = (head: string, reviewers: string[]) => + runReview({ + changedFiles: MARTS.map((path) => ({ + path, + status: "modified" as const, + diff: `-${base}\n${head + .split("\n") + .map((l) => `+${l}`) + .join("\n")}\n`, + })), + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner, + getContent: content(head, base), + }) + const expanded = "select customer_id,\n email,\n ssn\nfrom customers" + for (const reviewers of [["pii_exposure"], [], ["dbt_patterns"]]) { + const env = await run(expanded, reviewers) + expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + } + // Control: the same columns read from a different table are new. + const env = await run("select customer_id,\n email,\n ssn\nfrom spouses", ["pii_exposure"]) + const broad = env.findings.filter((f) => f.evidence?.tool === "schema.detect_pii") + expect(broad.map((f) => (f.evidence?.result as any)?.columns)).toEqual([["email", "ssn"], ["email", "ssn"], ["email", "ssn"]]) + }) + + test("adding a join does not make an unqualified PII column look new", async () => { + const base = "select customer_id,\n email\nfrom customers" + const head = "select customer_id,\n email\nfrom customers\njoin orders using (customer_id)" + for (const { reviewers, env } of await piiRuns(head, base, "+join orders using (customer_id)\n", ["email"])) + expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) + }) + test("a qualified reference resolves through its own source, not any CTE with that column", async () => { // Base reads `home_address` masked from CTE `m`; head reads it raw from `customers c`. const base = [ From 12aea2d438eb3870a790ac945f27c8036eb15199 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:16:53 +0530 Subject: [PATCH 24/81] =?UTF-8?q?fix(review):=20parse=20`select=20distinct?= =?UTF-8?q?=20on=20(=E2=80=A6)`=20as=20a=20prefix,=20not=20part=20of=20the?= =?UTF-8?q?=20first=20item?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The select-list prefix matched only `distinct|all|top n`, so on Postgres and DuckDB `select distinct on (id) ssn` parsed its first item as `on (id) ssn`: the base never credited `ssn` as raw and a later edit reported it as new. The `distinct on (…)` group is now skipped to its closing parenthesis. The prefix match also reads a bounded window instead of the rest of the file. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/rule-catalog.ts | 12 ++++++++---- .../test/altimate/review-rule-catalog.test.ts | 9 +++++++++ packages/opencode/test/altimate/review.test.ts | 7 +++++++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index d0fb3c2a62..b068ba36cd 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -395,11 +395,15 @@ function parseSelects(sql: string): ParsedSelects { const scope = scopes[scopes.length - 1] const branch = branches.get(scope) ?? 0 branches.set(scope, branch + 1) - // The list runs from after `select [distinct|all|top n]` to the first clause - // keyword, `)` or `;` at its own nesting level. + // The list runs from after `select [distinct [on (…)]|all|top n]` to the first + // clause keyword, `)` or `;` at its own nesting level. let start = i + 6 - const prefix = /^\s+(?:(?:distinct|all)\b|top\s+\d+\b)?/i.exec(s.slice(start)) - if (prefix) start += prefix[0].length + const distinctOn = /^\s+distinct\s+on\s*\(/i.exec(s.slice(start, start + 100)) + if (distinctOn) start = closingParen(s, start + distinctOn[0].length - 1) + 1 + else { + const prefix = /^\s+(?:(?:distinct|all)\b|top\s+\d+\b)?/i.exec(s.slice(start, start + 100)) + if (prefix) start += prefix[0].length + } let depth = 0 let itemStart = start let position = 0 diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index dff5731916..5ccc35d366 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -169,6 +169,15 @@ describe("rawColumnExposures", () => { expect(refCovered("customers|orders.email", new Set(["customers.ssn"]))).toBe(false) expect(refCovered("a|b.email", new Set(["b|c.email"]))).toBe(false) }) + test("`distinct on (…)` is a select prefix, not part of the first item", () => { + expect(asObject(rawColumnExposures("select distinct on (id) ssn, id from customers"))).toEqual({ + ssn: ["customers.ssn"], + id: ["customers.id"], + }) + expect(asObject(rawColumnExposures("select distinct on (date_trunc('day', ts), id) c.ssn from customers c"))).toEqual({ + ssn: ["customers.ssn"], + }) + }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index a266ac6b3a..bbb1306d44 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2552,6 +2552,13 @@ describe("orchestrate", () => { expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) }) + test("a column the base selected under `distinct on (…)` is credited as exposed", async () => { + const base = "select distinct on (customer_id) ssn, customer_id\nfrom customers" + const head = "select ssn, customer_id\nfrom customers" + for (const { reviewers, env } of await piiRuns(head, base, `-${base.split("\n")[0]}\n+${head.split("\n")[0]}\n`, ["ssn"])) + expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) + }) + test("a qualified reference resolves through its own source, not any CTE with that column", async () => { // Base reads `home_address` masked from CTE `m`; head reads it raw from `customers c`. const base = [ From 2ad0660b01331fcb5c955acfce91de5b2771c16b Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:17:56 +0530 Subject: [PATCH 25/81] fix(review): key a nested query by its alias, else number it within its parent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nested-query scopes were numbered across the whole file, so adding a subquery anywhere above an unchanged one renamed it (`sub1` -> `sub2`). The reindent check compares items by scope, so a pure reindent inside that subquery came back as a critical regex twin. A nested query is now keyed by the alias after its closing parenthesis (`(select …) s`, `(select …) as n`), and one without an alias is numbered within its parent scope. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/rule-catalog.ts | 27 ++++++++++++-- .../opencode/test/altimate/review.test.ts | 35 +++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index b068ba36cd..c60145f341 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -227,7 +227,8 @@ export interface SelectItem { /** For an item that is not a raw column, every column reference its expression * reads (outside `over (…)`, `filter (…)` and `within group (…)`). */ reads?: Array<{ qualifier?: string; column: string }> - /** `ROOT_SCOPE` for the outermost query, the CTE name for a CTE body, `>sub` for a nested query. */ + /** `ROOT_SCOPE` for the outermost query, the CTE name for a CTE body, and for a + * nested query `>` or, without one, `>sub`. */ scope: string /** Which `UNION`/`INTERSECT`/`EXCEPT` branch of its scope (0 for the first select). */ branch: number @@ -372,7 +373,27 @@ function parseSelects(sql: string): ParsedSelects { "i", ) const tableRef = new RegExp(String.raw`^\s*((?:${SEGMENT}\s*\.\s*)*${SEGMENT})`, "i") - let nested = 0 + // A nested query is keyed by the alias after its `)` (`(select …) s`, + // `(select …) as n`), else numbered within its parent, so a subquery added + // elsewhere does not rename it between base and head. + const nestedKeys = new Set() + const nestedCount = new Map() + const subAlias = new RegExp(String.raw`^\s+(?:as\s+)?(${SEGMENT})`, "i") + const nestedKey = (parent: string, open: number) => { + const close = closingParen(s, open) + const alias = subAlias.exec(s.slice(close + 1, close + 200))?.[1] + const named = + alias && !NOT_A_SOURCE_ALIAS.has(unquote(alias)) && !NOT_AN_ALIAS.has(unquote(alias)) && !SELECT_LIST_END.test(alias) + ? `${parent}>${unquote(alias)}` : undefined + let key = named + if (!key || nestedKeys.has(key)) { + const n = (nestedCount.get(parent) ?? 0) + 1 + nestedCount.set(parent, n) + key = `${named ?? parent}>sub${n}` + } + nestedKeys.add(key) + return key + } for (let i = 0; i < s.length; i++) { const c = s[i] if (c === "(") { @@ -382,7 +403,7 @@ function parseSelects(sql: string): ParsedSelects { // other parenthesis (a call, a grouping) stays in its parent's scope. if (cte && !/^as$/i.test(cte[1])) scopes.push(unquote(cte[1])) else if (/^[\s(]*select\b/i.test(s.slice(i + 1, i + 200))) { - scopes.push(`${parent}>sub${++nested}`) + scopes.push(nestedKey(parent, i)) parenScope.set(i, scopes[scopes.length - 1]) } else scopes.push(parent) continue diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index bbb1306d44..6dda3a6ade 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2645,6 +2645,41 @@ describe("orchestrate", () => { expect(star[0].env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) }) + test("a reindent inside a nested query stays a reindent when a subquery is added above it", async () => { + // Base PII detection misses `ssn`, so only the reindent check keeps the twin quiet. + const runner: ReviewRunner = { ...piiRunner([]), detectPii: async () => ({ columns: [] }) } + const base = [ + "with a as (select customer_id from customers)", + "select s.customer_id, s.ssn", + "from (", + " select customer_id,", + " ssn", + " from customers", + ") s", + ].join("\n") + const heads = [ + // A subquery added in another scope (a CTE). + base + .replace("select customer_id from customers)", "select customer_id from customers where customer_id in (select id from vip))") + .replace("\n ssn\n", "\n ssn\n"), + // A scalar subquery added earlier in the same scope. + base + .replace("s.ssn\n", "s.ssn, (select count(*) from orders o where o.customer_id = s.customer_id) as n\n") + .replace("\n ssn\n", "\n ssn\n"), + ] + for (const head of heads) { + 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, + getContent: content(head, base), + }) + expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) + } + }) + test("a PII line moved from a CTE into the final select is not a reindent", async () => { // ` email,` leaves the CTE and the same text lands in the final select: the // model's output now carries `email`, though the line matches a removed one. From 2e674a71e3d5e4001b7a2ac7ac69b10374e70092 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:19:18 +0530 Subject: [PATCH 26/81] fix(review): keep database and schema in a source table's identity A FROM/JOIN table was named by its last segment only, so `restricted.customers` and `public.customers` were the same source and switching a model to another schema's table of the same name counted as already exposed. The source name is now every segment, unquoted and lowercased; a column qualifier still matches a table by its last segment. The whitespace skip after `from`/`join` now reads a bounded window. The `keeps the source table` expectation for `schema1.employees.email` changes from `employees.email` to `schema1.employees.email` accordingly. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/rule-catalog.ts | 38 ++++++++++++------- .../test/altimate/review-rule-catalog.test.ts | 10 ++++- .../opencode/test/altimate/review.test.ts | 6 +++ 3 files changed, 40 insertions(+), 14 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index c60145f341..11122ca654 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -320,10 +320,13 @@ const NOT_A_SOURCE_ALIAS = new Set( ), ) -/** One FROM/JOIN source of a select: a table (last name segment), a CTE, or a - * FROM subquery (named by its scope), with the alias it is read under. */ +/** One FROM/JOIN source of a select: a table (its full relation name, every + * segment unquoted and lowercased), a CTE, or a FROM subquery (named by its + * scope), with the alias it is read under. */ interface Source { name: string + /** A schema-qualified table's last segment, which a column qualifier names it by. */ + short?: string alias?: string } @@ -474,6 +477,7 @@ function parseSelects(sql: string): ParsedSelects { // `from`, `join`, or a `,` inside a FROM list, with its alias, up to the end of // the select (`)`, `;`, a set operator). const aliasRe = new RegExp(String.raw`^\s+(?:as\s+)?(${SEGMENT})`, "i") + const segmentRe = new RegExp(SEGMENT, "g") for (const { scope, branch, end } of selects) { const read: Source[] = [] let inFrom = false @@ -489,8 +493,9 @@ function parseSelects(sql: string): ParsedSelects { const kw = boundary ? /^(from|join)\b/i.exec(s.slice(j, j + 5)) : null if (kw || (inFrom && d === ",")) { const after = j + (kw ? kw[0].length : 1) - const lead = after + (/^\s*/.exec(s.slice(after))?.[0].length ?? 0) + const lead = after + (/^\s*/.exec(s.slice(after, after + 200))?.[0].length ?? 0) let name: string | undefined + let short: string | undefined let rest = lead if (s[lead] === "(") { // A FROM subquery is a source under its alias; any other parenthesis @@ -500,16 +505,22 @@ function parseSelects(sql: string): ParsedSelects { } else { const ref = tableRef.exec(s.slice(after, after + 300)) if (ref) { - const last = ref[1].split(".").pop()!.trim() + const segments = [...ref[1].matchAll(segmentRe)].map((m) => m[0]) + const last = segments[segments.length - 1] const at = after + ref[0].length - last.length // A Jinja `{{ ref('x') }}` is masked to underscores: name it by its source text. - name = /^_+$/.test(last) ? sql.slice(at, at + last.length).replace(/\s+/g, "").toLowerCase() : unquote(last) + short = /^_+$/.test(last) ? sql.slice(at, at + last.length).replace(/\s+/g, "").toLowerCase() : unquote(last) + // Database and schema stay part of the identity: `restricted.customers` + // and `public.customers` are different tables. + name = [...segments.slice(0, -1).map(unquote), short].join(".") rest = after + ref[0].length } } if (name) { const alias = aliasRe.exec(s.slice(rest, rest + 200))?.[1] - read.push(alias && !NOT_A_SOURCE_ALIAS.has(unquote(alias)) ? { name, alias: unquote(alias) } : { name }) + const src: Source = short && short !== name ? { name, short } : { name } + if (alias && !NOT_A_SOURCE_ALIAS.has(unquote(alias))) src.alias = unquote(alias) + read.push(src) } inFrom = true j = after - 1 @@ -564,10 +575,11 @@ interface ScopeOutputs extends Omit { /** * Per output name of the model (its FINAL projection, never a CTE's or a * nested query's own aliases), the source columns it exposes RAW under that - * name, each as `source.column` where the source is the table (last name - * segment) the column is read from: `c.ssn as tax_ref` with `customers c` → - * `tax_ref: {customers.ssn}`, so the same column name from another table - * (`s.ssn` with `spouses s`) is a different exposure. A qualifier resolves + * name, each as `source.column` where the source is the table (its full + * relation name as written) the column is read from: `c.ssn as tax_ref` with + * `customers c` → `tax_ref: {customers.ssn}`, so the same column name from + * another table (`s.ssn` with `spouses s`, or `restricted.customers` vs + * `public.customers`) is a different exposure. A qualifier resolves * through its own FROM/JOIN source only; a column read from a CTE or a FROM * subquery takes that scope's exposure for it (masked there → nothing raw), and * `*` over them takes all of theirs. An unqualified column resolves through the @@ -649,10 +661,10 @@ export function finalOutputs(sql: string): FinalOutputs { return 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 && x.name === qualifier) ?? - srcs.find((x) => x.name === qualifier) + srcs.find((x) => x.alias === qualifier) ?? srcs.find((x) => !x.alias && named(x)) ?? srcs.find(named) return src ? fromSource(src) : unresolved(col) } const named = srcs.filter((x) => isDerived(x, scope, seen) && resolve(x.name, inner).names.has(col)) diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 5ccc35d366..2f09781447 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -92,7 +92,15 @@ describe("rawColumnExposures", () => { expect(asObject(rawColumnExposures(sql))).toEqual({ ssn: ["customers.ssn"], spouse_ssn: ["spouses.ssn"], - email: ["employees.email"], + email: ["schema1.employees.email"], + }) + }) + test("keeps the database and schema in the source identity", () => { + expect(asObject(rawColumnExposures("select ssn from restricted.customers"))).toEqual({ ssn: ["restricted.customers.ssn"] }) + expect(asObject(rawColumnExposures("select ssn from public.customers"))).toEqual({ ssn: ["public.customers.ssn"] }) + expect(asObject(rawColumnExposures('select c.ssn, customers.email from "DB"."Public"."Customers" c, raw.customers'))).toEqual({ + ssn: ["db.public.customers.ssn"], + email: ["raw.customers.email"], }) }) test("resolves a qualifier through its own source only", () => { diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 6dda3a6ade..cd7b81c5ab 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2559,6 +2559,12 @@ describe("orchestrate", () => { expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) }) + test("the same table name in another schema is a different source", async () => { + const base = "select customer_id,\n ssn\nfrom restricted.customers" + const head = "select customer_id,\n ssn\nfrom public.customers" + expectReportedPii(await piiRuns(head, base, "-from restricted.customers\n+from public.customers\n", ["ssn"]), ["ssn"], "none") + }) + test("a qualified reference resolves through its own source, not any CTE with that column", async () => { // Base reads `home_address` masked from CTE `m`; head reads it raw from `customers c`. const base = [ From 44c7ee00d11f67da71cf538a8acbbfec5c308555 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:21:27 +0530 Subject: [PATCH 27/81] fix(review): read a regex twin's alias like the select-list parser, and stop at clause text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `selectItemColumns` took the alias from a narrow `as name` regex, so `c.ssn tax_ref` had none and `c.ssn as "Tax Ref"` gave `tax`. It now uses the same explicit / implicit alias split as `selectItems`. - An alias on the next line is invisible to a one-line twin, so the base-exposure check now takes the output name from the head's final-select item that spans the twin's line and reads that column raw, falling back to the twin's own alias. - Tokens after a clause keyword at the query's own level (`email from ssn`, `where ssn …`) are no longer collected; a keyword inside a call (`extract(year from x)`) does not count, and a later `select` resumes. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 40 +++++++++---- .../src/altimate/review/rule-catalog.ts | 60 +++++++++++++++---- .../test/altimate/review-rule-catalog.test.ts | 13 ++++ .../opencode/test/altimate/review.test.ts | 41 +++++++++++++ 4 files changed, 131 insertions(+), 23 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index f6d0ce5e04..6d3b86642c 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -20,6 +20,7 @@ import { type SelectItemColumn, finalOutputs, refCovered, + ROOT_SCOPE, normalizeSelectLine, selectItems, } from "./rule-catalog" @@ -1264,11 +1265,18 @@ export async function runReview(input: OrchestrateInput): Promise { - const refs = [...(outputs(file, "new").raw.get(alias ?? column) ?? [])].filter((r) => r.endsWith(`.${column}`)) - if (!refs.length) return false + // The output name comes from the head's final-select item that spans the line + // and reads the column raw, so an alias on the next line counts; else the + // twin's own alias, else the column. + const isBaseExposed = (file: string, column: string, alias?: string, line?: string) => { + const spanning = line ? headItemsOnLine(file, line).filter((i) => i.scope === ROOT_SCOPE && i.rawColumn === column) : [] + const names = spanning.length ? [...new Set(spanning.map((i) => i.name!))] : [alias ?? column] + const head = outputs(file, "new").raw const exposed = baseRawPii(file) - return refs.every((r) => refCovered(r, exposed)) + return names.every((name) => { + const refs = [...(head.get(name) ?? [])].filter((r) => r.endsWith(`.${column}`)) + return refs.length > 0 && refs.every((r) => refCovered(r, exposed)) + }) } // A head PII output name the base already exposed. When the head selects a // column raw under it, the base must expose that same source column raw (base @@ -1498,23 +1506,33 @@ export async function runReview(input: OrchestrateInput): Promise; head: SelectItem[]; headLines: string[]; base: Set }>() const itemKey = (i: SelectItem) => `${i.scope}#${i.branch}\u0000${i.text.toLowerCase()}` - const isReindented = (file: string, line: string) => { + const reindentInfo = (file: string) => { const ctx = ctxByPath.get(file) - if (!ctx?.newSql || !ctx.oldSql) return false + if (!ctx?.newSql) return undefined let r = reindentByFile.get(file) if (!r) { r = { removed: new Set(splitDiff(ctx.file.diff).removed.map(normalizeSelectLine).filter(Boolean)), head: selectItems(ctx.newSql), headLines: ctx.newSql.split("\n").map(normalizeSelectLine), - base: new Set(selectItems(ctx.oldSql).map(itemKey)), + base: new Set(ctx.oldSql ? selectItems(ctx.oldSql).map(itemKey) : []), } reindentByFile.set(file, r) } + return r + } + // Head select items spanning any head line equal to `line` (normalised). + const headItemsOnLine = (file: string, line: string) => { + const r = reindentInfo(file) const normalized = normalizeSelectLine(line) - if (!normalized || !r.removed.has(normalized)) return false + if (!r || !normalized) return [] const lineNos = r.headLines.flatMap((l, i) => (l === normalized ? [i + 1] : [])) - const items = r.head.filter((i) => lineNos.some((n) => i.startLine <= n && n <= i.endLine)) + return r.head.filter((i) => lineNos.some((n) => i.startLine <= n && n <= i.endLine)) + } + const isReindented = (file: string, line: string) => { + const r = reindentInfo(file) + if (!r || !ctxByPath.get(file)?.oldSql || !r.removed.has(normalizeSelectLine(line))) return false + const items = headItemsOnLine(file, line) return items.length > 0 && items.every((i) => r.base.has(itemKey(i))) } const merged = flat.filter((f) => { @@ -1548,12 +1566,12 @@ export async function runReview(input: OrchestrateInput): Promise isReindented(f.file, i.line) || isBaseExposed(f.file, i.column, i.alias))) return false + if (items.length && items.every((i) => isReindented(f.file, i.line) || isBaseExposed(f.file, i.column, i.alias, i.line))) return false // Otherwise suppress only when a precise detector actually EMITTED a PII // finding for the file (so the exposure is reported by the better source, // not silently dropped). diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 11122ca654..c0d6265399 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -164,12 +164,11 @@ export function selectItemColumns(line: string, tokenRe: RegExp): SelectItemColu const seen = new Set() // Literals are blanked first: their contents are neither column tokens nor // item separators (`email || ',' || phone_number as contact` is one item). - for (const item of topLevelItems(stripLiterals(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() + // Clause text (`from ssn_vault`, `where …`) is not a select list. + for (const item of topLevelItems(selectListText(stripLiterals(stripComments(line))))) { + // The alias as the select-list parser reads it: with or without `AS`, + // quoted (`as "Tax Ref"` → `tax ref`), after any parenthesised expression. + const alias = itemAlias(item) for (const m of item.matchAll(global)) { const column = m[1]?.toLowerCase() if (!column || seen.has(`${column} ${alias ?? ""}`)) continue @@ -205,6 +204,33 @@ const NOT_AN_ALIAS = new Set( const SELECT_LIST_END = /^(from|where|group|order|limit|qualify|having|union|intersect|except|minus|window|into|fetch|offset)\b/i +/** `line` with everything outside a select list blanked: from a clause keyword + * (`from`, `where`, …) at a query's own level up to the next `select`. A + * keyword inside a call (`extract(day from d)`) does not count. */ +function selectListText(line: string): string { + // Per open parenthesis: whether it opens a subquery, and the outer mode. + const stack: Array<{ query: boolean; listing: boolean }> = [] + let listing = true + let query = true + let out = "" + for (let i = 0; i < line.length; i++) { + const c = line[i] + if (c === "(") { + stack.push({ query, listing }) + query = /^\s*select\b/i.test(line.slice(i + 1, i + 40)) + if (query) listing = false + } else if (c === ")") { + const outer = stack.pop() + if (outer) ({ query, listing } = outer) + } else if (query && !isWordChar(line[i - 1])) { + if (/^select\b/i.test(line.slice(i, i + 7))) listing = true + else if (SELECT_LIST_END.test(line.slice(i, i + 10))) listing = false + } + out += listing || c === "(" || c === ")" ? c : c === "\n" ? c : " " + } + return out +} + const unquote = (s: string) => s.replace(/^["`]|["`]$/g, "").toLowerCase() /** Scope key of the model's outermost query. No identifier unquotes to it, so a @@ -295,14 +321,24 @@ function columnReads(expr: string): Array<{ qualifier?: string; column: string } return out } +/** A select item's expression and its alias (`AS` or implicit), if any. */ +function splitAlias(text: string): { expr: string; alias?: string } { + const explicit = EXPLICIT_ALIAS.exec(text) + if (explicit) return { expr: explicit[1], alias: explicit[2] } + const implicit = IMPLICIT_ALIAS.exec(text) + if (implicit && !NOT_AN_ALIAS.has(unquote(implicit[2]))) return { expr: implicit[1], alias: implicit[2] } + return { expr: text } +} + +/** A select item's output alias, unquoted and lowercased, when it has one. */ +function itemAlias(item: string): string | undefined { + const { alias } = splitAlias(normalizeItem(item)) + return alias ? unquote(alias) : undefined +} + function describeItem(raw: string): Pick { const text = normalizeItem(raw) - let expr = text - let alias: string | undefined - const explicit = EXPLICIT_ALIAS.exec(text) - const implicit = explicit ? null : IMPLICIT_ALIAS.exec(text) - if (explicit) [, expr, alias] = explicit - else if (implicit && !NOT_AN_ALIAS.has(unquote(implicit[2]))) [, expr, alias] = implicit + const { expr, alias } = splitAlias(text) const ref = RAW_COLUMN_EXPRS.map((re) => re.exec(expr)).find(Boolean) const rawColumn = ref ? unquote(ref[2]) : undefined const rawQualifier = ref?.[1] ? unquote(ref[1]) : undefined diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 2f09781447..002255758c 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -42,6 +42,19 @@ describe("selectItemColumns", () => { { column: "email", alias: undefined, line: "email, 'passport' as kind" }, ]) }) + test("reads the alias as the select-list parser does: implicit, quoted, after a call", () => { + expect(selectItemColumns("c.ssn tax_ref,", PII)).toEqual([{ column: "ssn", alias: "tax_ref", line: "c.ssn tax_ref," }]) + expect(selectItemColumns('c.ssn as "Tax Ref"', PII)).toEqual([{ column: "ssn", alias: "tax ref", line: 'c.ssn as "Tax Ref"' }]) + expect(selectItemColumns("cast(c.ssn as varchar) as tax_ref", PII)[0].alias).toBe("tax_ref") + expect(selectItemColumns("case when x then ssn end,", PII)[0].alias).toBeUndefined() + }) + test("collects no tokens from clause text after the select list", () => { + expect(selectItemColumns("email from ssn", PII)).toEqual([{ column: "email", alias: undefined, line: "email from ssn" }]) + expect(selectItemColumns("email from t where ssn is not null", PII).map((c) => c.column)).toEqual(["email"]) + // A keyword inside a call is not a clause; a later `select` resumes the list. + expect(selectItemColumns("extract(year from passport) as y", PII).map((c) => c.column)).toEqual(["passport"]) + expect(selectItemColumns("email from a union all select ssn from b", PII).map((c) => c.column)).toEqual(["email", "ssn"]) + }) test("does not split a select item on a comma inside a literal", () => { const line = "email || ',' || phone_number as contact" expect(selectItemColumns(line, PII)).toEqual([ diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index cd7b81c5ab..ec11b70e89 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2686,6 +2686,47 @@ describe("orchestrate", () => { } }) + test("a regex twin takes the output name from the parsed select item: next-line, implicit and quoted aliases", async () => { + const cases: Array<[string, string]> = [ + [" c.ssn\n as tax_ref", "tax_ref"], + [" c.ssn tax_ref", "tax_ref"], + [' c.ssn as "Tax Ref"', "Tax Ref"], + ] + for (const [item, output] of cases) { + // The output name is what the engine reports for the base and head. + const runner: ReviewRunner = { + ...piiRunner(["ssn"]), + detectPii: async (sql: string) => ({ columns: /ssn/.test(sql) ? [output] : [] }), + } + const base = `select c.customer_id,\n${item}\nfrom customers c` + const head = base.replace(/\bc\./g, "cust.").replace("customers c", "customers cust") + const diff = [ + "-select c.customer_id,", + `-${item.split("\n")[0]}`, + "-from customers c", + "+select cust.customer_id,", + `+${item.split("\n")[0].replace("c.", "cust.")}`, + "+from customers cust", + "", + ].join("\n") + for (const reviewers of [["pii_exposure"], [], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner, + getContent: content(head, base), + }) + expect({ item, reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ + item, + reviewers, + pii: [], + }) + } + } + }) + test("a PII line moved from a CTE into the final select is not a reindent", async () => { // ` email,` leaves the CTE and the same text lands in the final select: the // model's output now carries `email`, though the line matches a removed one. From 6f1682b682c10b250deff5e2b864211739a2dbbe Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:25:10 +0530 Subject: [PATCH 28/81] fix(review): keep local diagnostics whole, trust only the trailing finding marker, and tidy summary notes - Unverified-engine and AI-lane reasons were clipped to 200 characters even on uncapped local output (CLI, agent tool); they are now clipped only when the comment has a finite budget. - `postedFindingIds` accepted a marker anywhere in a bot comment, and those bodies can echo PR text, so a planted marker could suppress another finding's inline comment. Only the marker `inlineComments` appends at the end counts. - The grouping key is `JSON.stringify([...])` instead of a `|` join, which `r|x` + `y` and `r` + `x|y` could collide on. - The moved-files note no longer reads like a coverage gap, the overflow hint points at the job log and `altimate review --json --output ` (the action uploads no `--output` artifact), and the `bulletsFor` JSDoc sits on `bulletsFor`. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 4 +-- .../opencode/src/altimate/review/format.ts | 29 +++++++++------- .../test/altimate/review-noise.test.ts | 33 +++++++++++++++++++ 3 files changed, 53 insertions(+), 13 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index a1375cb2a2..0deabe0d59 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -290,8 +290,8 @@ rubric: - **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. + counted, and the full list is always in the job log and the verdict envelope + (`altimate review --json --output `). 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. diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index e5c695dd77..5a0fc8824f 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -155,8 +155,8 @@ export function renderSummary(env: VerdictEnvelope, opts: RenderOptions = {}): s .map((sev) => `${hidden[sev]} ${sev}`) .join(", ") lines.push( - `> … ${hiddenTotal} more finding(s) not shown (${bySeverity}) to keep this comment short — the full list is in the verdict envelope ` + - "(`altimate review --json`, or the action's `--output` artifact).", + `> … ${hiddenTotal} more finding(s) not shown (${bySeverity}) to keep this comment short — the full list is in the job log ` + + "and in the verdict envelope (`altimate review --json --output `).", "", ) } @@ -206,13 +206,13 @@ 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. */ // A budgeted bullet's body is clipped to this, so one long finding cannot fill // the comment and hide the titles of the most severe findings. const BULLET_BODY_MAX = 600 +/** 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 }> { // Budgeted (grouped) output clips bodies; local output keeps them whole. const bodyOf = (text: string) => (group ? clip(text, BULLET_BODY_MAX) : text) @@ -220,7 +220,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou 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 key = group ? JSON.stringify([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]) @@ -264,6 +264,8 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou */ export function coverageNotes(env: VerdictEnvelope, maxChars = Infinity): string[] { const notes: string[] = [] + // Diagnostic reasons are clipped only in a budgeted comment; local output is whole. + const reasonOf = (text: string) => (maxChars === Infinity ? text : clip(text, 200)) const undecided = env.findings.filter((f) => f.degraded).length if (undecided) notes.push(`${undecided} finding(s) could not be decided by the engine and are marked _unverified_.`) const unverified = env.scope?.unverified ?? [] @@ -272,7 +274,7 @@ export function coverageNotes(env: VerdictEnvelope, maxChars = Infinity): string const byReason = new Map() for (const u of unverified) byReason.set(u.reason, [...(byReason.get(u.reason) ?? []), u.path]) for (const [reason, paths] of byReason) { - const label = `${paths.length} model(s) not verified by the engine — ${clip(reason, 200)}` + const label = `${paths.length} model(s) not verified by the engine — ${reasonOf(reason)}` // Whole paths only: at most 5, and within an even share of the notes budget. const shown = takeWhole( paths.slice(0, 5).map((p) => `\`${p}\``), @@ -288,12 +290,12 @@ export function coverageNotes(env: VerdictEnvelope, maxChars = Infinity): string 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. ` + + `${env.scope.movedUnchangedFiles} file(s) moved without edits (no content changes to review). ` + "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 ? `: ${clip(env.ai.reason, 200)}` : ""}.`) + notes.push(`Advisory AI review ${what}${env.ai.reason ? `: ${reasonOf(env.ai.reason)}` : ""}.`) } // Whole notes within the budget; the rest are counted. const lines = takeWhole( @@ -320,10 +322,15 @@ export function findingMarker(id: string): string { return `` } -/** Finding ids already posted, read from existing inline comment bodies. */ +/** Finding ids already posted, read from existing inline comment bodies. Only + * the marker `inlineComments` appends at the very end counts: one inside the + * body can be echoed PR text (SQL or an AI finding quoting it). */ 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]) + for (const b of bodies) { + const m = /\s*$/.exec(b ?? "") + if (m) out.add(m[1]) + } return out } diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 06fff8e927..ee3ed11f12 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -141,6 +141,14 @@ describe("inline dedup across pushes", () => { expect(inlineComments(env, posted).map((c) => c.line)).toEqual([4]) }) + test("only the trailing marker of a bot comment counts, not one echoed inside its body", () => { + const a = finding({ startLine: 3, title: "m: a" }) + const b = finding({ startLine: 4, title: "m: b" }) + // `b`'s body quotes PR text that carries `a`'s marker; only `b`'s trailing marker counts. + const echoed = `🛑 **m: b**\n\nThe SQL reads \`${findingMarker(a.id)}\` here.\n\n${findingMarker(b.id)}\n` + expect([...postedFindingIds([echoed])]).toEqual([b.id]) + }) + 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") @@ -317,6 +325,31 @@ describe("summary grouping and budget", () => { ) }) + test("diagnostic reasons are clipped in the posted comment but whole in local output", () => { + const reason = `compile failed: ${"Database Error in model m (models/m.sql) ".repeat(8)}END` + const env = buildEnvelope({ + findings: [], + tier: "lite", + mode: "comment", + scope: { unverified: [{ path: "models/m.sql", reason }] } as any, + ai: { state: "error", reason: `ai lane: ${"timeout talking to provider ".repeat(10)}END` } as any, + }) + const local = renderSummary(env, { maxChars: Infinity }) + expect(local).toContain(reason) + expect(local).toContain("provider END") + const posted = renderSummary(env) + expect(posted).not.toContain(reason) + expect(posted).not.toContain("provider END") + }) + + test("the grouping key cannot be forged by a `|` in a title or body", () => { + const make = (models: string[], title: string, body: string) => + models.map((m) => finding({ model: m, file: `models/${m}.sql`, title: `${m}: ${title}`, body })) + const fs = [...make(["a", "b", "c"], "r|x", "y"), ...make(["d", "e", "f"], "r", "x|y")] + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md.match(/3 findings across 3 model\(s\)/g)?.length).toBe(2) + }) + test("the metadata is budgeted too: a run with no findings and huge metadata stays within budget", () => { const long = (tag: string, i: number) => `models/${"deeply/nested/".repeat(8)}${tag}_${i}.sql` const env = buildEnvelope({ From 5d80f3d8c91f985a8c017a110fd4beb5c309ce04 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:25:22 +0530 Subject: [PATCH 29/81] fix(review): show each member's own values in a grouped bullet, and group file-titled findings - Grouping blanks every backticked value, so three different unsupported functions, or a second column on one model, rendered as one bullet with the values gone. When members differ by more than their model, the bullet now lists each member's backticked values next to its model. - The grouping title stripped only a leading `model: `, so findings titled by their file (`schema.yml: unique test removed from orders.id`) never grouped. A leading file name or basename is stripped too, and the model named as a whole word mid-title is blanked. - Docs describe grouping as the same rule and message ignoring model and column names. The `a grouped body that names one model's column` test now expects each column attributed to its own model instead of no column name at all. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 7 ++-- .../opencode/src/altimate/review/format.ts | 38 +++++++++++++++--- .../test/altimate/review-noise.test.ts | 39 ++++++++++++++++++- 3 files changed, 75 insertions(+), 9 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 0deabe0d59..28ce2cdfb4 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -292,9 +292,10 @@ rubric: 5,000 characters. Critical findings come first; anything that does not fit is counted, and the full list is always in the job log and the verdict envelope (`altimate review --json --output `). 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. +- **Repeated findings are grouped:** the same rule and message (ignoring model + and column names) on three or more models is one bullet listing the models, + with each model's own names when they differ. 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 diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 5a0fc8824f..f6b4cb9ec9 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -200,10 +200,24 @@ 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. */ +/** A finding's title without its leading `model: ` or `file: `, with its model + * name and 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) + const prefixes = [f.model, f.file, f.file.split("/").pop()].filter((p): p is string => !!p) + const lead = prefixes.find((p) => f.title.startsWith(`${p}: `)) + let title = lead ? f.title.slice(lead.length + 2) : f.title + // `Model orders modified — …`: the model named mid-title, as a whole word. + if (f.model) + title = title.replace(new RegExp(`(? m[1]).filter((v) => !own.has(v)) + return [...new Set(values)] } // A budgeted bullet's body is clipped to this, so one long finding cannot fill @@ -235,12 +249,26 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou 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 = bodyOf(g.every((f) => f.body === g[0].body) ? oneLine(g[0].body) : blankNames(oneLine(g[0].body))) + const same = g.every((f) => f.body === g[0].body) + const body = bodyOf(same ? oneLine(g[0].body) : blankNames(oneLine(g[0].body))) + // Members that differ by more than their model (another function, a second + // column on one model): list each member's own values. + const values = g.map((f) => ({ f, v: distinguishingValues(f) })) + const differ = values.some(({ v }) => v.join("\u0000") !== values[0].v.join("\u0000")) + const detail = + differ && values.some(({ v }) => v.length) + ? ` ${bodyOf( + values + .slice(0, 8) + .map(({ f, v }) => `\`${f.model ?? f.file}\`: ${v.map((x) => `\`${x}\``).join(", ") || "—"}`) + .join(" · ") + (values.length > 8 ? ` (+${values.length - 8} more)` : ""), + )} \n` + : "" 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}`, + ` ${body} \n${detail} ${g[0].category}${unverified}`, count: g.length, }) continue diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index ee3ed11f12..2878cfa146 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -233,7 +233,44 @@ describe("summary grouping and budget", () => { 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`") + // Each column is attributed to its own model, never shown as everyone's. + expect(md).not.toContain("Column `a_id`") + expect(md).toContain("`a`: `a_id` · `b`: `b_id` · `c`: `c_id`") + }) + + test("a group whose members differ by more than the model lists each member's values", () => { + const fs = [ + ["a", "ILIKE"], + ["b", "QUALIFY"], + ["c", "IFF"], + ["c", "NVL2"], + ].map(([m, fn]) => + finding({ + severity: "warning", + category: "sql_quality", + model: m, + file: `models/${m}.sql`, + title: `${m}: unsupported function`, + body: `Function \`${fn}\` is unsupported on the target dialect.`, + }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).toContain("4 findings across 3 model(s)") + expect(md).toContain("`a`: `ILIKE` · `b`: `QUALIFY` · `c`: `IFF` · `c`: `NVL2`") + }) + + test("findings titled by their file group like findings titled by their model", () => { + const fs = ["a", "b", "c"].map((m) => + finding({ + model: m, + file: `models/${m}/schema.yml`, + // The removed-test shape: file prefix, model named unquoted mid-title. + title: `schema.yml: unique test removed from ${m}.id`, + category: "test_coverage", + }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + expect(md).toContain("3 findings across 3 model(s)") }) test("more than eight models: the posted comment lists eight, local output lists every finding", () => { From bfb900c7a028b0d9cfb185645145b28de6243a09 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:28:00 +0530 Subject: [PATCH 30/81] fix(review): report a partial inline post, record a failed retry, and skip files the PR does not list - A successful verified-only retry still left `inlineFellBack` true, so the CLI said inline comments fell back to summary-only after some were posted. `PostResult.inlineDropped` now counts the comments that retry dropped; the CLI prints it and telemetry counts it as a partial post. - The retry's bare `catch {}` swallowed a non-positioning failure (a 5xx); it is now recorded in `postError` even when the event-only review then succeeds, and the CLI says the review was posted without its inline comments rather than that the review event failed. - The file map keeps every listed file (`undefined` lines for a patchless one), so a path GitHub did not list is skipped instead of attempted, and the verified-only retry keeps only files with a known patch. - Inline comments are built once; already-posted ones are filtered from that list to count `inlineSkippedAsPosted`. - The test Octokit mock now pages its list results and `paginate` walks the pages; markers, reviews, files and the prior summary on page two are found. The `a positioning 422 with a patchless file retries with the verified comments first` test now expects `inlineFellBack: false, inlineDropped: 1` for the successful verified-only retry. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 28 +++-- .../src/altimate/review/post-github.ts | 59 +++++---- .../opencode/src/altimate/review/telemetry.ts | 2 +- packages/opencode/src/cli/cmd/review.ts | 7 +- .../test/altimate/review-noise.test.ts | 113 ++++++++++++++++-- 5 files changed, 164 insertions(+), 45 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index f6b4cb9ec9..b387ae91d3 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -388,25 +388,27 @@ export function commentableLines(diff: string | undefined): Set { } /** - * 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. + * Inline comments for findings with a line. With `commentable` (every file the + * PR lists, mapped to its head-side commentable lines, 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 listed with `undefined` lines has + * unknown hunks (GitHub omits the patch for large diffs): its lines are + * attempted, and the 422 fallback covers a miss. A file the PR does not list + * gets no inline comment. The finding keeps its line in the envelope and summary. */ export function inlineComments( env: VerdictEnvelope, alreadyPosted: Set = new Set(), - commentable?: Map>, + commentable?: Map | undefined>, ): InlineComment[] { + const onDiff = (file: string, line: number) => { + if (!commentable) return true + if (!commentable.has(file)) return false + const lines = commentable.get(file) + return !lines || lines.has(line) + } return env.findings - .filter( - (f) => - typeof f.startLine === "number" && - !alreadyPosted.has(f.id) && - (!commentable?.has(f.file) || commentable.get(f.file)!.has(f.startLine)), - ) + .filter((f) => typeof f.startLine === "number" && !alreadyPosted.has(f.id) && onDiff(f.file, f.startLine)) .map((f) => ({ path: f.file, line: f.startLine!, diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index a7bfbf2316..96332d7792 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -57,8 +57,12 @@ export async function resolveGitHubTarget(): Promise { export interface PostResult { summaryCommentId?: number reviewId?: number - /** True when some or all inline comments were dropped due to a 422 positioning error. */ + /** True when every inline comment was dropped after a 422 positioning error + * (the review was posted without them). */ inlineFellBack: boolean + /** Inline comments dropped after a positioning 422 when the retry with only + * the comments on files with a known patch succeeded. */ + inlineDropped?: number /** 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. */ @@ -69,6 +73,19 @@ export interface PostResult { reviewSkipped?: boolean } +/** Only a 422 that is actually about line POSITIONING justifies silently + * dropping inline comments. A generic 422 (and any other status) is a real + * error and must be reported, not masqueraded as "lines outside diff". */ +function isPositioningError(e: any): boolean { + const status = e?.status ?? e?.response?.status + const detail = `${e?.message ?? ""} ${JSON.stringify(e?.response?.data?.errors ?? e?.errors ?? "")}`.toLowerCase() + return status === 422 && /(position|\bline\b|diff|commit)/.test(detail) +} + +function describeError(e: any): string { + return `${e?.status ?? e?.response?.status ?? ""} ${e?.message ?? e}`.trim() +} + /** Headline of a review this bot posted (see verdictHeadline). */ const BOT_REVIEW_RE = /(Approved|Reviewed with comments|Changes requested)\b.*\((trivial|lite|full) tier/ @@ -126,20 +143,21 @@ export async function postGitHubReview( /* 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 + // Inline comments only on lines GitHub accepts (inside the PR's diff hunks), + // and only on files the PR lists. 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> | 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)])) + commentable = new Map(files.map((f) => [f.filename, f.patch ? commentableLines(f.patch) : undefined])) } catch { /* fall back to the positioning retry below */ } - const comments = inlineComments(env, posted, commentable) - // Both calls use the same `commentable`, so the difference is exactly the - // comments skipped because this bot already posted them. - result.inlineSkippedAsPosted = inlineComments(env, new Set(), commentable).length - comments.length + // One pass: the eligible comments, less those this bot already posted. + const eligible = inlineComments(env, new Set(), commentable) + const comments = eligible.filter((c) => ![...postedFindingIds([c.body])].some((id) => posted.has(id))) + result.inlineSkippedAsPosted = eligible.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 @@ -176,18 +194,13 @@ export async function postGitHubReview( // inline comments — anchoring outside the diff hunk. Other errors (auth, // can't-approve-own-PR, 5xx) should NOT masquerade as "lines outside diff", // so we still retry event-only but record the real reason. - const status = e?.status ?? e?.response?.status - // Only a 422 that is actually about line POSITIONING justifies silently - // dropping inline comments. A generic 422 (and any other status) is a real - // error and must be reported, not masqueraded as "lines outside diff". - const detail = `${e?.message ?? ""} ${JSON.stringify(e?.response?.data?.errors ?? e?.errors ?? "")}`.toLowerCase() - const isPositioning = status === 422 && /(position|\bline\b|diff|commit)/.test(detail) + const isPositioning = isPositioningError(e) result.inlineFellBack = isPositioning - result.postError = isPositioning ? undefined : `${status ?? ""} ${e?.message ?? e}`.trim() + result.postError = isPositioning ? undefined : describeError(e) // 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)) : [] + const verified = isPositioning && commentable ? comments.filter((c) => commentable!.get(c.path)) : [] if (verified.length && verified.length < comments.length) { try { const r = await octo.rest.pulls.createReview({ @@ -200,9 +213,13 @@ export async function postGitHubReview( comments: verified, }) result.reviewId = r.data.id + result.inlineFellBack = false + result.inlineDropped = comments.length - verified.length return result - } catch { - /* fall through to the event-only review */ + } catch (e3: any) { + // Another positioning 422 falls through to the event-only review; any + // other failure is recorded even if that review then succeeds. + if (!isPositioningError(e3)) result.postError = describeError(e3) } } try { @@ -217,7 +234,7 @@ export async function postGitHubReview( result.reviewId = r.data.id } catch (e2: any) { // Summary comment already landed; don't fail CI on a review-post error. - result.postError = `${e2?.status ?? ""} ${e2?.message ?? e2}`.trim() + result.postError = describeError(e2) } } return result diff --git a/packages/opencode/src/altimate/review/telemetry.ts b/packages/opencode/src/altimate/review/telemetry.ts index 3fbe4af1bb..b69fc237d8 100644 --- a/packages/opencode/src/altimate/review/telemetry.ts +++ b/packages/opencode/src/altimate/review/telemetry.ts @@ -71,7 +71,7 @@ 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) return "partial" + if (result.inlineFellBack || result.inlineDropped || result.postError) return "partial" if (result.reviewId === undefined && !result.reviewSkipped) return "partial" return "full" } diff --git a/packages/opencode/src/cli/cmd/review.ts b/packages/opencode/src/cli/cmd/review.ts index cef6942c20..b387a387a0 100644 --- a/packages/opencode/src/cli/cmd/review.ts +++ b/packages/opencode/src/cli/cmd/review.ts @@ -188,11 +188,16 @@ export const ReviewCommand = cmd({ emitPostOnce(classifyPostOutcome(r), postDuration()) const where = `${target.owner}/${target.repo}#${target.prNumber}` if (r.postError) { - UI.println(`⚠️ Posted the summary comment to ${where}, but the review event failed: ${r.postError}`) + UI.println( + r.reviewId !== undefined + ? `⚠️ Posted the review to ${where} without its inline comments: ${r.postError}` + : `⚠️ Posted the summary comment to ${where}, but the review event failed: ${r.postError}`, + ) } else { UI.println( `Posted review to ${where}` + (r.inlineFellBack ? " (inline comments fell back to summary-only)" : "") + + (r.inlineDropped ? ` (${r.inlineDropped} inline comment(s) dropped: lines outside the diff)` : "") + (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 index 2878cfa146..baaa60d76a 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -14,6 +14,7 @@ import { inlineComments, postedFindingIds, renderSummary, + REVIEW_MARKER, SUMMARY_BUDGET_CHARS, } from "../../src/altimate/review/format" import { buildEnvelope } from "../../src/altimate/review/verdict" @@ -560,25 +561,47 @@ describe("postGitHubReview", () => { listFails?: boolean files?: Array<{ filename: string; patch?: string }> reviewComments?: Array<{ body: string; user?: { login: string } }> + issueComments?: Array<{ id: number; body: string }> createReview?: (call: number) => unknown } = {}, ) { const reviewCalls: any[] = [] + const summaryCalls: string[] = [] const fail = async () => { throw new Error("listing failed") } + // GitHub lists in pages: each list call returns one page of PAGE items, and + // `paginate` walks the pages, so anything read without it sees page one only. + const PAGE = 2 + const paged = + (items: T[]) => + async (p: { page?: number }) => + items.slice(((p?.page ?? 1) - 1) * PAGE, (p?.page ?? 1) * PAGE) const octo = { - paginate: async (fn: (p: unknown) => unknown, p: unknown) => fn(p), + paginate: async (fn: (p: unknown) => Promise, p: Record) => { + const all: unknown[] = [] + for (let page = 1; ; page++) { + const items = await fn({ ...p, page }) + all.push(...items) + if (items.length < PAGE) return all + } + }, rest: { issues: { - listComments: async () => [], - createComment: async () => ({ data: { id: 1, user: { login: BOT } } }), - updateComment: async () => ({ data: { id: 1, user: { login: BOT } } }), + listComments: paged(opts.issueComments ?? []), + createComment: async () => { + summaryCalls.push("create") + return { data: { id: 1, user: { login: BOT } } } + }, + updateComment: async (p: { comment_id: number }) => { + summaryCalls.push(`update ${p.comment_id}`) + return { data: { id: p.comment_id, user: { login: BOT } } } + }, }, pulls: { - listReviewComments: opts.listFails ? fail : async () => opts.reviewComments ?? [], - listReviews: opts.listFails ? fail : async () => opts.reviews ?? [], - listFiles: opts.listFails ? fail : async () => opts.files ?? [{ filename: "models/m.sql", patch: PATCH }], + listReviewComments: opts.listFails ? fail : paged(opts.reviewComments ?? []), + listReviews: opts.listFails ? fail : paged(opts.reviews ?? []), + listFiles: opts.listFails ? fail : paged(opts.files ?? [{ filename: "models/m.sql", patch: PATCH }]), get: async () => ({ data: { head: { sha: "abc" } } }), createReview: async (p: any) => { reviewCalls.push(p) @@ -588,11 +611,80 @@ describe("postGitHubReview", () => { }, }, } - return { octo: octo as any, reviewCalls } + return { octo: octo as any, reviewCalls, summaryCalls } } const noLine = buildEnvelope({ findings: [finding()], tier: "lite", mode: "comment" }) + test("markers, reviews, files and the prior summary are read from every page", async () => { + const env = buildEnvelope({ + findings: [finding({ startLine: 3, title: "m: a" }), finding({ file: "models/late.sql", startLine: 5, title: "late: b" })], + tier: "lite", + mode: "comment", + }) + const [first] = inlineComments(env, new Set(), undefined) + const filler = (n: number) => Array.from({ length: n }, (_, i) => ({ body: `other ${i}`, user: { login: "someone" } })) + const { octo, reviewCalls, summaryCalls } = fakeOcto({ + // Each item that matters is on page two or later. + issueComments: [...filler(3).map((c, i) => ({ id: 100 + i, body: c.body })), { id: 42, body: `${REVIEW_MARKER}\nold` }], + reviewComments: [...filler(3), { body: first.body, user: { login: BOT } }], + files: [ + { filename: "models/x.sql", patch: PATCH }, + { filename: "models/y.sql", patch: PATCH }, + { filename: "models/m.sql", patch: PATCH }, + { filename: "models/late.sql", patch: PATCH }, + ], + }) + const r = await postGitHubReview(env, target, octo) + expect(summaryCalls).toEqual(["update 42"]) + expect(r.inlineSkippedAsPosted).toBe(1) + expect(reviewCalls[0].comments.map((c: { path: string; line: number }) => `${c.path}:${c.line}`)).toEqual(["models/late.sql:5"]) + // This bot's latest review on page two carries the same headline: no new review. + const quiet = buildEnvelope({ findings: [finding()], tier: "lite", mode: "comment" }) + const again = fakeOcto({ reviews: [...filler(2), { body: verdictHeadline(quiet), user: { login: BOT } }] }) + expect((await postGitHubReview(quiet, target, again.octo)).reviewSkipped).toBe(true) + }) + + test("a file the PR does not list gets no inline comment once the file list is known", async () => { + const env = buildEnvelope({ + findings: [finding({ startLine: 3, title: "m: a" }), finding({ file: "models/unlisted.sql", startLine: 3, title: "u: b" })], + tier: "lite", + mode: "comment", + }) + const { octo, reviewCalls } = fakeOcto() + await postGitHubReview(env, target, octo) + expect(reviewCalls[0].comments.map((c: { path: string }) => c.path)).toEqual(["models/m.sql"]) + }) + + test("a non-positioning failure of the verified-only retry is recorded", 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 { octo, reviewCalls } = fakeOcto({ + files: [{ filename: "models/known.sql", patch: PATCH }, { filename: "models/big.sql" }], + createReview: (call) => { + if (call === 1) + throw Object.assign(new Error("Unprocessable Entity"), { + status: 422, + response: { data: { errors: ["Line could not be resolved"] } }, + }) + if (call === 2) throw Object.assign(new Error("Server Error"), { status: 502 }) + return undefined + }, + }) + const r = await postGitHubReview(env, target, octo) + expect(reviewCalls.length).toBe(3) + expect(reviewCalls[2].comments).toBeUndefined() + expect(r.reviewId).toBe(9) + expect(r.inlineFellBack).toBe(true) + expect(r.postError).toBe("502 Server Error") + }) + test("skips a new review when this bot's latest review has the same headline", async () => { const { octo, reviewCalls } = fakeOcto({ reviews: [ @@ -752,7 +844,10 @@ describe("postGitHubReview", () => { }) 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) + // Some inline comments were posted: a partial drop, not a summary-only fallback. + expect(r.inlineFellBack).toBe(false) + expect(r.inlineDropped).toBe(1) + expect(classifyPostOutcome(r)).toBe("partial") expect(r.postError).toBeUndefined() expect(r.reviewId).toBe(9) From f80483230b62e3c5bf46f971d4351baa35ecfddf Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:29:15 +0530 Subject: [PATCH 31/81] test(review): make the PII classifier stub column-specific, and drive a moved-only run through `runReview` - The no-compiled-base PII test's `classifyPii` stub classified every column (including `customer_id`) as Email and asserted only a non-empty result. It now classifies only `email` and asserts a finding names `email` and none names `customer_id`. - The moved-files test built the envelope by hand, so the "not a lint-only run" claim was never exercised. A new test scopes a moved-only change with `scopeToProject` and runs it through `runReview` with no manifest; it fails if `runDegraded` goes back to `!anyManifest`. Co-Authored-By: Claude Opus 5.5 --- .../test/altimate/review-noise.test.ts | 38 +++++++++++++++++++ .../opencode/test/altimate/review.test.ts | 6 ++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index baaa60d76a..4247e0a874 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -23,6 +23,7 @@ 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" +import { scopeToProject } from "../../src/altimate/review/diff-filter" /** * The PR comment must stay readable: inline comments land on real lines of the @@ -548,6 +549,43 @@ describe("moved files", () => { expect(renderSummary(env)).toContain("3 file(s) moved without edits") expect(renderSummary(env)).toContain("`+schema`") }) + + test("a run of only unchanged moves, through runReview without a manifest, is not lint-only", async () => { + const scoped = scopeToProject( + [ + { + path: "models/staging/b/schema.yml", + oldPath: "models/staging/a/schema.yml", + status: "renamed", + similarity: 100, + diff: "", + }, + ], + undefined, + ) + expect(scoped).toMatchObject({ inScope: [], movedUnchanged: 1 }) + const runner = { + async impact() { + return { hasManifest: false, severity: "SAFE", directCount: 0, transitiveCount: 0, testCount: 0 } + }, + async detectPii() { + return { columns: [] } + }, + } as unknown as ReviewRunner + const env = await runReview({ + changedFiles: scoped.inScope, + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "comment", + runner, + getContent: async () => undefined, + scope: { movedUnchangedFiles: scoped.movedUnchanged }, + }) + expect(env.summary.degraded).toBe(false) + const md = renderSummary(env) + expect(md).toContain("1 file(s) moved without edits") + expect(md).not.toContain("Lint-only") + }) }) describe("postGitHubReview", () => { diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index ec11b70e89..298a3b759f 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2141,7 +2141,8 @@ describe("orchestrate", () => { ] }, async classifyPii(columns) { - return columns.map((column) => ({ column, classification: "Email", confidence: 0.95 })) + // Column-specific, like the real classifier: only `email` is PII. + return columns.filter((c) => c === "email").map((column) => ({ column, classification: "Email", confidence: 0.95 })) }, } const env = await runReview({ @@ -2158,6 +2159,9 @@ describe("orchestrate", () => { }) const pii = env.findings.filter((f) => f.category === "pii_exposure") expect(pii.length).toBeGreaterThan(0) + // The finding names `email`, and nothing flags `customer_id`. + expect(pii.some((f) => f.column === "email" || /\bemail\b/.test(f.title))).toBe(true) + expect(pii.some((f) => f.column === "customer_id" || /customer_id/.test(f.title))).toBe(false) expect(pii.every((f) => f.severity !== "critical")).toBe(true) expect(env.verdict).not.toBe("REQUEST_CHANGES") }) From db76ec16aa136e3b10eab09f3b586f692a54c689 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:29:42 +0530 Subject: [PATCH 32/81] fix(review): drop FETCH FIRST portability advice on DuckDB DuckDB accepts `FETCH FIRST n ROWS ONLY` (checked with the DuckDB CLI), so `fetch-first` now lists `duckdb` in `worksOn` and the advice is suppressed on DuckDB projects. It is still kept on BigQuery. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/rule-catalog.ts | 2 +- packages/opencode/test/altimate/review-noise.test.ts | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index c0d6265399..4ffaf75c57 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -2602,7 +2602,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, portability: { worksOn: ["postgres", "snowflake", "oracle", "trino"] } }, + { added: /fetch\s+first\s+\d+/i, portability: { worksOn: ["postgres", "snowflake", "oracle", "trino", "duckdb"] } }, { add: "fetch first 10 rows only" }, { add: "limit 10" }, ), diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 4247e0a874..7c98e78f4a 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -535,6 +535,10 @@ describe("portability noise", () => { for (const ansi of ["select d - interval '30' day as d30 from t", "select d + interval '12' month as d12 from t"]) for (const dialect of ["trino", "athena", "bigquery", "oracle", "mysql"]) expect(await rules(ansi, dialect)).not.toContain("interval-string-literal") + // DuckDB accepts `FETCH FIRST n ROWS ONLY`; BigQuery does not. + const fetchFirst = "select id from t order by id fetch first 10 rows only" + expect(await rules(fetchFirst, "duckdb")).not.toContain("fetch-first") + expect(await rules(fetchFirst, "bigquery")).toContain("fetch-first") }) }) From c9e33bdf29f1b6343b839bcc2415429b8e1ed410 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:32:11 +0530 Subject: [PATCH 33/81] fix(review): resolve raw and computed refs in one memoised walk, without copying the scope chain per step Resolving every output's `reads` doubled the per-column walk through `*` chains, and each step copied the visited-scope set. `resolveRef` now returns raw and computed refs together, memoises per scope, branch, qualifier and column, and reuses one visited set per (parent, scope) pair. A 3,000-column select over a 300-deep `select x.*` CTE chain resolves in about 0.7 s, down from 2.9 s at the start of this round and 7.6 s with `reads` unmemoised. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/rule-catalog.ts | 64 +++++++++++++------ 1 file changed, 44 insertions(+), 20 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 4ffaf75c57..542ea08f70 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -674,48 +674,71 @@ export function finalOutputs(sql: string): FinalOutputs { return out } const memo = new Map() + const refMemo = new Map; reads: Set }>() + // `seen` plus `scope`, built once per pair: the same chain is walked for every + // column, so copying `seen` on each step would make a deep chain quadratic. + const innerSets = new WeakMap, Map>>() + const innerOf = (seen: Set, scope: string) => { + let perScope = innerSets.get(seen) + if (!perScope) innerSets.set(seen, (perScope = new Map())) + let inner = perScope.get(scope) + if (!inner) perScope.set(scope, (inner = new Set([...seen, scope]))) + return inner + } const isDerived = (src: Source, scope: string, seen: Set) => src.name !== scope && byScope.has(src.name) && !seen.has(src.name) // The `source.column` refs a column read in `scope#branch` resolves to: those - // it exposes raw (`key: "raw"`; a column a CTE computes is none), or every one - // its value is computed from (`key: "reads"`). - const resolveRef = ( + // it exposes raw (`raw`; a column a CTE computes is none), and every one its + // value is computed from (`reads`). + type Refs = { raw: Set; reads: Set } + const same = (set: Set): Refs => ({ raw: set, reads: set }) + const unionRefs = (list: Refs[]): Refs => ({ raw: union(list.map((r) => r.raw)), reads: union(list.map((r) => r.reads)) }) + const resolveRef = (scope: string, branch: number, qualifier: string | undefined, col: string, seen: Set): Refs => { + // Memoised like `resolve`: a wide select over a deep `*` chain would + // otherwise walk the chain once per column reference. + const memoKey = `${scope}#${branch}\u0000${qualifier ?? ""}\u0000${col}` + const hit = refMemo.get(memoKey) + if (hit) return hit + const out = resolveRefUncached(scope, branch, qualifier, col, seen) + refMemo.set(memoKey, out) + return out + } + const resolveRefUncached = ( scope: string, branch: number, qualifier: string | undefined, col: string, seen: Set, - key: "raw" | "reads" = "raw", - ): Set => { + ): Refs => { const srcs = sources.get(`${scope}#${branch}`) ?? [] - const inner = new Set([...seen, scope]) - const fromSource = (src: Source): Set => { - if (!isDerived(src, scope, seen)) return byScope.has(src.name) ? unresolved(col) : new Set([`${src.name}.${col}`]) + const inner = innerOf(seen, scope) + const fromSource = (src: Source): Refs => { + if (!isDerived(src, scope, seen)) return same(byScope.has(src.name) ? unresolved(col) : new Set([`${src.name}.${col}`])) const out = resolve(src.name, inner) - if (out.names.has(col)) return out[key].get(col) ?? new Set() - if (out.stars.length) return union(out.stars.map((st) => resolveRef(src.name, st.branch, st.qualifier, col, inner, key))) - return unresolved(col) + if (out.names.has(col)) return { raw: out.raw.get(col) ?? new Set(), reads: out.reads.get(col) ?? new Set() } + if (out.stars.length) return unionRefs(out.stars.map((st) => resolveRef(src.name, st.branch, st.qualifier, col, inner))) + 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) - return src ? fromSource(src) : unresolved(col) + return src ? fromSource(src) : same(unresolved(col)) } const named = srcs.filter((x) => isDerived(x, scope, seen) && resolve(x.name, inner).names.has(col)) - if (named.length) return union(named.map(fromSource)) + if (named.length) return unionRefs(named.map(fromSource)) const open = srcs.filter((x) => isDerived(x, scope, seen) ? resolve(x.name, inner).stars.length > 0 : !byScope.has(x.name), ) if (open.length === 1) return fromSource(open[0]) - if (open.length > 1) return new Set([`${[...new Set(open.map((x) => x.name))].sort().join("|")}.${col}`]) - return unresolved(col) + if (open.length > 1) return same(new Set([`${[...new Set(open.map((x) => x.name))].sort().join("|")}.${col}`])) + return same(unresolved(col)) } const resolve = (scope: string, seen: Set): ScopeOutputs => { const cached = memo.get(scope) if (cached) return cached - const inner = new Set([...seen, scope]) + const inner = innerOf(seen, scope) const raw = new Map>() const names = new Set() const signatures = new Map>() @@ -752,11 +775,12 @@ export function finalOutputs(sql: string): FinalOutputs { names.add(name) addTo(signatures, name, [`${item.exact.toLowerCase()}\u0001${bodies.join("\u0002")}`]) if (item.rawColumn) { - addTo(raw, name, resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen)) - addTo(reads, name, resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen, "reads")) + 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")) + for (const r of item.reads ?? []) addTo(reads, name, resolveRef(scope, item.branch, r.qualifier, r.column, seen).reads) } } for (const [n, cols] of raw) if (!cols.size) raw.delete(n) @@ -767,7 +791,7 @@ export function finalOutputs(sql: string): FinalOutputs { } const { raw, names, signatures, reads, stars } = resolve(ROOT_SCOPE, new Set()) const starRaw = (column: string) => - union(stars.map((st) => resolveRef(ROOT_SCOPE, st.branch, st.qualifier, column, new Set()))) + union(stars.map((st) => resolveRef(ROOT_SCOPE, st.branch, st.qualifier, column, new Set()).raw)) return { raw, names, signatures, reads, passthrough: stars.length > 0, starRaw } } From e7ac0a6e0f0eabd60baa8e7d493bbf22a6f3cda5 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:32:58 +0530 Subject: [PATCH 34/81] fix(review): keep `starRaw` off the per-scope output type `starRaw` exists only on the model's final output; `ScopeOutputs` now omits it, which `tsgo --noEmit` requires. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/rule-catalog.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 542ea08f70..c3bcbe1b6f 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -601,7 +601,7 @@ export interface FinalOutputs { reads: Map> } -interface ScopeOutputs extends Omit { +interface ScopeOutputs extends Omit { /** `*` items, whose columns pass through unnamed (`select * from customers`). */ stars: Array<{ branch: number; qualifier?: string }> /** Every item's text, and that of every scope it reads. */ From fa217444869899db1a87995a1e61f591792aa6d3 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:50:47 +0530 Subject: [PATCH 35/81] fix(review): cover a combined join ref by a single-table base ref, never the reverse `refCovered` also accepted a single-table head ref when the base had a combined ref (`customers|spouses.ssn`), so base `ssn` over a join -> head `s.ssn` was quiet. The base never said which table it read, so only the forward direction (head combined, base single member) is kept. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/rule-catalog.ts | 9 +++++---- .../opencode/test/altimate/review-rule-catalog.test.ts | 3 ++- packages/opencode/test/altimate/review.test.ts | 7 +++++++ 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index c3bcbe1b6f..9c930ac64d 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -640,9 +640,11 @@ const splitRef = (ref: string) => { /** * `ref` is one of the `exposed` source columns. An unqualified column read over * several tables (`customers|orders.email`, see `rawColumnExposures`) comes from - * exactly one of them (the query would be ambiguous otherwise), so it matches a - * single-table ref to one of its members, and the reverse. Two combined refs - * match only when equal. + * exactly one of them (the query would be ambiguous otherwise), so it is + * covered by a single-table ref to one of its members. The reverse is not: a + * base combined ref does not say which table the column came from, so a head + * read pinned to one of them (`s.ssn`) may be new. Two combined refs match only + * when equal. */ export function refCovered(ref: string, exposed: Set): boolean { if (exposed.has(ref)) return true @@ -651,7 +653,6 @@ export function refCovered(ref: string, exposed: Set): boolean { const x = splitRef(e) if (x.column !== r.column) continue if (r.tables.length > 1 && x.tables.length === 1 && r.tables.includes(x.tables[0])) return true - if (r.tables.length === 1 && x.tables.length > 1 && x.tables.includes(r.tables[0])) return true } return false } diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 002255758c..822db3a16e 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -185,7 +185,8 @@ describe("rawColumnExposures", () => { }) test("`refCovered` matches an unqualified column over a join to its single-table ref", () => { expect(refCovered("customers|orders.email", new Set(["customers.email"]))).toBe(true) - expect(refCovered("customers.email", new Set(["customers|orders.email"]))).toBe(true) + // The reverse is not covered: the base never said which table it read. + expect(refCovered("customers.email", new Set(["customers|orders.email"]))).toBe(false) expect(refCovered("customers|orders.email", new Set(["spouses.email"]))).toBe(false) expect(refCovered("customers|orders.email", new Set(["customers.ssn"]))).toBe(false) expect(refCovered("a|b.email", new Set(["b|c.email"]))).toBe(false) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 298a3b759f..d5ba869fa2 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2549,6 +2549,13 @@ describe("orchestrate", () => { expect(broad.map((f) => (f.evidence?.result as any)?.columns)).toEqual([["email", "ssn"], ["email", "ssn"], ["email", "ssn"]]) }) + test("a head column pinned to one table is new when the base read it unqualified over a join", async () => { + // Base `ssn` over customers ⋈ spouses does not say which table it came from. + const base = "select customer_id,\n ssn\nfrom customers c\njoin spouses s using (customer_id)" + const head = base.replace(" ssn\n", " s.ssn\n") + expectReportedPii(await piiRuns(head, base, "- ssn\n+ s.ssn\n", ["ssn"]), ["ssn"]) + }) + test("adding a join does not make an unqualified PII column look new", async () => { const base = "select customer_id,\n email\nfrom customers" const head = "select customer_id,\n email\nfrom customers\njoin orders using (customer_id)" From dd9f9ffdaca5bb7c2f7c20a746d088d7ccad562f Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:51:56 +0530 Subject: [PATCH 36/81] fix(review): never reuse a numbered nested-scope key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The numbered fallback key (`>sub`) was not checked against keys already taken, so an unaliased subquery inside `(…) s` and a second `(…) s` in another union branch both became `…>s>sub1` and were merged into one scope. The number now advances until the key is unused. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/rule-catalog.ts | 7 +++++-- .../opencode/test/altimate/review-rule-catalog.test.ts | 8 ++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 9c930ac64d..3bc7dd90da 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -426,9 +426,12 @@ function parseSelects(sql: string): ParsedSelects { ? `${parent}>${unquote(alias)}` : undefined let key = named if (!key || nestedKeys.has(key)) { - const n = (nestedCount.get(parent) ?? 0) + 1 + // Numbered within the parent, skipping any key already taken (a numbered + // key can equal one another scope numbered under the same alias). + let n = nestedCount.get(parent) ?? 0 + do key = `${named ?? parent}>sub${++n}` + while (nestedKeys.has(key)) nestedCount.set(parent, n) - key = `${named ?? parent}>sub${n}` } nestedKeys.add(key) return key diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 822db3a16e..c44c12e18b 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -7,6 +7,8 @@ import { rawColumnExposures, refCovered, selectItemColumns, + selectItems, + ROOT_SCOPE, } from "../../src/altimate/review/rule-catalog" describe("rule catalog (self-verifying scenario corpus)", () => { @@ -200,6 +202,12 @@ describe("rawColumnExposures", () => { ssn: ["customers.ssn"], }) }) + test("every nested query gets its own scope, even when a numbered key meets an aliased one", () => { + // Two union branches alias their subquery `s`; the first holds an unaliased subquery. + const sql = "select a from (select a from t where a in (select a from u)) s\nunion all\nselect a from (select a from v) s" + const scopes = selectItems(sql).filter((i) => i.scope !== ROOT_SCOPE).map((i) => i.scope) + expect(new Set(scopes).size).toBe(scopes.length) + }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) From 1d919822b3196cd583e3a133326f814c78745132 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:53:17 +0530 Subject: [PATCH 37/81] fix(review): never treat a computed output as reading nothing unless it is a constant MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `columnReads` cut any `filter (`, including the array function `filter(arr, x -> …)`, so `array_to_string(filter(c.phone_list, …), ',')` read nothing. `over` / `filter` / `within group` clauses are now cut only right after a call's `)`. - Soft keywords (`first`, `last`, `time`, `zone`, `row`, `range`, …) were dropped as syntax even when they are columns. They now count as columns unless they are in their keyword phrase (`nulls last`, `at time zone`, `respect nulls`). - An expression whose reads parse to nothing was "already exposed" (an empty `every`). A non-constant one now gets an unresolved read, so it falls through to the signature compare; only a constant reads nothing. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/rule-catalog.ts | 38 +++++++++++++++---- .../test/altimate/review-rule-catalog.test.ts | 18 +++++++++ .../opencode/test/altimate/review.test.ts | 7 ++++ 3 files changed, 56 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 3bc7dd90da..3f8e6153a0 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -253,6 +253,8 @@ export interface SelectItem { /** For an item that is not a raw column, every column reference its expression * reads (outside `over (…)`, `filter (…)` and `within group (…)`). */ reads?: Array<{ qualifier?: string; column: string }> + /** The item is a constant (literals, numbers, `null`/`true`/`false`, casts of them). */ + constant?: boolean /** `ROOT_SCOPE` for the outermost query, the CTE name for a CTE body, and for a * nested query `>` or, without one, `>sub`. */ scope: string @@ -291,7 +293,7 @@ const normalizeItem = (raw: string) => // Words in an expression that are syntax, never a column. const EXPR_KEYWORDS = new Set( - "and or not is null true false case when then else end as in like ilike rlike regexp similar escape between distinct all any some exists over partition by order asc desc nulls first last rows range groups unbounded preceding following current row filter within group interval from for at time zone collate both leading trailing using separator respect ignore cast try_cast".split( + "and or not is null true false case when then else end as in like ilike rlike regexp similar escape between distinct all any some exists over partition by order asc desc nulls filter within group interval from for collate both leading trailing using separator cast try_cast".split( " ", ), ) @@ -299,15 +301,20 @@ const COLUMN_TOKEN = new RegExp(String.raw`(? { let e = expr.replace(/'(?:[^']|'')*'/g, " ") - // `over (…)` / `filter (…)` / `within group (…)`: cut each clause to its `)`. - for (let m = /\b(?:over|filter|within\s+group)\s*\(/i.exec(e); m; m = /\b(?:over|filter|within\s+group)\s*\(/i.exec(e)) { + // `f(…) over (…)` / `filter (…)` / `within group (…)`: cut 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) + " " + e.slice(closingParen(e, open) + 1) + e = e.slice(0, m.index + 1) + " " + e.slice(closingParen(e, open) + 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 }> = [] @@ -336,14 +343,27 @@ function itemAlias(item: string): string | undefined { return alias ? unquote(alias) : undefined } -function describeItem(raw: string): Pick { +/** Only literals, numbers, `null`/`true`/`false` and casts of them. */ +function isConstant(expr: string): boolean { + const rest = expr + .replace(/'(?:[^']|'')*'/g, " ") + .replace(/::\s*\w+(?:\s*\([\d\s,]*\))?/g, " ") + .replace(/\bas\s+\w+(?:\s+\w+)*?(?:\s*\([\d\s,]*\))?\s*(?=\))/gi, " ") + .replace(/\b(?:null|true|false|cast)\b/gi, " ") + return /^[\s\d.+\-*/(),]*$/.test(rest) +} + +function describeItem( + raw: string, +): Pick { const text = normalizeItem(raw) const { expr, alias } = splitAlias(text) const ref = RAW_COLUMN_EXPRS.map((re) => re.exec(expr)).find(Boolean) const rawColumn = ref ? unquote(ref[2]) : undefined const rawQualifier = ref?.[1] ? unquote(ref[1]) : undefined const name = alias ? unquote(alias) : rawColumn - return ref ? { name, rawColumn, rawQualifier, text } : { name, text, reads: columnReads(expr) } + if (ref) return { name, rawColumn, rawQualifier, text } + return { name, text, reads: columnReads(expr), constant: isConstant(expr) } } // Words that end a FROM clause's table list at its own nesting level. @@ -785,6 +805,10 @@ export function finalOutputs(sql: string): FinalOutputs { } 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)) } } for (const [n, cols] of raw) if (!cols.size) raw.delete(n) diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index c44c12e18b..a56e7a2eae 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -178,6 +178,24 @@ describe("rawColumnExposures", () => { f: [], }) }) + test("`reads` keeps columns named like soft keywords and array `filter(…)` arguments", () => { + const sql = [ + "select first_value(c.last) over (order by c.ts nulls last) as a,", + " concat(time, ' ', zone) as b,", + " filter(c.phone_list, p -> p <> '') as d,", + " count(*) filter (where c.active) as e,", + " cast('n/a' as varchar) as f", + "from customers c", + ].join("\n") + const reads = Object.fromEntries([...finalOutputs(sql).reads].map(([k, v]) => [k, [...v].sort()])) + expect(reads.a).toEqual(["customers.last"]) + expect(reads.b).toEqual(["customers.time", "customers.zone"]) + expect(reads.d).toEqual(["customers.p", "customers.phone_list"]) + expect(reads.f).toEqual([]) + // `count(*)` reads no column but is not a constant: never "reads nothing". + expect(reads.e).toHaveLength(1) + expect(reads.e[0]).toMatch(/^\?\d+\.e$/) + }) test("`starRaw` resolves a column a plain `*` passes through", () => { expect([...finalOutputs("select * from customers").starRaw("ssn")]).toEqual(["customers.ssn"]) expect([...finalOutputs("select c.* from customers c join orders o on true").starRaw("ssn")]).toEqual(["customers.ssn"]) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index d5ba869fa2..b9795c4cc7 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2501,6 +2501,13 @@ describe("orchestrate", () => { for (const { env } of lowered) expect(env.findings.filter((f) => f.category === "pii_exposure")).toEqual([]) }) + test("a computed output read through an array `filter(…)` lambda is not taken as reading nothing", async () => { + const from = "sha2(phone) as phone" + const to = "array_to_string(filter(c.phone_list, p -> p <> ''), ',') as phone" + const sql = (item: string) => `select c.customer_id,\n ${item}\nfrom customers c` + expectReportedPii(await piiRuns(sql(to), sql(from), `- ${from}\n+ ${to}\n`, ["phone"]), ["phone"], "none") + }) + test("a changed literal in a masking expression is a different computation", async () => { const from = "regexp_replace(ssn, '\\d', '*') as ssn" const to = "regexp_replace(ssn, '^$', '*') as ssn" From 366abe985a4f770a734246b19586720dce5f8877 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:53:23 +0530 Subject: [PATCH 38/81] fix(review): say which inline comments a partial post dropped The comments the verified-only retry drops are those on files GitHub listed without a patch, not lines known to be outside the diff. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/cli/cmd/review.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opencode/src/cli/cmd/review.ts b/packages/opencode/src/cli/cmd/review.ts index b387a387a0..385d32bd7c 100644 --- a/packages/opencode/src/cli/cmd/review.ts +++ b/packages/opencode/src/cli/cmd/review.ts @@ -197,7 +197,7 @@ export const ReviewCommand = cmd({ UI.println( `Posted review to ${where}` + (r.inlineFellBack ? " (inline comments fell back to summary-only)" : "") + - (r.inlineDropped ? ` (${r.inlineDropped} inline comment(s) dropped: lines outside the diff)` : "") + + (r.inlineDropped ? ` (${r.inlineDropped} inline comment(s) on files without a known patch dropped)` : "") + (r.inlineSkippedAsPosted ? ` (${r.inlineSkippedAsPosted} inline already on the PR)` : "") + (r.reviewSkipped ? " (summary updated; no new review needed)" : ""), ) From 0d575b30185c2af6a3dc05504045b3ffb3ed7940 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:54:42 +0530 Subject: [PATCH 39/81] fix(review): compare a table's database/schema only when both sides were compiled in one environment Keeping database and schema in a source's identity reported pre-existing PII as new whenever the base and head compile to different schemas: a prod `target-base` (`"analytics"."dbt_prod"."customers"`) against a CI head (`"analytics"."dbt_ci_pr_42"."customers"`), slim CI with `--defer`, or a PR changing `+schema`. Base `from customers` -> head `from analytics.customers` was reported too. `finalOutputs` now lists the schema prefixes each side reads tables under, and `refCovered` takes them. Tables with the same own name match when either side is unqualified, or when their prefixes cannot be compared because a prefix appears on one side only. Two different prefixes are a different table only when each also appears among the other side's relations, so a model that reads both `restricted` and `public` on both sides still reports a switch from `restricted.customers` to `public.customers`. The `the same table name in another schema is a different source` test now reads both schemas on both sides; with one schema per side the change is indistinguishable from an environment difference and is not reported. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 14 +++-- .../src/altimate/review/rule-catalog.ts | 51 ++++++++++++++++--- .../test/altimate/review-rule-catalog.test.ts | 14 +++++ .../opencode/test/altimate/review.test.ts | 32 ++++++++++-- 4 files changed, 98 insertions(+), 13 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 6d3b86642c..32d0af4192 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -16,6 +16,7 @@ import { type ReviewMode, type ReviewScope, type VerdictEnvelope, buildEnvelope, import { detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" import { type FinalOutputs, + type RelationPrefixes, type SelectItem, type SelectItemColumn, finalOutputs, @@ -1239,6 +1240,13 @@ export async function runReview(input: OrchestrateInput): Promise ({ + head: outputs(file, "new").prefixes, + base: outputs(file, "old").prefixes, + }) // `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). @@ -1275,7 +1283,7 @@ export async function runReview(input: OrchestrateInput): Promise { const refs = [...(head.get(name) ?? [])].filter((r) => r.endsWith(`.${column}`)) - return refs.length > 0 && refs.every((r) => refCovered(r, exposed)) + return refs.length > 0 && refs.every((r) => refCovered(r, exposed, envOf(file))) }) } // A head PII output name the base already exposed. When the head selects a @@ -1293,14 +1301,14 @@ export async function runReview(input: OrchestrateInput): Promise refCovered(ref, exposed)) + return [...rawColumns].every((ref) => refCovered(ref, exposed, envOf(file))) } if (!basePii.has(name)) return false const base = outputs(file, "old") if (head.names.has(name)) { const exposed = baseRawPii(file) const reads = head.reads.get(name) - if (reads && [...reads].every((ref) => refCovered(ref, exposed))) return true + if (reads && [...reads].every((ref) => refCovered(ref, exposed, envOf(file)))) return true const baseSigs = base.signatures.get(name) return !!baseSigs && [...(head.signatures.get(name) ?? [])].every((sig) => baseSigs.has(sig)) } diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 3f8e6153a0..ef49bb370b 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -614,6 +614,9 @@ export interface FinalOutputs { * for a column they pass through unnamed (`select * from customers` → * `ssn: {customers.ssn}`; a CTE that masks it → none). */ starRaw: (column: string) => Set + /** 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 included) 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. */ @@ -624,7 +627,7 @@ export interface FinalOutputs { reads: Map> } -interface ScopeOutputs extends Omit { +interface ScopeOutputs extends Omit { /** `*` items, whose columns pass through unnamed (`select * from customers`). */ stars: Array<{ branch: number; qualifier?: string }> /** Every item's text, and that of every scope it reads. */ @@ -660,6 +663,39 @@ 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 + * `{{ ref(…) }}` name has no prefix. */ +function splitTable(table: string): { prefix: string; name: string } { + const dot = table.startsWith("{{") ? -1 : table.lastIndexOf(".") + return dot < 0 ? { prefix: "", name: table } : { prefix: table.slice(0, dot), name: table.slice(dot + 1) } +} + +/** The database/schema prefixes each side's SQL reads tables under. */ +export interface RelationPrefixes { + head: Set + base: Set +} + +/** + * 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 compared only when each also appears among the other + * side's relations, i.e. both sides were compiled in one environment: a base + * compiled into `dbt_prod` and a head into `dbt_ci_pr_42` (or a `+schema` + * change) read the same tables, while `restricted.customers` vs + * `public.customers` in a model that reads both schemas on both sides do not. + * Without `env`, names must be equal. + */ +function sameTable(h: string, b: string, env?: RelationPrefixes): boolean { + if (h === b) return true + if (!env) return false + const x = splitTable(h) + const y = splitTable(b) + if (x.name !== y.name) return false + if (!x.prefix || !y.prefix) return true + return !(env.base.has(x.prefix) && env.head.has(y.prefix)) +} + /** * `ref` is one of the `exposed` source columns. An unqualified column read over * several tables (`customers|orders.email`, see `rawColumnExposures`) comes from @@ -667,15 +703,16 @@ const splitRef = (ref: string) => { * covered by a single-table ref to one of its members. The reverse is not: a * base combined ref does not say which table the column came from, so a head * read pinned to one of them (`s.ssn`) may be new. Two combined refs match only - * when equal. + * when equal. Tables compare as in `sameTable` (database/schema only within + * one environment). */ -export function refCovered(ref: string, exposed: Set): boolean { +export function refCovered(ref: string, exposed: Set, env?: RelationPrefixes): boolean { if (exposed.has(ref)) return true const r = splitRef(ref) for (const e of exposed) { const x = splitRef(e) - if (x.column !== r.column) continue - if (r.tables.length > 1 && x.tables.length === 1 && r.tables.includes(x.tables[0])) return true + if (x.column !== r.column || x.tables.length !== 1) continue + if (r.tables.some((t) => sameTable(t, x.tables[0], env))) return true } return false } @@ -820,7 +857,9 @@ export function finalOutputs(sql: string): FinalOutputs { const { raw, names, signatures, reads, stars } = resolve(ROOT_SCOPE, new Set()) const starRaw = (column: string) => union(stars.map((st) => resolveRef(ROOT_SCOPE, st.branch, st.qualifier, column, new Set()).raw)) - return { raw, names, signatures, reads, passthrough: stars.length > 0, starRaw } + 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 } } /** A diff line with comments and whitespace normalised (and a leading/trailing diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index a56e7a2eae..2cec28880d 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -211,6 +211,20 @@ describe("rawColumnExposures", () => { expect(refCovered("customers|orders.email", new Set(["customers.ssn"]))).toBe(false) expect(refCovered("a|b.email", new Set(["b|c.email"]))).toBe(false) }) + test("`refCovered` compares database/schema only within one environment", () => { + const prod = new Set(["analytics.dbt_prod.customers.ssn"]) + // Different environments: the prefixes appear on one side only. + const envs = { head: new Set(["analytics.dbt_ci_pr_42"]), base: new Set(["analytics.dbt_prod"]) } + 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 = { head: new Set(["restricted", "public"]), base: new Set(["restricted", "public"]) } + expect(refCovered("public.customers.ssn", new Set(["restricted.customers.ssn"]), both)).toBe(false) + // Without an environment, names must be equal. + expect(refCovered("analytics.dbt_ci_pr_42.customers.ssn", prod)).toBe(false) + }) test("`distinct on (…)` is a select prefix, not part of the first item", () => { expect(asObject(rawColumnExposures("select distinct on (id) ssn, id from customers"))).toEqual({ ssn: ["customers.ssn"], diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index b9795c4cc7..6018c9dfe1 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2577,10 +2577,34 @@ describe("orchestrate", () => { expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) }) - test("the same table name in another schema is a different source", async () => { - const base = "select customer_id,\n ssn\nfrom restricted.customers" - const head = "select customer_id,\n ssn\nfrom public.customers" - expectReportedPii(await piiRuns(head, base, "-from restricted.customers\n+from public.customers\n", ["ssn"]), ["ssn"], "none") + test("the same table name in another schema is a different source when both sides read both schemas", async () => { + // Both schemas appear on both sides, so the prefixes are comparable. + const base = "select c.customer_id,\n c.ssn\nfrom restricted.customers c\njoin public.customers p using (customer_id)" + const head = base.replace(" c.ssn\n", " p.ssn\n") + expectReportedPii(await piiRuns(head, base, "- c.ssn\n+ p.ssn\n", ["ssn"]), ["ssn"]) + }) + + test("a base compiled into another schema is the same table, not new exposure", async () => { + const raw = "select customer_id,\n ssn\nfrom {{ ref('customers') }}" + const touched = raw.replace("select customer_id,", "select customer_id, region,") + const compiled = (schema: string, sql: string) => sql.replace("{{ ref('customers') }}", `"analytics"."${schema}"."customers"`) + const runs = await piiRuns(touched, raw, "-select customer_id,\n+select customer_id, region,\n", ["ssn"], { + head: compiled("dbt_ci_pr_42", touched), + base: compiled("dbt_prod", raw), + }) + for (const { reviewers, env } of runs) { + expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) + expect(env.verdict).not.toBe("REQUEST_CHANGES") + } + // 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"], + ) + for (const { reviewers, env } of quiet) + expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) }) test("a qualified reference resolves through its own source, not any CTE with that column", async () => { From 36923226d63096913f465522733e1b36ce3d8b9b Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 11:59:53 +0530 Subject: [PATCH 40/81] fix(review): compare two combined join refs member by member MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two combined refs (an unqualified column over a join) still compared as exact strings, so the same join compiled into `dbt_prod` and `dbt_ci` (`…dbt_prod.customers|raw.crm.orders.ssn` vs `…dbt_ci.customers|…`) was reported as new. A head combined ref is now covered by a base combined ref with the same number of tables when each head table matches a base table under `sameTable`. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/rule-catalog.ts | 14 ++++++++++---- packages/opencode/test/altimate/review.test.ts | 6 ++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index ef49bb370b..f39b93b8dc 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -703,16 +703,22 @@ function sameTable(h: string, b: string, env?: RelationPrefixes): boolean { * covered by a single-table ref to one of its members. The reverse is not: a * base combined ref does not say which table the column came from, so a head * read pinned to one of them (`s.ssn`) may be new. Two combined refs match only - * when equal. Tables compare as in `sameTable` (database/schema only within - * one environment). + * when they read the same tables, member by member. Tables compare as in + * `sameTable` (database/schema only within one environment). */ export function refCovered(ref: string, exposed: Set, env?: RelationPrefixes): boolean { if (exposed.has(ref)) return true const r = splitRef(ref) for (const e of exposed) { const x = splitRef(e) - if (x.column !== r.column || x.tables.length !== 1) continue - if (r.tables.some((t) => sameTable(t, x.tables[0], env))) return true + if (x.column !== r.column) continue + if (x.tables.length === 1) { + if (r.tables.some((t) => sameTable(t, x.tables[0], env))) return true + continue + } + // Two combined refs: the same tables, member by member. + if (r.tables.length === x.tables.length && r.tables.every((t) => x.tables.some((b) => sameTable(t, b, env)))) + return true } return false } diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 6018c9dfe1..593fd87968 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2596,6 +2596,12 @@ 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"]) + 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", From e34e5efd13727077afedbfad80aec92efc785c11 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:00:18 +0530 Subject: [PATCH 41/81] fix(review): treat a move to a schema the base already read as a different table Two prefixes of a same-named table were compared only when each appeared on the other side, so base `restricted.customers c join public.orders o` -> head `public.customers c join public.orders o` was quiet. They are now different tables whenever the base already read tables under the head's prefix; a head prefix the base never read (prod -> CI schema, a `+schema` change, the `--defer` mix) is still an environment difference. A single-table swap to a schema the base never read remains quiet. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/rule-catalog.ts | 13 +++++++------ .../test/altimate/review-rule-catalog.test.ts | 6 ++++++ packages/opencode/test/altimate/review.test.ts | 10 ++++++++++ 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index f39b93b8dc..15d3bf3e1e 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -679,11 +679,12 @@ export interface RelationPrefixes { /** * 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 compared only when each also appears among the other - * side's relations, i.e. both sides were compiled in one environment: a base - * compiled into `dbt_prod` and a head into `dbt_ci_pr_42` (or a `+schema` - * change) read the same tables, while `restricted.customers` vs - * `public.customers` in a model that reads both schemas on both sides do not. + * 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. */ function sameTable(h: string, b: string, env?: RelationPrefixes): boolean { @@ -693,7 +694,7 @@ function sameTable(h: string, b: string, env?: RelationPrefixes): boolean { const y = splitTable(b) if (x.name !== y.name) return false if (!x.prefix || !y.prefix) return true - return !(env.base.has(x.prefix) && env.head.has(y.prefix)) + return !env.base.has(x.prefix) } /** diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 2cec28880d..bda415e1ec 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -222,6 +222,12 @@ describe("rawColumnExposures", () => { // Both schemas read on both sides: the prefix is compared. const both = { head: new Set(["restricted", "public"]), base: new Set(["restricted", "public"]) } 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 = { head: new Set(["public"]), base: new Set(["restricted", "public"]) } + 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 = { head: new Set(["public"]), base: new Set(["restricted"]) } + expect(refCovered("public.customers.ssn", new Set(["restricted.customers.ssn"]), alone)).toBe(true) // 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 593fd87968..becffef985 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2584,6 +2584,16 @@ describe("orchestrate", () => { expectReportedPii(await piiRuns(head, base, "- c.ssn\n+ p.ssn\n", ["ssn"]), ["ssn"]) }) + test("switching a table to a schema the base already read is a different source", async () => { + const base = "select c.customer_id,\n c.ssn\nfrom restricted.customers c\njoin public.orders o using (customer_id)" + const head = base.replace("restricted.customers", "public.customers") + expectReportedPii( + await piiRuns(head, base, "-from restricted.customers c\n+from public.customers c\n", ["ssn"]), + ["ssn"], + "none", + ) + }) + test("a base compiled into another schema is the same table, not new exposure", async () => { const raw = "select customer_id,\n ssn\nfrom {{ ref('customers') }}" const touched = raw.replace("select customer_id,", "select customer_id, region,") From 7c13b482221e94860479591b0d90052398609ace Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 12:01:09 +0530 Subject: [PATCH 42/81] =?UTF-8?q?fix(review):=20read=20`null`=20items=20as?= =?UTF-8?q?=20constants=20and=20keep=20`within=20group=20(=E2=80=A6)`=20in?= =?UTF-8?q?side=20its=20select=20item?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A bare `null` / `true` / `false` (or `cast(null as …)`) matched the raw-column pattern and became a raw column named `null`. It is now a constant, which reads nothing. - `listagg(x, ',') within group (order by y) as z` ended the select list at `group`, losing the alias and every later item (in the select-list parser and in the regex twins' clause cut). A `group (` right after `within` no longer ends the list. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/rule-catalog.ts | 12 ++++++++++-- .../test/altimate/review-rule-catalog.test.ts | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 15d3bf3e1e..3fdfb522e6 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -204,6 +204,10 @@ const NOT_AN_ALIAS = new Set( const SELECT_LIST_END = /^(from|where|group|order|limit|qualify|having|union|intersect|except|minus|window|into|fetch|offset)\b/i +/** The `group` at `at` is the `within group (…)` of an ordered-set aggregate. */ +const withinGroup = (sql: string, at: number) => + /^group\s*\(/i.test(sql.slice(at, at + 20)) && /\bwithin\s+$/i.test(sql.slice(Math.max(0, at - 20), at)) + /** `line` with everything outside a select list blanked: from a clause keyword * (`from`, `where`, …) at a query's own level up to the next `select`. A * keyword inside a call (`extract(day from d)`) does not count. */ @@ -224,7 +228,7 @@ function selectListText(line: string): string { if (outer) ({ query, listing } = outer) } else if (query && !isWordChar(line[i - 1])) { if (/^select\b/i.test(line.slice(i, i + 7))) listing = true - else if (SELECT_LIST_END.test(line.slice(i, i + 10))) listing = false + else if (SELECT_LIST_END.test(line.slice(i, i + 10)) && !withinGroup(line, i)) listing = false } out += listing || c === "(" || c === ")" ? c : c === "\n" ? c : " " } @@ -358,7 +362,9 @@ function describeItem( ): Pick { const text = normalizeItem(raw) const { expr, alias } = splitAlias(text) - const ref = RAW_COLUMN_EXPRS.map((re) => re.exec(expr)).find(Boolean) + const matched = RAW_COLUMN_EXPRS.map((re) => re.exec(expr)).find(Boolean) + // A bare `null` / `true` / `false` (or a cast of one) is a constant, not a column. + const ref = matched && !matched[1] && /^(?:null|true|false)$/i.test(matched[2]) ? undefined : matched const rawColumn = ref ? unquote(ref[2]) : undefined const rawQualifier = ref?.[1] ? unquote(ref[1]) : undefined const name = alias ? unquote(alias) : rawColumn @@ -522,6 +528,8 @@ function parseSelects(sql: string): ParsedSelects { depth === 0 && !isWordChar(s[j - 1]) && SELECT_LIST_END.test(s.slice(j, j + 10)) && + // `listagg(x, ',') within group (order by y)` is part of the item. + !withinGroup(s, j) && // `* except (…)` (BigQuery) is one item, not a set operation. !(/^except\b/i.test(s.slice(j, j + 7)) && /\*\s*$/.test(s.slice(itemStart, j))) ) { diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index bda415e1ec..da1508e0f5 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -246,6 +246,22 @@ describe("rawColumnExposures", () => { const scopes = selectItems(sql).filter((i) => i.scope !== ROOT_SCOPE).map((i) => i.scope) expect(new Set(scopes).size).toBe(scopes.length) }) + test("`null` / `true` / `false` items are constants, not raw columns", () => { + const out = finalOutputs("select null as ssn, cast(null as varchar) as email, true as flag, c.id from customers c") + expect(Object.fromEntries([...out.raw].map(([k, v]) => [k, [...v]]))).toEqual({ id: ["customers.id"] }) + expect([...out.reads.get("ssn")!]).toEqual([]) + expect([...out.reads.get("email")!]).toEqual([]) + }) + test("`within group (…)` does not end the select list", () => { + const sql = "select listagg(c.ssn, ',') within group (order by c.id) as ssns, c.email from customers c" + const out = finalOutputs(sql) + expect([...out.names].sort()).toEqual(["email", "ssns"]) + expect(asObject(out.raw)).toEqual({ email: ["customers.email"] }) + expect([...out.reads.get("ssns")!]).toEqual(["customers.ssn"]) + expect(selectItemColumns("listagg(ssn, ',') within group (order by id) as ssns", /\b(ssn)\b/i)).toEqual([ + { column: "ssn", alias: "ssns", line: "listagg(ssn, ',') within group (order by id) as ssns" }, + ]) + }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) From c6c73c0f8da0d0d85dbead54b52e4943380ce46e Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:42:29 +0530 Subject: [PATCH 43/81] fix(review): resolve a base `*` over a join to each source on its own `starRaw` resolved an unqualified `*` through the unqualified-column path, which over several sources returns one combined ref (`customers|spouses.ssn`). That is right for a column read (it comes from exactly one source) but not for a `*`, which passes every source's columns through. `refCovered` never lets a combined base ref cover a single-table head ref, so expanding `select * from customers c join spouses s` into `c.ssn` was reported as new PII exposure. `starRefs` now resolves each source of the star's select on its own, following derived sources through their own `*`. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/rule-catalog.ts | 30 +++++++++++++++- .../test/altimate/review-rule-catalog.test.ts | 15 ++++++++ .../opencode/test/altimate/review.test.ts | 36 +++++++++++++++++++ 3 files changed, 80 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 3fdfb522e6..b97ef78d65 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -870,8 +870,36 @@ export function finalOutputs(sql: string): FinalOutputs { return result } const { raw, names, signatures, 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 + // resolved on its own: `select * from customers join spouses` exposes + // `customers.ssn` and `spouses.ssn`, which a head `c.ssn` or `s.ssn` matches. + const starRefs = (scope: string, branch: number, qualifier: string | undefined, col: string, seen: Set) => { + const srcs = sources.get(`${scope}#${branch}`) ?? [] + const named = (x: Source) => x.name === qualifier || x.short === qualifier + const picked = qualifier + ? [srcs.find((x) => x.alias === qualifier) ?? srcs.find((x) => !x.alias && named(x)) ?? srcs.find(named)].filter( + (x): x is Source => !!x, + ) + : srcs + const inner = innerOf(seen, scope) + const out = new Set() + for (const src of picked) { + if (!isDerived(src, scope, seen)) { + if (!byScope.has(src.name)) out.add(`${src.name}.${col}`) + continue + } + const body = resolve(src.name, inner) + const refs = body.names.has(col) + ? (body.raw.get(col) ?? new Set()) + : union(body.stars.map((st) => starRefs(src.name, st.branch, st.qualifier, col, inner))) + for (const r of refs) out.add(r) + } + return out + } const starRaw = (column: string) => - union(stars.map((st) => resolveRef(ROOT_SCOPE, st.branch, st.qualifier, column, new Set()).raw)) + 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 } diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index da1508e0f5..f8cfab0386 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -203,6 +203,21 @@ describe("rawColumnExposures", () => { const masked = "with m as (select customer_id, sha2(ssn) as ssn from customers) select * from m" expect([...finalOutputs(masked).starRaw("ssn")]).toEqual([]) }) + test("`starRaw` resolves a plain `*` over a join to each source on its own", () => { + // A `*` passes every source's columns through; an unqualified column read does not. + const join = "select * from customers c join spouses s using (customer_id)" + expect([...finalOutputs(join).starRaw("ssn")].sort()).toEqual(["customers.ssn", "spouses.ssn"]) + const viaCte = `with j as (${join}) select * from j` + expect([...finalOutputs(viaCte).starRaw("ssn")].sort()).toEqual(["customers.ssn", "spouses.ssn"]) + // A qualified `*` stays on its source; a CTE that names the column is used as named. + expect([...finalOutputs("select s.* from customers c join spouses s on true").starRaw("ssn")]).toEqual(["spouses.ssn"]) + const named = "with k as (select customer_id, sha2(ssn) as ssn from customers) select * from k join spouses s using (customer_id)" + expect([...finalOutputs(named).starRaw("ssn")]).toEqual(["spouses.ssn"]) + // The unqualified column read keeps its combined ref. + expect(asObject(rawColumnExposures("select ssn from customers c join spouses s using (customer_id)"))).toEqual({ + ssn: ["customers|spouses.ssn"], + }) + }) test("`refCovered` matches an unqualified column over a join to its single-table ref", () => { expect(refCovered("customers|orders.email", new Set(["customers.email"]))).toBe(true) // The reverse is not covered: the base never said which table it read. diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index becffef985..12374a6c19 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2556,6 +2556,42 @@ describe("orchestrate", () => { expect(broad.map((f) => (f.evidence?.result as any)?.columns)).toEqual([["email", "ssn"], ["email", "ssn"], ["email", "ssn"]]) }) + test("expanding a base `select *` over a join into qualified columns is not new exposure", async () => { + // detectPii sees the joined tables' columns through `*`, as the real engine does with a schema. + const runs = async (head: string, base: string, diff: string) => { + const out: Array<{ reviewers: string[]; env: Awaited> }> = [] + for (const reviewers of [["pii_exposure"], [], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: { + ...piiRunner(["ssn"]), + async detectPii(sql: string) { + return { columns: /\bssn\b|select\s+\*/i.test(sql) ? ["ssn"] : [] } + }, + }, + getContent: content(head, base), + }) + out.push({ reviewers, env }) + } + return out + } + const base = "select *\nfrom customers c\njoin spouses s using (customer_id)" + for (const col of ["c.ssn", "s.ssn"]) { + const head = `select c.customer_id,\n ${col}\nfrom customers c\njoin spouses s using (customer_id)` + for (const { reviewers, env } of await runs(head, base, `-select *\n+select c.customer_id,\n+ ${col}\n`)) + expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) + } + // Control: the same column from a table the base never read is new. + const other = "select c.customer_id,\n e.ssn\nfrom customers c\njoin employees e using (customer_id)" + expectReportedPii( + await runs(other, base, "-select *\n-from customers c\n-join spouses s using (customer_id)\n+select c.customer_id,\n+ e.ssn\n+from customers c\n+join employees e using (customer_id)\n"), + ["ssn"], + ) + }) + test("a head column pinned to one table is new when the base read it unqualified over a join", async () => { // Base `ssn` over customers ⋈ spouses does not say which table it came from. const base = "select customer_id,\n ssn\nfrom customers c\njoin spouses s using (customer_id)" From bb81d27af989477a54f2d84f7d512232574e2aa7 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:42:50 +0530 Subject: [PATCH 44/81] =?UTF-8?q?fix(review):=20find=20`within=20group=20(?= =?UTF-8?q?=E2=80=A6)`=20across=20any=20run=20of=20whitespace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `withinGroup` looked only 20 characters either side of `group`, so a masked comment or a long whitespace run between `within` and `group` (or before the `(`) ended the select list there and cut the aggregate's item and every item after it. It now skips whitespace of any length on both sides. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/rule-catalog.ts | 14 +++++++++++--- .../test/altimate/review-rule-catalog.test.ts | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index b97ef78d65..0533b348c5 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -204,9 +204,17 @@ const NOT_AN_ALIAS = new Set( const SELECT_LIST_END = /^(from|where|group|order|limit|qualify|having|union|intersect|except|minus|window|into|fetch|offset)\b/i -/** The `group` at `at` is the `within group (…)` of an ordered-set aggregate. */ -const withinGroup = (sql: string, at: number) => - /^group\s*\(/i.test(sql.slice(at, at + 20)) && /\bwithin\s+$/i.test(sql.slice(Math.max(0, at - 20), at)) +/** The `group` at `at` is the `within group (…)` of an ordered-set aggregate. + * Any run of whitespace (a masked comment is one) may separate the words. */ +const withinGroup = (sql: string, at: number) => { + if (!/^group$/i.test(sql.slice(at, at + 5))) return false + let after = at + 5 + while (/\s/.test(sql[after] ?? "")) after++ + if (sql[after] !== "(") return false + let before = at + while (before > 0 && /\s/.test(sql[before - 1])) before-- + return before < at && /(?:^|[^\w$."`])within$/i.test(sql.slice(Math.max(0, before - 7), before)) +} /** `line` with everything outside a select list blanked: from a clause keyword * (`from`, `where`, …) at a query's own level up to the next `select`. A diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index f8cfab0386..21ae0b70c9 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -277,6 +277,20 @@ describe("rawColumnExposures", () => { { column: "ssn", alias: "ssns", line: "listagg(ssn, ',') within group (order by id) as ssns" }, ]) }) + test("`within group` split by a long comment or whitespace run does not end the select list", () => { + for (const gap of [" /* ordered-set aggregate, keep the order stable */ ", " ".repeat(30), "\n\n" + " ".repeat(24)]) { + for (const sql of [ + `select listagg(c.ssn, ',') within${gap}group (order by c.id) as ssns, c.email from customers c`, + `select listagg(c.ssn, ',') within group${gap}(order by c.id) as ssns, c.email from customers c`, + ]) { + const out = finalOutputs(sql) + expect([...out.names].sort()).toEqual(["email", "ssns"]) + expect(asObject(out.raw)).toEqual({ email: ["customers.email"] }) + } + } + // `group by` is still a clause. + expect([...finalOutputs("select c.email from customers c group by c.email").names]).toEqual(["email"]) + }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) From b3d64e2235f99b207ac1db0cc051109536b1a078 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:43:01 +0530 Subject: [PATCH 45/81] fix(review): read typed literals as constants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `date '2024-01-01'`, `timestamp '…'` and `interval '1 day'` were not constants, and their type word was recorded as a column read (`customers.date`). A head that replaced a base PII output with a typed literal under the same name then looked like it read a column the base never exposed. `isConstant` and `columnReads` now drop a type word that prefixes a string literal. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/rule-catalog.ts | 7 ++++++- .../test/altimate/review-rule-catalog.test.ts | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 0533b348c5..efbbac1c0c 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -309,6 +309,10 @@ const EXPR_KEYWORDS = new Set( " ", ), ) +// A typed literal (`date '2024-01-01'`, `timestamp '…'`, `interval '1 day'`): its +// type word is part of the constant, not a column. +const TYPED_LITERAL = + /(? { - let e = expr.replace(/'(?:[^']|'')*'/g, " ") + let e = expr.replace(TYPED_LITERAL, " ").replace(/'(?:[^']|'')*'/g, " ") // `f(…) over (…)` / `filter (…)` / `within group (…)`: cut 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 @@ -358,6 +362,7 @@ function itemAlias(item: string): string | undefined { /** Only literals, numbers, `null`/`true`/`false` and casts of them. */ function isConstant(expr: string): boolean { const rest = expr + .replace(TYPED_LITERAL, " ") .replace(/'(?:[^']|'')*'/g, " ") .replace(/::\s*\w+(?:\s*\([\d\s,]*\))?/g, " ") .replace(/\bas\s+\w+(?:\s+\w+)*?(?:\s*\([\d\s,]*\))?\s*(?=\))/gi, " ") diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 21ae0b70c9..cb58814012 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -291,6 +291,23 @@ describe("rawColumnExposures", () => { // `group by` is still a clause. expect([...finalOutputs("select c.email from customers c group by c.email").names]).toEqual(["email"]) }) + test("typed literals are constants and read no column", () => { + const sql = [ + "select date '2024-01-01' as dob,", + " timestamp '2024-01-01 00:00:00' as signup_at,", + " interval '1 day' as gap,", + " date_trunc('day', c.signup_date) as d,", + " concat(time, ' ', zone) as t", + "from customers c", + ].join("\n") + const out = finalOutputs(sql) + expect([...out.reads.get("dob")!]).toEqual([]) + expect([...out.reads.get("signup_at")!]).toEqual([]) + expect([...out.reads.get("gap")!]).toEqual([]) + expect([...out.reads.get("d")!]).toEqual(["customers.signup_date"]) + expect([...out.reads.get("t")!].sort()).toEqual(["customers.time", "customers.zone"]) + expect(selectItems(sql).filter((i) => i.constant).map((i) => i.name)).toEqual(["dob", "signup_at", "gap"]) + }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) From 0aca7d912b4278e763bce245145d5ff5e5a8e995 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:43:01 +0530 Subject: [PATCH 46/81] fix(review): keep whole entries in a grouped bullet's per-model detail The per-model values of a grouped bullet were clipped as free text to the 600-character body budget, so the cut could land inside a backticked value (leaving a dangling backtick) or drop the `(+N more)` count. The detail now keeps the leading entries that fit whole and counts every entry left out. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 14 ++++++----- .../test/altimate/review-noise.test.ts | 24 +++++++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index b387ae91d3..6c74a0e2e1 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -255,14 +255,16 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou // column on one model): list each member's own values. const values = g.map((f) => ({ f, v: distinguishingValues(f) })) const differ = values.some(({ v }) => v.join("\u0000") !== values[0].v.join("\u0000")) + // Whole entries that fit the body budget, so a cut never lands inside a + // code span or drops the count of the rest. + const entries = values + .slice(0, 8) + .map(({ f, v }) => `\`${f.model ?? f.file}\`: ${v.map((x) => `\`${x}\``).join(", ") || "—"}`) + const kept = takeWhole(entries, BULLET_BODY_MAX, " · ") + const rest = values.length - kept.length const detail = differ && values.some(({ v }) => v.length) - ? ` ${bodyOf( - values - .slice(0, 8) - .map(({ f, v }) => `\`${f.model ?? f.file}\`: ${v.map((x) => `\`${x}\``).join(", ") || "—"}`) - .join(" · ") + (values.length > 8 ? ` (+${values.length - 8} more)` : ""), - )} \n` + ? ` ${kept.join(" · ")}${rest ? `${kept.length ? " " : ""}(+${rest} more)` : ""} \n` : "" const unverified = g.some((f) => f.degraded) ? " · _unverified_" : "" out.push({ diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 7c98e78f4a..a094f22200 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -261,6 +261,30 @@ describe("summary grouping and budget", () => { expect(md).toContain("`a`: `ILIKE` · `b`: `QUALIFY` · `c`: `IFF` · `c`: `NVL2`") }) + test("a long per-member list keeps whole entries and counts the rest", () => { + // Nine members, each naming several long columns: the list exceeds the body budget. + const fs = Array.from({ length: 9 }, (_, i) => + finding({ + severity: "warning", + category: "sql_quality", + model: `model_${i}`, + file: `models/model_${i}.sql`, + title: `model_${i}: unsupported function`, + body: ["a", "b", "c"].map((x) => `\`${x}_${i}_${"y".repeat(30)}\``).join(", ") + " are unsupported.", + }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + const detail = md.split("\n").find((l) => l.includes("`model_0`: "))! + expect(detail).toBeDefined() + // Every code span is closed, and the entries left out are counted. + expect((detail.match(/`/g) ?? []).length % 2).toBe(0) + const shown = (detail.match(/`model_\d+`: /g) ?? []).length + expect(shown).toBeGreaterThan(0) + expect(shown).toBeLessThan(9) + expect(detail).toContain(`(+${9 - shown} more)`) + expect(detail).not.toContain("…") + }) + test("findings titled by their file group like findings titled by their model", () => { const fs = ["a", "b", "c"].map((m) => finding({ From 36159a804cb874b70cd477f63d9a1cce154f4685 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:43:10 +0530 Subject: [PATCH 47/81] fix(review): drop the unused head side of `RelationPrefixes` `sameTable` only asks whether the base already read tables under the head's prefix, so `RelationPrefixes.head` was computed and never read. The interface, `envOf` and the `refCovered` environment tests now carry the base prefixes only; every expectation is unchanged. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/orchestrate.ts | 7 ++----- packages/opencode/src/altimate/review/rule-catalog.ts | 4 ++-- .../opencode/test/altimate/review-rule-catalog.test.ts | 10 +++++----- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 32d0af4192..4da1b1fa4a 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1240,13 +1240,10 @@ export async function runReview(input: OrchestrateInput): Promise ({ - head: outputs(file, "new").prefixes, - base: outputs(file, "old").prefixes, - }) + const envOf = (file: string): RelationPrefixes => ({ base: outputs(file, "old").prefixes }) // `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). diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index efbbac1c0c..7212cffcc4 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -691,9 +691,9 @@ function splitTable(table: string): { prefix: string; name: string } { return dot < 0 ? { prefix: "", name: table } : { prefix: table.slice(0, dot), name: table.slice(dot + 1) } } -/** The database/schema prefixes each side's SQL reads tables under. */ +/** The database/schema prefixes the base's SQL reads tables under: `sameTable` + * asks only whether the base already read tables under the head's prefix. */ export interface RelationPrefixes { - head: Set base: Set } diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index cb58814012..8b4350a97e 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -228,20 +228,20 @@ describe("rawColumnExposures", () => { }) test("`refCovered` compares database/schema only within one environment", () => { const prod = new Set(["analytics.dbt_prod.customers.ssn"]) - // Different environments: the prefixes appear on one side only. - const envs = { head: new Set(["analytics.dbt_ci_pr_42"]), base: new Set(["analytics.dbt_prod"]) } + // Different environments: the head reads under `analytics.dbt_ci_pr_42`, which the base never read. + const envs = { base: new Set(["analytics.dbt_prod"]) } 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 = { head: new Set(["restricted", "public"]), base: new Set(["restricted", "public"]) } + const both = { base: new Set(["restricted", "public"]) } 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 = { head: new Set(["public"]), base: new Set(["restricted", "public"]) } + const swap = { base: new Set(["restricted", "public"]) } 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 = { head: new Set(["public"]), base: new Set(["restricted"]) } + const alone = { base: new Set(["restricted"]) } expect(refCovered("public.customers.ssn", new Set(["restricted.customers.ssn"]), alone)).toBe(true) // Without an environment, names must be equal. expect(refCovered("analytics.dbt_ci_pr_42.customers.ssn", prod)).toBe(false) From 8e859b03b58a71719a8054b6d2feb480758458a2 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:43:10 +0530 Subject: [PATCH 48/81] fix(review): drop a no-op `detectPii` override in a reindent test `piiRunner([])` already reports no PII columns, so the override changed nothing. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/test/altimate/review.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 12374a6c19..6aec89b6d6 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2747,7 +2747,7 @@ describe("orchestrate", () => { test("a reindent inside a nested query stays a reindent when a subquery is added above it", async () => { // Base PII detection misses `ssn`, so only the reindent check keeps the twin quiet. - const runner: ReviewRunner = { ...piiRunner([]), detectPii: async () => ({ columns: [] }) } + const runner: ReviewRunner = piiRunner([]) const base = [ "with a as (select customer_id from customers)", "select s.customer_id, s.ssn", From 374b92e1c1b865a4b0d650783e7a92b04736a30a Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:43:10 +0530 Subject: [PATCH 49/81] fix(review): say grouped findings share a severity in the PR review docs The summary renders each severity separately, so the same rule and message at two severities never become one bullet. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 28ce2cdfb4..7b7cac73ac 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -293,8 +293,8 @@ rubric: counted, and the full list is always in the job log and the verdict envelope (`altimate review --json --output `). Local CLI output is never truncated. - **Repeated findings are grouped:** the same rule and message (ignoring model - and column names) on three or more models is one bullet listing the models, - with each model's own names when they differ. Local CLI output lists every + and column names) at the same severity on three or more models is one bullet + listing the models, with each model's own names when they differ. 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. From 3382f415a6411aa69cabaff3446d34e6a0711a5a Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:49:18 +0530 Subject: [PATCH 50/81] fix(review): memoise `starRefs` A chain of CTEs whose `*` each joins the previous one twice doubled the `starRefs` walk at every level (22 levels took about 1.2 s, 24 about 4.8 s). It is now memoised on scope, branch, qualifier and column like `resolveRef`; results are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/rule-catalog.ts | 17 +++++++++++++++++ .../test/altimate/review-rule-catalog.test.ts | 8 ++++++++ 2 files changed, 25 insertions(+) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 7212cffcc4..e13f2a20e7 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -888,7 +888,24 @@ export function finalOutputs(sql: string): FinalOutputs { // them), a `*` passes every source's columns through, so each source is // resolved on its own: `select * from customers join spouses` exposes // `customers.ssn` and `spouses.ssn`, which a head `c.ssn` or `s.ssn` matches. + // Memoised like `resolveRef`: a CTE whose `*` joins the previous one twice + // would otherwise double the walk at every level. + const starMemo = new Map>() const starRefs = (scope: string, branch: number, qualifier: string | undefined, col: string, seen: Set) => { + const memoKey = `${scope}#${branch}\u0000${qualifier ?? ""}\u0000${col}` + const hit = starMemo.get(memoKey) + if (hit) return hit + const out = starRefsUncached(scope, branch, qualifier, col, seen) + starMemo.set(memoKey, out) + return out + } + const starRefsUncached = ( + scope: string, + branch: number, + qualifier: string | undefined, + col: string, + seen: Set, + ): Set => { const srcs = sources.get(`${scope}#${branch}`) ?? [] const named = (x: Source) => x.name === qualifier || x.short === qualifier const picked = qualifier diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 8b4350a97e..e6cfeed833 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -218,6 +218,14 @@ describe("rawColumnExposures", () => { ssn: ["customers|spouses.ssn"], }) }) + test("`starRaw` stays fast over a chain of `*` CTEs that each join the previous one twice", () => { + const ctes = ["c0 as (select * from customers)"] + for (let i = 1; i <= 30; i++) ctes.push(`c${i} as (select * from c${i - 1} a join c${i - 1} b using (customer_id))`) + const sql = `with ${ctes.join(",\n")}\nselect * from c30` + const t0 = performance.now() + expect([...finalOutputs(sql).starRaw("ssn")]).toEqual(["customers.ssn"]) + expect(performance.now() - t0).toBeLessThan(1000) + }) test("`refCovered` matches an unqualified column over a join to its single-table ref", () => { expect(refCovered("customers|orders.email", new Set(["customers.email"]))).toBe(true) // The reverse is not covered: the base never said which table it read. From 1552676a8a2f263c2450bea5a87d1728bc4d7f34 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 15:49:47 +0530 Subject: [PATCH 51/81] fix(review): read an unquoted `interval 1 day` as a constant BigQuery's `interval ` (and `interval '2' hour`) recorded its unit word as a column read (`customers.day`). A numeric or string interval with an optional date-part unit is now part of the constant; `interval x day` over a column still reads `x`. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/rule-catalog.ts | 7 ++++--- .../opencode/test/altimate/review-rule-catalog.test.ts | 8 +++++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index e13f2a20e7..06acf112c4 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -309,10 +309,11 @@ const EXPR_KEYWORDS = new Set( " ", ), ) -// A typed literal (`date '2024-01-01'`, `timestamp '…'`, `interval '1 day'`): its -// type word is part of the constant, not a column. +// A typed literal (`date '2024-01-01'`, `timestamp '…'`, `interval '1 day'`, +// BigQuery `interval 1 day`): its type and unit words are part of the constant, +// not columns. const TYPED_LITERAL = - /(? { "select date '2024-01-01' as dob,", " timestamp '2024-01-01 00:00:00' as signup_at,", " interval '1 day' as gap,", + " interval 1 day as gap_bq,", + " interval '2' hour as gap_unit,", + " c.signup_at + interval 3 day as later,", " date_trunc('day', c.signup_date) as d,", " concat(time, ' ', zone) as t", "from customers c", @@ -312,9 +315,12 @@ describe("rawColumnExposures", () => { expect([...out.reads.get("dob")!]).toEqual([]) expect([...out.reads.get("signup_at")!]).toEqual([]) expect([...out.reads.get("gap")!]).toEqual([]) + expect([...out.reads.get("gap_bq")!]).toEqual([]) + expect([...out.reads.get("gap_unit")!]).toEqual([]) + expect([...out.reads.get("later")!]).toEqual(["customers.signup_at"]) expect([...out.reads.get("d")!]).toEqual(["customers.signup_date"]) expect([...out.reads.get("t")!].sort()).toEqual(["customers.time", "customers.zone"]) - expect(selectItems(sql).filter((i) => i.constant).map((i) => i.name)).toEqual(["dob", "signup_at", "gap"]) + expect(selectItems(sql).filter((i) => i.constant).map((i) => i.name)).toEqual(["dob", "signup_at", "gap", "gap_bq", "gap_unit"]) }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" From 219f3e81d879d681576aadf1147ca05c38c84179 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:08:23 +0530 Subject: [PATCH 52/81] fix(review): judge a base-exposed PII output by its source columns MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two fallbacks in `isBaseExposedOutput` matched by name or text alone: - The signature fallback (same item text, same derived-query bodies) did not hold the source tables, so `lower(email) as email` moved from `customers` to `spouses` matched the base. It now also needs every resolved head read to be one the base's name read (`refCovered`, environment-aware). - A head name passed through a plain `*` counted as exposed whenever the base had the name, so `select email from customers` → `select * from spouses` was hidden. The head `*` is now resolved with `starRaw` and every ref must be one a base PII output exposed raw; an unresolved `*` is reported. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 28 +++++++++---- .../opencode/test/altimate/review.test.ts | 40 +++++++++++++++++++ 2 files changed, 61 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 4da1b1fa4a..5a2c6b1042 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1289,10 +1289,12 @@ export async function runReview(input: OrchestrateInput): Promise) => { const head = outputs(file, "new") const rawColumns = head.raw.get(name) @@ -1306,13 +1308,25 @@ export async function runReview(input: OrchestrateInput): Promise refCovered(ref, exposed, envOf(file)))) 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 + // 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, envOf(file))) const baseSigs = base.signatures.get(name) - return !!baseSigs && [...(head.signatures.get(name) ?? [])].every((sig) => baseSigs.has(sig)) + return sameReads && !!baseSigs && [...(head.signatures.get(name) ?? [])].every((sig) => baseSigs.has(sig)) } // Unresolved only through a plain `*`: a shape the parser does not model (a - // parenthesised top-level union, `* except (…)`) is reported. + // parenthesised top-level union, `* except (…)`) is reported. A `*` the + // parser resolves is base-exposed only when every source column it passes + // the name through was one a base PII output exposed raw. if (!head.passthrough) return false - return base.raw.has(name) || (!base.names.has(name) && base.passthrough) + const starRefs = head.starRaw(name) + const exposed = baseRawPii(file) + return starRefs.size > 0 && [...starRefs].every((ref) => refCovered(ref, exposed, envOf(file))) } for (const ctx of ctxByPath.values()) { const tasks: Promise[] = [] diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 6aec89b6d6..115bf73501 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2592,6 +2592,46 @@ describe("orchestrate", () => { ) }) + test("a computed PII output read from another table is new even when its text matches the base", async () => { + const base = "select customer_id,\n lower(email) as email\nfrom customers" + const head = base.replace("from customers", "from spouses") + expectReportedPii(await piiRuns(head, base, "-from customers\n+from spouses\n", ["email"]), ["email"], "none") + // Control: the same computation over the same table is not new. + const same = base.replace("lower(email)", "lower( email )") + for (const { reviewers, env } of await piiRuns(same, base, "- lower(email) as email\n+ lower( email ) as email\n", ["email"])) + expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) + }) + + test("a head `*` over another table does not inherit the base's named PII column", async () => { + const runs = async (head: string, base: string, diff: string) => { + const out: Array<{ reviewers: string[]; env: Awaited> }> = [] + for (const reviewers of [["pii_exposure"], [], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: [{ path: "models/marts/m.sql", status: "modified", diff }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + // detectPii sees the table's columns through `*`, as the real engine does with a schema. + runner: { + ...piiRunner(["email"]), + async detectPii(sql: string) { + return { columns: /\bemail\b|select\s+\*/i.test(sql) ? ["email"] : [] } + }, + }, + getContent: content(head, base), + }) + out.push({ reviewers, env }) + } + return out + } + const base = "select customer_id,\n email\nfrom customers" + const diff = "-select customer_id,\n- email\n-from customers\n+select *\n+from spouses\n" + expectReportedPii(await runs("select *\nfrom spouses", base, diff), ["email"], "none") + // Control: `*` over the same table is not new. + for (const { reviewers, env } of await runs("select *\nfrom customers", base, diff.replace("from spouses", "from customers"))) + expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) + }) + test("a head column pinned to one table is new when the base read it unqualified over a join", async () => { // Base `ssn` over customers ⋈ spouses does not say which table it came from. const base = "select customer_id,\n ssn\nfrom customers c\njoin spouses s using (customer_id)" From eb54e51a6511a110813f2e1a857e1cae817a971c Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:08:23 +0530 Subject: [PATCH 53/81] fix(review): keep string-literal case in output signatures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signatures lowercased the whole item text, so `regexp_replace(email, '[a-z]', '*')` → `'[A-Z]'` (which stops masking upper-case letters) compared equal and the PII output counted as already exposed. Keywords and identifiers are still lowercased; string literals keep their case. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/rule-catalog.ts | 9 +++++++-- packages/opencode/test/altimate/review.test.ts | 10 ++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 06acf112c4..d0729aa373 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -746,6 +746,11 @@ export function refCovered(ref: string, exposed: Set, env?: RelationPref return false } +/** `sql` lowercased except inside string literals, whose case can change what + * an expression does (`regexp_replace(email, '[a-z]', '*')`). */ +const lowerOutsideLiterals = (sql: string) => + sql.replace(/'(?:[^']|'')*'|[^']+/g, (m) => (m.startsWith("'") ? m : m.toLowerCase())) + /** The model's final output: every name it resolves, the source columns each * exposes raw (as `rawColumnExposures`), and how each is computed. */ export function finalOutputs(sql: string): FinalOutputs { @@ -863,7 +868,7 @@ 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, [`${item.exact.toLowerCase()}\u0001${bodies.join("\u0002")}`]) + addTo(signatures, name, [`${lowerOutsideLiterals(item.exact)}\u0001${bodies.join("\u0002")}`]) if (item.rawColumn) { const refs = resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen) addTo(raw, name, refs.raw) @@ -878,7 +883,7 @@ export function finalOutputs(sql: string): FinalOutputs { } } for (const [n, cols] of raw) if (!cols.size) raw.delete(n) - const body = [scopeItems.map((i) => i.exact.toLowerCase()).join(","), ...[...readBodies].sort()].join("\u0003") + const body = [scopeItems.map((i) => lowerOutsideLiterals(i.exact)).join(","), ...[...readBodies].sort()].join("\u0003") const result = { raw, names, signatures, reads, stars, body } memo.set(scope, result) return result diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 115bf73501..11dd943a42 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2632,6 +2632,16 @@ describe("orchestrate", () => { expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) }) + test("a masking literal whose case changed is a different computation", async () => { + const base = "select customer_id,\n regexp_replace(email, '[a-z]', '*') as email\nfrom customers" + const head = base.replace("'[a-z]'", "'[A-Z]'") + expectReportedPii( + await piiRuns(head, base, "- regexp_replace(email, '[a-z]', '*') as email\n+ regexp_replace(email, '[A-Z]', '*') as email\n", ["email"]), + ["email"], + "none", + ) + }) + test("a head column pinned to one table is new when the base read it unqualified over a join", async () => { // Base `ssn` over customers ⋈ spouses does not say which table it came from. const base = "select customer_id,\n ssn\nfrom customers c\njoin spouses s using (customer_id)" From e0e3ba0a2bf37a1761abb77b1f76ac8059c93f15 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:08:23 +0530 Subject: [PATCH 54/81] fix(review): keep a regex PII twin's severity when the raw base cannot expose it Without a compiled base every regex PII twin became a non-blocking warning of unknown confidence, including a column the PR plainly adds. The raw base still proves a column new when the column and its alias appear nowhere in it, no select item is a `*`, and its only Jinja expressions are `ref`, `source`, `config` or `this`. Such a twin now keeps its severity. Any other raw base (a `*`, `dbt_utils.star`, a `{{ col }}` loop) is still undecided. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 26 ++++++++++++++--- .../opencode/test/altimate/review.test.ts | 29 +++++++++++++++++++ 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 5a2c6b1042..28e820526a 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1107,6 +1107,20 @@ interface ModelContext { complex?: boolean } +/** + * The raw (uncompiled) base cannot expose any of `names`: none appears in it as + * a word, no select item is a `*`, and its only Jinja expressions are `ref`, + * `source`, `config` or `this`. A macro (`dbt_utils.star(…)`), a variable or a + * `{{ col }}` loop could emit any column, so any other expression proves nothing. + */ +function rawBaseLacks(oldSql: string | undefined, names: string[]): boolean { + if (!oldSql || !names.length) return false + const plain = /^\{\{-?\s*(?:(?:ref|source|config)\s*\([^{}]*\)|this)\s*-?\}\}$/ + if (!(oldSql.match(/\{\{[\s\S]*?\}\}/g) ?? []).every((e) => plain.test(e))) return false + if (selectItems(oldSql).some((i) => /(?:^|\.)\*(?:\s|$)/.test(i.text))) return false + return names.every((n) => !new RegExp(`(? { const reviewable = filterChangedFiles(input.changedFiles, input.rubric.exclusions.excludeGlobs, input.layout) const dialect = input.config.dialect @@ -1623,12 +1637,16 @@ export async function runReview(input: OrchestrateInput): Promise [it.column, it.alias])] + if (rawBaseLacks(ctx.oldSql, names.filter((n): n is string => !!n))) continue + merged[i] = { ...f, severity: f.severity === "critical" ? "warning" : f.severity, confidence: "unknown" } } // AI reviewer lane — runs AFTER the deterministic lanes so it can be GROUNDED diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 11dd943a42..ca9744ce14 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -3120,6 +3120,35 @@ describe("orchestrate", () => { } }) + test("without a compiled base, a regex PII twin keeps its severity when the raw base cannot expose the column", async () => { + const files: ChangedFile[] = MARTS.map((path) => ({ path, status: "modified", diff: "+ ssn\n" })) + const head = "select customer_id,\n ssn\nfrom {{ ref('customers') }}" + const run = (base: string) => + runReview({ + changedFiles: files, + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content(head, base), + }) + // The raw base names no `ssn`, reads no `*` and renders only `ref(…)`: the column is new. + const env = await run("select customer_id\nfrom {{ ref('customers') }}") + const twins = env.findings.filter(isTwin) + expect(twins.length).toBeGreaterThan(0) + expect(twins.some((f) => f.severity === "critical" && f.confidence !== "unknown")).toBe(true) + expect(env.verdict).toBe("REQUEST_CHANGES") + // A raw base that could expose it stays undecided: a `*`, or a macro that emits columns. + for (const base of [ + "select *\nfrom {{ ref('customers') }}", + "select {{ dbt_utils.star(ref('customers')) }}\nfrom {{ ref('customers') }}", + ]) { + const undecided = await run(base) + expect(undecided.findings.filter(isTwin).every((f) => f.severity === "warning" && f.confidence === "unknown")).toBe(true) + expect(undecided.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" }], From 0212e2eaa0e820f134e652cbbccd4f9e15f80f99 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:08:40 +0530 Subject: [PATCH 55/81] fix(review): update only a summary comment this token's account posted The prior summary was the first comment from anyone carrying the review marker, and `updateComment` returns that comment's original author, which then became the bot login used to dedup inline findings. A maintainer who posted the marker first could therefore suppress findings with their own comments. The prior summary must now come from the authenticated account (a PAT), or from a `Bot` account when the token cannot read `/user` (an app or Actions token); otherwise a new summary is created. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/post-github.ts | 17 +++++++- .../test/altimate/review-noise.test.ts | 41 +++++++++++++++++-- 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index 96332d7792..96ea5dde08 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -107,13 +107,26 @@ export async function postGitHubReview( issue_number: prNumber, per_page: 100, }) - const prior = existing.find((c) => c.body?.includes(REVIEW_MARKER)) + // Only a summary this token's own account posted is ours to update: anyone + // with edit rights can post the marker, and `updateComment` returns the + // comment's original author. The account is the authenticated user (a PAT); + // an app/Actions token cannot read `/user`, and then only a Bot account's + // comment counts (a person's account is never type `Bot`). + let selfLogin: string | undefined + try { + selfLogin = (await octo.rest.users.getAuthenticated()).data.login + } catch { + /* app or Actions token */ + } + const prior = existing.find( + (c) => c.body?.includes(REVIEW_MARKER) && (selfLogin ? c.user?.login === selfLogin : c.user?.type === "Bot"), + ) 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 + const botLogin = selfLogin ?? upserted.data.user?.login // 2. Post a review. `env.verdict` arrives already mode-gated from // buildEnvelope (comment mode softened REQUEST_CHANGES → COMMENT upstream); diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index a094f22200..6ede812a9f 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -627,7 +627,9 @@ describe("postGitHubReview", () => { listFails?: boolean files?: Array<{ filename: string; patch?: string }> reviewComments?: Array<{ body: string; user?: { login: string } }> - issueComments?: Array<{ id: number; body: string }> + issueComments?: Array<{ id: number; body: string; user?: { login: string; type?: string } }> + /** The token's account as `/user` reports it; unset, the call fails like an app token's. */ + self?: string createReview?: (call: number) => unknown } = {}, ) { @@ -659,9 +661,17 @@ describe("postGitHubReview", () => { summaryCalls.push("create") return { data: { id: 1, user: { login: BOT } } } }, + // GitHub returns the comment's original author, not the token's account. updateComment: async (p: { comment_id: number }) => { summaryCalls.push(`update ${p.comment_id}`) - return { data: { id: p.comment_id, user: { login: BOT } } } + const author = opts.issueComments?.find((c) => c.id === p.comment_id)?.user ?? { login: BOT } + return { data: { id: p.comment_id, user: author } } + }, + }, + users: { + getAuthenticated: async () => { + if (!opts.self) throw new Error("Resource not accessible by integration") + return { data: { login: opts.self } } }, }, pulls: { @@ -692,7 +702,7 @@ describe("postGitHubReview", () => { const filler = (n: number) => Array.from({ length: n }, (_, i) => ({ body: `other ${i}`, user: { login: "someone" } })) const { octo, reviewCalls, summaryCalls } = fakeOcto({ // Each item that matters is on page two or later. - issueComments: [...filler(3).map((c, i) => ({ id: 100 + i, body: c.body })), { id: 42, body: `${REVIEW_MARKER}\nold` }], + issueComments: [...filler(3).map((c, i) => ({ id: 100 + i, body: c.body })), { id: 42, body: `${REVIEW_MARKER}\nold`, user: { login: BOT, type: "Bot" } }], reviewComments: [...filler(3), { body: first.body, user: { login: BOT } }], files: [ { filename: "models/x.sql", patch: PATCH }, @@ -831,6 +841,31 @@ describe("postGitHubReview", () => { expect(again.inlineSkippedAsPosted).toBe(1) }) + test("a summary marker someone else posted is not this bot's summary", async () => { + const env = buildEnvelope({ findings: [finding({ startLine: 3, title: "m: a" })], tier: "lite", mode: "comment" }) + const [first] = inlineComments(env, new Set(), undefined) + // A maintainer posts the marker first, then a comment carrying the finding's marker. + const planted = { + issueComments: [{ id: 7, body: `${REVIEW_MARKER}\nplanted`, user: { login: "maintainer", type: "User" } }], + reviewComments: [{ body: first.body, user: { login: "maintainer" } }], + } + const app = fakeOcto(planted) + const r = await postGitHubReview(env, target, app.octo) + expect(app.summaryCalls).toEqual(["create"]) + expect(r.inlineSkippedAsPosted).toBe(0) + expect(app.reviewCalls[0].comments.map((c: { line: number }) => c.line)).toEqual([3]) + // A PAT run: only the authenticated account's summary is updated. + const pat = fakeOcto({ ...planted, self: "local-dev" }) + await postGitHubReview(env, target, pat.octo) + expect(pat.summaryCalls).toEqual(["create"]) + const own = fakeOcto({ + issueComments: [{ id: 8, body: `${REVIEW_MARKER}\nmine`, user: { login: "local-dev", type: "User" } }], + self: "local-dev", + }) + await postGitHubReview(env, target, own.octo) + expect(own.summaryCalls).toEqual(["update 8"]) + }) + test("a deleted file gets no inline comment; a pure rename without a patch keeps its comments", async () => { const env = buildEnvelope({ findings: [ From 139da8a7318341ebaa2dd7b1824f9f32f5b854e5 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:08:40 +0530 Subject: [PATCH 56/81] fix(review): clip a budgeted bullet's title so the first critical always fits Bodies were clipped but titles were not, and the broad PII title lists every column. On a wide model one critical bullet could exceed the room left after the fixed notes. The listing then stopped, and the comment said "Changes requested" while hiding the finding that blocks. Budgeted titles are now clipped to 200 characters, never inside a code span; local output keeps the whole title. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/format.ts | 17 +++++++++++++++-- .../opencode/test/altimate/review-noise.test.ts | 17 +++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 6c74a0e2e1..8a117fc25f 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -223,6 +223,18 @@ function distinguishingValues(f: Finding): string[] { // A budgeted bullet's body is clipped to this, so one long finding cannot fill // the comment and hide the titles of the most severe findings. const BULLET_BODY_MAX = 600 +// As for the title (a wide model's PII title lists every column), so a single +// bullet always fits the room the capped notes leave. +const BULLET_TITLE_MAX = 200 + +/** `clip`, never ending inside a code span: an unpaired backtick is cut back. */ +function clipTitle(text: string, max: number): string { + const clipped = clip(text, max) + if (clipped === text) return clipped + const body = clipped.slice(0, -1) + const ticks = (body.match(/`/g) ?? []).length + return ticks % 2 ? `${body.slice(0, body.lastIndexOf("`")).trimEnd()}…` : clipped +} /** 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 @@ -230,6 +242,7 @@ const BULLET_BODY_MAX = 600 function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; count: number }> { // Budgeted (grouped) output clips bodies; local output keeps them whole. const bodyOf = (text: string) => (group ? clip(text, BULLET_BODY_MAX) : text) + const titleOf = (text: string) => (group ? clipTitle(text, BULLET_TITLE_MAX) : text) const groups = new Map() for (const f of items) { // The body is part of the key: one rule with different messages (e.g. a @@ -269,7 +282,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou 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` + + `- **${titleOf(groupKeyTitle(g[0]))}** — ${g.length} findings across ${names.length} model(s): ${shown}${more} \n` + ` ${body} \n${detail} ${g[0].category}${unverified}`, count: g.length, }) @@ -278,7 +291,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou for (const f of g) { const loc = f.file + (f.startLine ? `:${f.startLine}` : "") out.push({ - text: `- **${f.title}** \n ${bodyOf(oneLine(f.body))} \n \`${loc}\`${f.degraded ? " · _unverified_" : ""} · ${f.category}`, + text: `- **${titleOf(f.title)}** \n ${bodyOf(oneLine(f.body))} \n \`${loc}\`${f.degraded ? " · _unverified_" : ""} · ${f.category}`, count: 1, }) } diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 6ede812a9f..6ee9fd9700 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -334,6 +334,23 @@ describe("summary grouping and budget", () => { expect(renderSummary(env, { maxChars: Infinity })).toContain("m199: distinct issue number 199") }) + test("a critical whose title lists hundreds of columns is still shown, its title clipped", () => { + const cols = Array.from({ length: 300 }, (_, i) => `column_number_${i}`) + const f = finding({ + severity: "critical", + category: "pii_exposure", + title: `wide: exposes PII columns (${cols.join(", ")})`, + body: "Confirm masking. ".repeat(60), + }) + const env = buildEnvelope({ findings: [f], tier: "full", mode: "gate" }) + const md = renderSummary(env) + expect(md.length).toBeLessThanOrEqual(SUMMARY_BUDGET_CHARS) + expect(md).toContain("wide: exposes PII columns (column_number_0, ") + expect(md).not.toMatch(/more finding\(s\) not shown/) + // Local output keeps the whole title. + expect(renderSummary(env, { maxChars: Infinity })).toContain("column_number_299)") + }) + test("a critical that does not fit stops the listing: no later, shorter finding jumps ahead of it", () => { // Twelve criticals with long bodies (each clipped, still ~700 chars) cannot // all fit; the short suggestions after them must not be listed instead. From b637b11c749821b31ea143b17e2a2d36cf0d74cb Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:13:32 +0530 Subject: [PATCH 57/81] fix(review): retry a transient `/user` failure instead of guessing the account Any `/user` error fell back to the app-token rule (only a `Bot` account's summary counts), so a PAT run that hit a 5xx or network error missed its own summary and posted a duplicate. Only 401/403/404 now mean "this token cannot read `/user`". Any other failure is retried once, then the post fails before anything is published, as when listing comments fails. Guessing would create a duplicate summary and re-post every inline finding. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/post-github.ts | 27 +++++++++++++------ .../test/altimate/review-noise.test.ts | 21 +++++++++++++-- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index 96ea5dde08..f825f6ab45 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -89,6 +89,20 @@ function describeError(e: any): string { /** Headline of a review this bot posted (see verdictHeadline). */ const BOT_REVIEW_RE = /(Approved|Reviewed with comments|Changes requested)\b.*\((trivial|lite|full) tier/ +/** The token's own login, or `undefined` for a token that cannot read `/user` + * (an app or Actions token). A transient failure is retried once, then thrown. */ +async function authenticatedLogin(octo: Octokit): Promise { + for (let attempt = 0; ; attempt++) { + try { + return (await octo.rest.users.getAuthenticated()).data.login + } catch (e: any) { + const status = e?.status ?? e?.response?.status + if (status === 401 || status === 403 || status === 404) return undefined + if (attempt > 0) throw e + } + } +} + export async function postGitHubReview( env: VerdictEnvelope, target: GitHubTarget, @@ -110,14 +124,11 @@ export async function postGitHubReview( // Only a summary this token's own account posted is ours to update: anyone // with edit rights can post the marker, and `updateComment` returns the // comment's original author. The account is the authenticated user (a PAT); - // an app/Actions token cannot read `/user`, and then only a Bot account's - // comment counts (a person's account is never type `Bot`). - let selfLogin: string | undefined - try { - selfLogin = (await octo.rest.users.getAuthenticated()).data.login - } catch { - /* app or Actions token */ - } + // an app/Actions token cannot read `/user` (401/403/404), and then only a Bot + // account's comment counts (a person's account is never type `Bot`). Any + // other failure is retried once, then fails the post: guessing would create + // a duplicate summary and re-post every inline finding. + const selfLogin = await authenticatedLogin(octo) const prior = existing.find( (c) => c.body?.includes(REVIEW_MARKER) && (selfLogin ? c.user?.login === selfLogin : c.user?.type === "Bot"), ) diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 6ee9fd9700..9cfbf960c8 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -645,8 +645,10 @@ describe("postGitHubReview", () => { files?: Array<{ filename: string; patch?: string }> reviewComments?: Array<{ body: string; user?: { login: string } }> issueComments?: Array<{ id: number; body: string; user?: { login: string; type?: string } }> - /** The token's account as `/user` reports it; unset, the call fails like an app token's. */ + /** The token's account as `/user` reports it; unset, the call fails like an app token's (403). */ self?: string + /** Statuses `/user` fails with first, one per call, before answering as above. */ + selfErrors?: number[] createReview?: (call: number) => unknown } = {}, ) { @@ -687,7 +689,8 @@ describe("postGitHubReview", () => { }, users: { getAuthenticated: async () => { - if (!opts.self) throw new Error("Resource not accessible by integration") + const status = opts.selfErrors?.shift() ?? (opts.self ? undefined : 403) + if (status) throw Object.assign(new Error(status === 403 ? "Resource not accessible by integration" : "Bad gateway"), { status }) return { data: { login: opts.self } } }, }, @@ -883,6 +886,20 @@ describe("postGitHubReview", () => { expect(own.summaryCalls).toEqual(["update 8"]) }) + test("a transient `/user` failure retries once, then fails the post rather than duplicating the summary", async () => { + const env = buildEnvelope({ findings: [finding({ startLine: 3, title: "m: a" })], tier: "lite", mode: "comment" }) + const mine = { issueComments: [{ id: 8, body: `${REVIEW_MARKER}\nmine`, user: { login: "local-dev", type: "User" } }], self: "local-dev" } + // One 502, then the PAT's own login: its summary is updated in place. + const once = fakeOcto({ ...mine, selfErrors: [502] }) + await postGitHubReview(env, target, once.octo) + expect(once.summaryCalls).toEqual(["update 8"]) + // Two failures: nothing is created or posted. + const twice = fakeOcto({ ...mine, selfErrors: [502, 503] }) + await expect(postGitHubReview(env, target, twice.octo)).rejects.toThrow() + expect(twice.summaryCalls).toEqual([]) + expect(twice.reviewCalls).toEqual([]) + }) + test("a deleted file gets no inline comment; a pure rename without a patch keeps its comments", async () => { const env = buildEnvelope({ findings: [ From 48f53c8f432af27d772f615b53858ed2723632d0 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 16:14:34 +0530 Subject: [PATCH 58/81] fix(review): compare output signatures by source, not table alias MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signatures held the item text as written, so renaming only a table alias inside a masked expression (`md5(c.ssn) as ssn from customers c` → `md5(cu.ssn) as ssn from customers cu`) looked like a new computation. That made a critical PII finding. In signatures and derived-query bodies, each FROM/JOIN alias is now replaced by the source it names: a table by its own name, a CTE or subquery by its scope. The database/schema is left out because the `reads` check, environment-aware through `refCovered`, already requires the same source columns, so the same alias moved to another table is still reported. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/rule-catalog.ts | 24 +++++++++++++++++-- .../opencode/test/altimate/review.test.ts | 15 ++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index d0729aa373..d835e5faa4 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -830,6 +830,26 @@ 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 own 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) => { + 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) + 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}` + }), + ) + } const resolve = (scope: string, seen: Set): ScopeOutputs => { const cached = memo.get(scope) if (cached) return cached @@ -868,7 +888,7 @@ 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, [`${lowerOutsideLiterals(item.exact)}\u0001${bodies.join("\u0002")}`]) + addTo(signatures, name, [`${signatureText(item, scope)}\u0001${bodies.join("\u0002")}`]) if (item.rawColumn) { const refs = resolveRef(scope, item.branch, item.rawQualifier, item.rawColumn, seen) addTo(raw, name, refs.raw) @@ -883,7 +903,7 @@ export function finalOutputs(sql: string): FinalOutputs { } } for (const [n, cols] of raw) if (!cols.size) raw.delete(n) - const body = [scopeItems.map((i) => lowerOutsideLiterals(i.exact)).join(","), ...[...readBodies].sort()].join("\u0003") + const body = [scopeItems.map((i) => signatureText(i, scope)).join(","), ...[...readBodies].sort()].join("\u0003") const result = { raw, names, signatures, reads, stars, body } memo.set(scope, result) return result diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index ca9744ce14..9808174821 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2632,6 +2632,21 @@ describe("orchestrate", () => { expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) }) + test("renaming a table alias inside a masked output is not new exposure", async () => { + const base = "select c.customer_id,\n md5(c.ssn) as ssn\nfrom customers c" + const head = "select cu.customer_id,\n md5(cu.ssn) as ssn\nfrom customers cu" + const diff = "-select c.customer_id,\n- md5(c.ssn) as ssn\n-from customers c\n+select cu.customer_id,\n+ md5(cu.ssn) as ssn\n+from customers cu\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: [] }) + // Inside a CTE the masked body is compared the same way. + const cte = (a: string) => `with k as (select ${a}.customer_id, md5(${a}.ssn) as ssn from customers ${a})\nselect customer_id,\n ssn\nfrom k` + for (const { reviewers, env } of await piiRuns(cte("cu"), cte("c"), "-with k as (select c.customer_id, md5(c.ssn) as ssn from customers c)\n+with k as (select cu.customer_id, md5(cu.ssn) as ssn from customers cu)\n", ["ssn"])) + expect({ reviewers, pii: env.findings.filter((f) => f.category === "pii_exposure") }).toEqual({ reviewers, pii: [] }) + // Control: the same alias moved to another table is new. + const moved = "select cu.customer_id,\n md5(cu.ssn) as ssn\nfrom spouses cu" + expectReportedPii(await piiRuns(moved, base, diff.replace("+from customers cu", "+from spouses cu"), ["ssn"]), ["ssn"], "none") + }) + test("a masking literal whose case changed is a different computation", async () => { const base = "select customer_id,\n regexp_replace(email, '[a-z]', '*') as email\nfrom customers" const head = base.replace("'[a-z]'", "'[A-Z]'") From 9f5954a2613b48c17ac1ad5f22ec45fd83593d2f Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 17:19:17 +0530 Subject: [PATCH 59/81] fix(review): drop the `rawColumnExposures` wrapper It only returned `finalOutputs(sql).raw`, and only tests called it. Its doc comment (what a raw exposure is and how refs resolve) now sits on `FinalOutputs.raw`, and the tests read `finalOutputs(sql).raw` directly. Behaviour is unchanged. The `signatures` doc now mentions the alias normalisation. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/rule-catalog.ts | 49 ++++++++---------- .../test/altimate/review-rule-catalog.test.ts | 51 ++++++++++--------- 2 files changed, 48 insertions(+), 52 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index d835e5faa4..7075627662 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -626,7 +626,24 @@ const STAR = new RegExp(String.raw`^(?:${SEGMENT}\.)*\*$`) /** The model's final output, as `finalOutputs` resolves it. */ export interface FinalOutputs { - /** Per output name, the `source.column` refs it exposes RAW (see `rawColumnExposures`). */ + /** + * Per output name of the model (its FINAL projection, never a CTE's or a + * nested query's own aliases), the source columns it exposes RAW under that + * name, each as `source.column` where the source is the table (its full + * relation name as written) the column is read from: `c.ssn as tax_ref` with + * `customers c` → `tax_ref: {customers.ssn}`, so the same column name from + * another table (`s.ssn` with `spouses s`, or `restricted.customers` vs + * `public.customers`) is a different exposure. A qualifier resolves + * through its own FROM/JOIN source only; a column read from a CTE or a FROM + * subquery takes that scope's exposure for it (masked there → nothing raw), and + * `*` over them takes all of theirs. An unqualified column resolves through the + * CTEs/subqueries that output it, else the single table read (several tables → + * one combined `a|b.column` ref). A qualifier that matches no source gets a ref + * that matches nothing on the other side. A later set-operation branch takes the + * first branch's name at the same position. An item that wraps the column in any + * other function or expression (`sha2(c.ssn)`, `left(c.ssn, 4)`, `case …`, + * `a || b`) exposes nothing raw and is left out. + */ raw: Map> /** Every output name the final projection resolves. */ names: Set @@ -640,8 +657,8 @@ export interface FinalOutputs { * unqualified one), for `refCovered`'s environment check. */ prefixes: Set /** Per output name, a signature of how it is computed: the item text (string - * literals included) 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. */ + * 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, every `source.column` ref its value is computed from, raw * or not, resolved like `raw` (`lower(s.ssn) as email` with `spouses s` → @@ -656,28 +673,6 @@ interface ScopeOutputs extends Omit> { - return finalOutputs(sql).raw -} - let unresolvedRefs = 0 const splitRef = (ref: string) => { @@ -721,7 +716,7 @@ function sameTable(h: string, b: string, env?: RelationPrefixes): boolean { /** * `ref` is one of the `exposed` source columns. An unqualified column read over - * several tables (`customers|orders.email`, see `rawColumnExposures`) comes from + * several tables (`customers|orders.email`, see `FinalOutputs.raw`) comes from * exactly one of them (the query would be ambiguous otherwise), so it is * covered by a single-table ref to one of its members. The reverse is not: a * base combined ref does not say which table the column came from, so a head @@ -752,7 +747,7 @@ const lowerOutsideLiterals = (sql: string) => sql.replace(/'(?:[^']|'')*'|[^']+/g, (m) => (m.startsWith("'") ? m : m.toLowerCase())) /** The model's final output: every name it resolves, the source columns each - * exposes raw (as `rawColumnExposures`), and how each is computed. */ + * exposes raw (`raw`), and how each is computed. */ export function finalOutputs(sql: string): FinalOutputs { const { items, sources } = parseSelects(sql) const byScope = new Map() diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index a23e743b18..3c7c6b4569 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -4,7 +4,6 @@ import { ruleMatches, inputFromExample, finalOutputs, - rawColumnExposures, refCovered, selectItemColumns, selectItems, @@ -66,11 +65,13 @@ describe("selectItemColumns", () => { }) }) -describe("rawColumnExposures", () => { +const rawOf = (sql: string) => finalOutputs(sql).raw + +describe("finalOutputs().raw", () => { const asObject = (m: Map>) => Object.fromEntries([...m].map(([k, v]) => [k, [...v].sort()])) test("reads the final projection only, not a CTE's own aliases", () => { const sql = "with h as (\n select ssn as contact\n from customers\n)\nselect c.email as contact from customers c" - expect(asObject(rawColumnExposures(sql))).toEqual({ contact: ["customers.email"] }) + expect(asObject(rawOf(sql))).toEqual({ contact: ["customers.email"] }) }) test("resolves a final column through the CTE it reads, and `*` over a CTE", () => { const sql = [ @@ -78,42 +79,42 @@ describe("rawColumnExposures", () => { "final as (select id, sha2(phone) as phone, ssn, email as contact from src)", "select * from final", ].join("\n") - expect(asObject(rawColumnExposures(sql))).toEqual({ + expect(asObject(rawOf(sql))).toEqual({ id: ["{{ref('customers')}}.id"], ssn: ["{{ref('customers')}}.ssn"], contact: ["{{ref('customers')}}.email"], }) - expect(asObject(rawColumnExposures("with b as (select email as contact from c) select contact from b"))).toEqual({ + expect(asObject(rawOf("with b as (select email as contact from c) select contact from b"))).toEqual({ contact: ["c.email"], }) }) test("parses a select item whose alias is on another line", () => { const sql = "select c.customer_id,\n c.ssn\n as tax_ref\nfrom customers c" - expect(asObject(rawColumnExposures(sql))).toEqual({ customer_id: ["customers.customer_id"], tax_ref: ["customers.ssn"] }) + expect(asObject(rawOf(sql))).toEqual({ customer_id: ["customers.customer_id"], tax_ref: ["customers.ssn"] }) }) test("accepts quoted identifiers", () => { - expect(asObject(rawColumnExposures('select "c"."ssn" as "tax_ref" from customers "c"'))).toEqual({ tax_ref: ["customers.ssn"] }) + expect(asObject(rawOf('select "c"."ssn" as "tax_ref" from customers "c"'))).toEqual({ tax_ref: ["customers.ssn"] }) }) test("accepts an alias without AS, and not a trailing keyword", () => { const sql = "select c.ssn tax_ref, cast(c.dob as date) dob_day, case when x then y end, sha2(c.email) em from c" - expect(asObject(rawColumnExposures(sql))).toEqual({ tax_ref: ["c.ssn"], dob_day: ["c.dob"] }) + expect(asObject(rawOf(sql))).toEqual({ tax_ref: ["c.ssn"], dob_day: ["c.dob"] }) }) test("names a later set-operation branch by the first branch's position", () => { const sql = "select id, ssn as tax_ref from a\nunion all\nselect id, email from b" - expect(asObject(rawColumnExposures(sql))).toEqual({ id: ["a.id", "b.id"], tax_ref: ["a.ssn", "b.email"] }) + expect(asObject(rawOf(sql))).toEqual({ id: ["a.id", "b.id"], tax_ref: ["a.ssn", "b.email"] }) }) test("keeps the source table, so a same-named column from another table is distinct", () => { const sql = "select c.ssn, s.ssn as spouse_ssn, schema1.employees.email from customers c, schema1.employees join spouses as s on true" - expect(asObject(rawColumnExposures(sql))).toEqual({ + expect(asObject(rawOf(sql))).toEqual({ ssn: ["customers.ssn"], spouse_ssn: ["spouses.ssn"], email: ["schema1.employees.email"], }) }) test("keeps the database and schema in the source identity", () => { - expect(asObject(rawColumnExposures("select ssn from restricted.customers"))).toEqual({ ssn: ["restricted.customers.ssn"] }) - expect(asObject(rawColumnExposures("select ssn from public.customers"))).toEqual({ ssn: ["public.customers.ssn"] }) - expect(asObject(rawColumnExposures('select c.ssn, customers.email from "DB"."Public"."Customers" c, raw.customers'))).toEqual({ + expect(asObject(rawOf("select ssn from restricted.customers"))).toEqual({ ssn: ["restricted.customers.ssn"] }) + expect(asObject(rawOf("select ssn from public.customers"))).toEqual({ ssn: ["public.customers.ssn"] }) + expect(asObject(rawOf('select c.ssn, customers.email from "DB"."Public"."Customers" c, raw.customers'))).toEqual({ ssn: ["db.public.customers.ssn"], email: ["raw.customers.email"], }) @@ -124,15 +125,15 @@ describe("rawColumnExposures", () => { "k as (select customer_id, sha2(ssn) as ssn from customers)", "select r.ssn as a, k.ssn as b, c.ssn as d from r join k on true join customers c on true", ].join("\n") - expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["customers.ssn"], d: ["customers.ssn"] }) + expect(asObject(rawOf(sql))).toEqual({ a: ["customers.ssn"], d: ["customers.ssn"] }) // An unknown qualifier never matches anything: it resolves to a unique ref. - expect([...(rawColumnExposures("select x.ssn from customers c").get("ssn") ?? [])][0]).toMatch(/^\?\d+\.ssn$/) + expect([...(rawOf("select x.ssn from customers c").get("ssn") ?? [])][0]).toMatch(/^\?\d+\.ssn$/) }) test("resolves through a FROM subquery under its alias", () => { - expect(asObject(rawColumnExposures("select s.ssn, s.email from (select sha2(ssn) as ssn, email from customers) s"))).toEqual({ + expect(asObject(rawOf("select s.ssn, s.email from (select sha2(ssn) as ssn, email from customers) s"))).toEqual({ email: ["customers.email"], }) - expect(asObject(rawColumnExposures("select ssn from (select * from customers) as s"))).toEqual({ ssn: ["customers.ssn"] }) + expect(asObject(rawOf("select ssn from (select * from customers) as s"))).toEqual({ ssn: ["customers.ssn"] }) }) test("only a plain `*` passes columns through; `* except (…)` does not", () => { expect(finalOutputs("select * from customers").passthrough).toBe(true) @@ -141,7 +142,7 @@ describe("rawColumnExposures", () => { }) test("a CTE with a column list is still a CTE: a renamed column resolves to nothing known", () => { const sql = "with m (id, tax) as (select customer_id, ssn from customers)\nselect tax as ssn from m" - expect([...(rawColumnExposures(sql).get("ssn") ?? [])][0]).toMatch(/^\?\d+\.tax$/) + expect([...(rawOf(sql).get("ssn") ?? [])][0]).toMatch(/^\?\d+\.tax$/) }) test("a CTE named `final` is a CTE, not the model's output", () => { // The outer `b` is the output; the CTE outputs no `b`, so it resolves to nothing known. @@ -151,13 +152,13 @@ describe("rawColumnExposures", () => { expect([...lost.raw.get("b")!][0]).toMatch(/^\?\d+\.b$/) // Masked in the CTE, selected by name or through `*`: nothing raw. const masked = "with final as (select id, md5(email) as email from customers) select id, email from final" - expect(asObject(rawColumnExposures(masked))).toEqual({ id: ["customers.id"] }) - expect(asObject(rawColumnExposures(masked.replace("select id, email from final", "select * from final")))).toEqual({ + expect(asObject(rawOf(masked))).toEqual({ id: ["customers.id"] }) + expect(asObject(rawOf(masked.replace("select id, email from final", "select * from final")))).toEqual({ id: ["customers.id"], }) // Masked in the outer list: nothing raw, and the outer names are the outputs. const outer = "with final as (select id, email from customers) select id, md5(email) as email_hash from final" - expect(asObject(rawColumnExposures(outer))).toEqual({ id: ["customers.id"] }) + expect(asObject(rawOf(outer))).toEqual({ id: ["customers.id"] }) expect([...finalOutputs(outer).names].sort()).toEqual(["email_hash", "id"]) }) test("`reads` lists the source columns a computed output is built from", () => { @@ -214,7 +215,7 @@ describe("rawColumnExposures", () => { const named = "with k as (select customer_id, sha2(ssn) as ssn from customers) select * from k join spouses s using (customer_id)" expect([...finalOutputs(named).starRaw("ssn")]).toEqual(["spouses.ssn"]) // The unqualified column read keeps its combined ref. - expect(asObject(rawColumnExposures("select ssn from customers c join spouses s using (customer_id)"))).toEqual({ + expect(asObject(rawOf("select ssn from customers c join spouses s using (customer_id)"))).toEqual({ ssn: ["customers|spouses.ssn"], }) }) @@ -255,11 +256,11 @@ describe("rawColumnExposures", () => { expect(refCovered("analytics.dbt_ci_pr_42.customers.ssn", prod)).toBe(false) }) test("`distinct on (…)` is a select prefix, not part of the first item", () => { - expect(asObject(rawColumnExposures("select distinct on (id) ssn, id from customers"))).toEqual({ + expect(asObject(rawOf("select distinct on (id) ssn, id from customers"))).toEqual({ ssn: ["customers.ssn"], id: ["customers.id"], }) - expect(asObject(rawColumnExposures("select distinct on (date_trunc('day', ts), id) c.ssn from customers c"))).toEqual({ + expect(asObject(rawOf("select distinct on (date_trunc('day', ts), id) c.ssn from customers c"))).toEqual({ ssn: ["customers.ssn"], }) }) @@ -324,6 +325,6 @@ describe("rawColumnExposures", () => { }) test("ignores commas and keywords inside literals and comments", () => { const sql = "select ssn as a, -- , email as a\n 'x, from y' as b, email as c from t" - expect(asObject(rawColumnExposures(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) + expect(asObject(rawOf(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) }) }) From 668d076869868c6ac8858688a53590a43879238a Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 17:19:59 +0530 Subject: [PATCH 60/81] fix(review): test a qualified `c.ssn` without a compiled base and a schema move MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two tests from the PR's review nits: - An added `c.ssn` over a raw Jinja base that cannot expose it, with no compiled base, blocks on the default tier and on `dbt_patterns` alone. - `analytics.customers` → `raw_restricted.customers` with one schema on each side stays quiet (it cannot be told apart from a base compiled into another environment). The same move when the base already read `raw_restricted` is reported. Co-Authored-By: Claude Opus 5.5 --- .../opencode/test/altimate/review.test.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 9808174821..9d2147a8e2 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2657,6 +2657,21 @@ describe("orchestrate", () => { ) }) + 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. + 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: [] }) + // 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") + const diffBoth = "-from analytics.customers c\n+from raw_restricted.customers c\n" + expectReportedPii(await piiRuns(headBoth, baseBoth, diffBoth, ["ssn"]), ["ssn"], "none") + }) + test("a head column pinned to one table is new when the base read it unqualified over a join", async () => { // Base `ssn` over customers ⋈ spouses does not say which table it came from. const base = "select customer_id,\n ssn\nfrom customers c\njoin spouses s using (customer_id)" @@ -3164,6 +3179,27 @@ describe("orchestrate", () => { } }) + test("without a compiled base, an added `c.ssn` over a raw base with no `ssn` still blocks", async () => { + for (const reviewers of [[], ["dbt_patterns"]]) { + const env = await runReview({ + changedFiles: MARTS.map((path) => ({ path, status: "modified" as const, diff: "-select c.customer_id\n+select c.customer_id,\n+ c.ssn\n" })), + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content( + "select c.customer_id,\n c.ssn\nfrom {{ ref('customers') }} c", + "select c.customer_id\nfrom {{ ref('customers') }} c", + ), + }) + expect({ reviewers, critical: env.findings.some((f) => f.category === "pii_exposure" && f.severity === "critical") }).toEqual({ + reviewers, + critical: true, + }) + expect({ reviewers, verdict: env.verdict }).toEqual({ reviewers, verdict: "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" }], From b6e15e51c4b8549f971d82ed8bc8295e2cf0aa45 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:03:50 +0530 Subject: [PATCH 61/81] fix(review): keep a proven-new regex PII twin past the undecided PII lanes With a compiled head and no compiled base, the broad `schema.detect_pii` lane and the diff-scoped classifier both report an unknown-confidence warning. The twin dedup dropped the regex twin against those findings before the `rawBaseLacks` check ran, so an added `c.ssn` the raw base cannot expose ended at COMMENT. - `provenNewTwin` runs the raw-base proof first; a proven twin is not deduped against the broad lane, the classifier's flagged columns or its emitted-finding file set. A column the classifier muted still drops the twin. - The test that three PII columns without a compiled base never block now uses a raw `select *` base, so its columns are really undecided. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 39 +++++++++++---- .../opencode/test/altimate/review.test.ts | 49 +++++++++++++++++-- 2 files changed, 75 insertions(+), 13 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 28e820526a..ce80d26f04 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1231,11 +1231,12 @@ export async function runReview(input: OrchestrateInput): Promise() const diffScopedPiiFindingFiles = new Set() const classifiedPiiColumnsByFile = new Map>() + const flaggedPiiColumnsByFile = new Map>() // Per file: PII columns the compiled base already exposed. Neither the broad // fallback nor the regex twins report these (this PR did not expose them). const basePiiColumnsByFile = new Map>() @@ -1384,6 +1385,10 @@ export async function runReview(input: OrchestrateInput): Promise String((f.evidence?.result as any)?.column ?? "").toLowerCase())), + ) const findings = [...diffScopedPii.findings] let basePii = new Set() if (hasOldSide(currentCtx.file) && currentCtx.engineOldSql) { @@ -1568,6 +1573,17 @@ export async function runReview(input: OrchestrateInput): Promise 0 && items.every((i) => r.base.has(itemKey(i))) } + // Without a compiled base every other PII lane is undecided (an unknown- + // confidence warning). A regex twin whose source columns the raw base cannot + // expose (`rawBaseLacks`) is proven new, so those undecided findings must not + // stand in for it: it survives their dedup and keeps its severity below. + const provenNewTwin = (f: Finding) => { + const ctx = ctxByPath.get(f.file) + if (!ctx || !hasOldSide(ctx.file) || ctx.engineOldSql) return false + const result = (f.evidence?.result ?? {}) as { column?: string; alias?: string; items?: SelectItemColumn[] } + const names = [result.column, result.alias, ...(result.items ?? []).flatMap((it) => [it.column, it.alias])] + return rawBaseLacks(ctx.oldSql, names.filter((n): n is string => !!n)) + } const merged = flat.filter((f) => { const tool = f.evidence?.tool const fallbackRule = String((f.evidence?.result as any)?.rule ?? "").replace(/_/g, "-") @@ -1581,8 +1597,9 @@ export async function runReview(input: OrchestrateInput): Promise !!c && !!classified?.has(c) && !(proven && flagged?.has(c)) + if (considered(result.column) || considered(result.alias)) return false // A column the base already exposed is not newly exposed by this PR. return !isBaseExposed(f.file, result.column, result.alias, result.line) } @@ -1608,7 +1629,7 @@ export async function runReview(input: OrchestrateInput): Promise [it.column, it.alias])] - if (rawBaseLacks(ctx.oldSql, names.filter((n): n is string => !!n))) continue + if (!ctx || !hasOldSide(ctx.file) || ctx.engineOldSql || provenNewTwin(f)) continue merged[i] = { ...f, severity: f.severity === "critical" ? "warning" : f.severity, confidence: "unknown" } } diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 9d2147a8e2..08b74941fa 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2167,8 +2167,10 @@ describe("orchestrate", () => { }) 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. + // Three head PII columns, base not compilable and its raw `*` may already + // expose them: each is a warning of undecided exposure and must not count + // toward the warning-pattern threshold. (A raw base that cannot expose them + // proves them new: see "a proven-new `c.ssn` still blocks past the undecided PII lanes".) const files: ChangedFile[] = [ { path: "models/marts/dim_customers.sql", status: "modified", diff: "+ email,\n+ ssn,\n+ phone_number\n" }, ] @@ -2195,7 +2197,7 @@ describe("orchestrate", () => { runner, getContent: content( "select customer_id, email, ssn, phone_number from customers", - "select customer_id from {{ ref('customers') }}", + "select * from {{ ref('customers') }}", ), }) const pii = env.findings.filter((f) => f.category === "pii_exposure") @@ -3200,6 +3202,47 @@ describe("orchestrate", () => { } }) + test("with a compiled head and no compiled base, a proven-new `c.ssn` still blocks past the undecided PII lanes", async () => { + // Only the head compiles, so the broad `schema.detect_pii` lane (and the + // classifier, when it flags the column) report an unknown-confidence warning. + // Those must not swallow the regex twin the raw base proves new. + const classifiers: ReviewRunner["classifyPii"][] = [ + async () => [], + async (columns) => columns.filter((c) => c === "ssn").map((column) => ({ column, classification: "SSN", confidence: 0.95 })), + ] + for (const reviewers of [[], ["dbt_patterns"]]) { + for (const [k, classify] of classifiers.entries()) { + const env = await runReview({ + changedFiles: MARTS.map((path) => ({ path, status: "modified" as const, diff: "-select c.customer_id\n+select c.customer_id,\n+ c.ssn\n" })), + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"], classify), + getContent: content( + "select c.customer_id,\n c.ssn\nfrom {{ ref('customers') }} c", + "select c.customer_id\nfrom {{ ref('customers') }} c", + ), + getCompiled: async (_f, side) => + side === "new" ? "select c.customer_id,\n c.ssn\nfrom analytics.customers c" : undefined, + }) + const critical = env.findings.some((f) => f.category === "pii_exposure" && f.severity === "critical") + expect({ reviewers, k, critical, verdict: env.verdict }).toEqual({ reviewers, k, critical: true, verdict: "REQUEST_CHANGES" }) + } + } + // A raw base that could expose the column stays undecided on the same path. + const env = await runReview({ + changedFiles: MARTS.map((path) => ({ path, status: "modified" as const, diff: "+ c.ssn\n" })), + config: { ...DEFAULT_REVIEW_CONFIG }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content("select c.customer_id,\n c.ssn\nfrom {{ ref('customers') }} c", "select *\nfrom {{ ref('customers') }} c"), + getCompiled: async (_f, side) => (side === "new" ? "select c.customer_id,\n c.ssn\nfrom analytics.customers c" : undefined), + }) + expect(env.findings.filter((f) => f.category === "pii_exposure").every((f) => f.severity !== "critical")).toBe(true) + 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" }], From 67a9bb193b159f192144280dbe4c24439ebc0e59 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:04:06 +0530 Subject: [PATCH 62/81] fix(review): tighten the raw-base proof for Jinja tags, comments and aliases `rawBaseLacks` decides whether a regex PII twin keeps its severity without a compiled base. - Jinja statements other than `if`/`elif`/`else`/`endif`, `for`/`endfor` and `set`/`endset` (for example `{% include %}` or `{% call %}`) can emit columns, so the base stays undecided. - A column named only in a SQL or Jinja comment is not a read. String literals still count, since a JSON path such as `'$.ssn'` can read the column. - Only the twin's source columns are compared. An output alias the base used for another column (`email as contact` -> `ssn as contact`) no longer hides a new source column. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 28 +++++++++----- .../opencode/test/altimate/review.test.ts | 38 +++++++++++++++++++ 2 files changed, 56 insertions(+), 10 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index ce80d26f04..35287081c1 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1108,17 +1108,25 @@ interface ModelContext { } /** - * The raw (uncompiled) base cannot expose any of `names`: none appears in it as - * a word, no select item is a `*`, and its only Jinja expressions are `ref`, - * `source`, `config` or `this`. A macro (`dbt_utils.star(…)`), a variable or a - * `{{ col }}` loop could emit any column, so any other expression proves nothing. + * The raw (uncompiled) base cannot expose any of the source columns `names`: + * none appears in it as a word outside comments, no select item is a `*`, its + * only Jinja expressions are `ref`, `source`, `config` or `this`, and its only + * Jinja statements are control flow (`if`/`for`/`set` and their ends), which + * emit no text of their own. A macro (`dbt_utils.star(…)`), a variable, a + * `{{ col }}` loop, an `{% include %}` or a `{% call %}` block could emit any + * column, so any other tag proves nothing. String literals still count as + * evidence: a JSON path (`payload:ssn`, `'$.ssn'`) can expose the column. */ +const RAW_BASE_PLAIN_EXPR = /^\{\{-?\s*(?:(?:ref|source|config)\s*\([^{}]*\)|this)\s*-?\}\}$/ +const RAW_BASE_SILENT_TAG = /^\{%[-+]?\s*(?:if|elif|else|endif|for|endfor|set|endset)\b[\s\S]*%\}$/ function rawBaseLacks(oldSql: string | undefined, names: string[]): boolean { if (!oldSql || !names.length) return false - const plain = /^\{\{-?\s*(?:(?:ref|source|config)\s*\([^{}]*\)|this)\s*-?\}\}$/ - if (!(oldSql.match(/\{\{[\s\S]*?\}\}/g) ?? []).every((e) => plain.test(e))) return false + if (!(oldSql.match(/\{\{[\s\S]*?\}\}/g) ?? []).every((e) => RAW_BASE_PLAIN_EXPR.test(e))) return false + if (!(oldSql.match(/\{%[\s\S]*?%\}/g) ?? []).every((t) => RAW_BASE_SILENT_TAG.test(t))) return false if (selectItems(oldSql).some((i) => /(?:^|\.)\*(?:\s|$)/.test(i.text))) return false - return names.every((n) => !new RegExp(`(? (m.startsWith("'") ? m : " ")) + return names.every((n) => !new RegExp(`(? { @@ -1580,9 +1588,9 @@ export async function runReview(input: OrchestrateInput): Promise { const ctx = ctxByPath.get(f.file) if (!ctx || !hasOldSide(ctx.file) || ctx.engineOldSql) return false - const result = (f.evidence?.result ?? {}) as { column?: string; alias?: string; items?: SelectItemColumn[] } - const names = [result.column, result.alias, ...(result.items ?? []).flatMap((it) => [it.column, it.alias])] - return rawBaseLacks(ctx.oldSql, names.filter((n): n is string => !!n)) + const result = (f.evidence?.result ?? {}) as { column?: string; items?: SelectItemColumn[] } + const columns = [result.column, ...(result.items ?? []).map((it) => it.column)] + return rawBaseLacks(ctx.oldSql, columns.filter((c): c is string => !!c)) } const merged = flat.filter((f) => { const tool = f.evidence?.tool diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index 08b74941fa..cb9b280605 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -3181,6 +3181,44 @@ describe("orchestrate", () => { } }) + test("raw-base proof: control-flow tags and comments prove nothing away, other Jinja tags and literals stay undecided", async () => { + const run = (base: string, head = "select customer_id,\n ssn\nfrom {{ ref('customers') }}", diff = "+ ssn\n") => + runReview({ + changedFiles: MARTS.map((path) => ({ path, status: "modified" as const, diff })), + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content(head, base), + }) + const blocks = async (base: string, head?: string, diff?: string) => { + const env = await run(base, head, diff) + return { base, critical: env.findings.filter(isTwin).some((f) => f.severity === "critical"), verdict: env.verdict } + } + // Proven new: `if`/`for`/`set` emit no text, a comment naming the column is + // not a read, and an output alias the base used for another column is not + // the source column (`email as contact` → `ssn as contact`). + for (const base of [ + "select customer_id\nfrom {{ ref('customers') }}\n{% if is_incremental() %}\nwhere updated_at > (select max(updated_at) from {{ this }})\n{% endif %}", + "{% set days = 3 %}\nselect customer_id -- ssn moved to the vault\nfrom {{ ref('customers') }} /* no ssn here */", + ]) + expect(await blocks(base)).toEqual({ base, critical: true, verdict: "REQUEST_CHANGES" }) + const aliasBase = "select customer_id,\n email as contact\nfrom {{ ref('customers') }}" + expect( + await blocks(aliasBase, "select customer_id,\n ssn as contact\nfrom {{ ref('customers') }}", "- email as contact\n+ ssn as contact\n"), + ).toEqual({ base: aliasBase, critical: true, verdict: "REQUEST_CHANGES" }) + // Undecided: a tag that can emit text, a `*` behind a select-list `if`, or a + // string literal that can read the column (a JSON path). + for (const base of [ + "select customer_id,\n{% include 'customer_columns.sql' %}\nfrom {{ ref('customers') }}", + "select customer_id\n{% call add_columns() %}x{% endcall %}\nfrom {{ ref('customers') }}", + "select customer_id{% if var('wide', false) %}, *{% endif %}\nfrom {{ ref('customers') }}", + "select {% if var('wide', false) %}*{% else %}customer_id{% endif %}\nfrom {{ ref('customers') }}", + "select customer_id, json_extract(payload, '$.ssn') as tax_ref\nfrom {{ ref('customers') }}", + ]) + expect(await blocks(base)).toEqual({ base, critical: false, verdict: expect.not.stringMatching(/^REQUEST_CHANGES$/) }) + }) + test("without a compiled base, an added `c.ssn` over a raw base with no `ssn` still blocks", async () => { for (const reviewers of [[], ["dbt_patterns"]]) { const env = await runReview({ From 3f6665b16ca2c46e52e976e26ab6a13f3fb73c72 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:05:56 +0530 Subject: [PATCH 63/81] fix(review): keep string-literal spacing in output signatures `normalizeItem` collapsed whitespace inside string literals, so `regexp_replace(ssn, '[0-9] *', '*', 'g')` and `'[0-9] *'` (which leaves a plain SSN unmasked) had the same signature and the change was approved. Whitespace and dot spacing now collapse only outside literals, for item signatures and for the CTE/subquery bodies built from them. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/rule-catalog.ts | 18 ++++++++++++------ packages/opencode/test/altimate/review.test.ts | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 7075627662..9145aa0f74 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -295,13 +295,19 @@ function maskSql(sql: string, keepLiterals = false): string { const isWordChar = (c: string | undefined) => !!c && /[\w$."`]/.test(c) +// Whitespace and dot spacing collapse only outside string literals, whose +// spacing can change what an expression does (`'[0-9] *'` vs `'[0-9] *'`). +const NORMALIZE_STEPS: Array<[RegExp, (group?: string) => string]> = [ + [/'(?:[^']|'')*'|\s+/g, () => " "], + [/'(?:[^']|'')*'|\(\s+/g, () => "("], + [/'(?:[^']|'')*'|\s+([),])/g, (close) => close!], + [/'(?:[^']|'')*'|\s*\.\s*/g, () => "."], +] const normalizeItem = (raw: string) => - raw - .replace(/\s+/g, " ") - .replace(/\(\s+/g, "(") - .replace(/\s+([),])/g, "$1") - .replace(/\s*\.\s*/g, ".") - .trim() + NORMALIZE_STEPS.reduce( + (s, [re, to]) => s.replace(re, (m: string, group?: string) => (m.startsWith("'") ? m : to(group))), + raw, + ).trim() // Words in an expression that are syntax, never a column. const EXPR_KEYWORDS = new Set( diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index cb9b280605..be8aa8eda5 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -2659,6 +2659,23 @@ describe("orchestrate", () => { ) }) + test("a masking literal whose spacing changed is a different computation", async () => { + // `'[0-9] *'` needs a trailing space after each digit, so a plain SSN is left unmasked. + const base = "select customer_id,\n regexp_replace(ssn, '[0-9] *', '*', 'g') as ssn\nfrom customers" + const head = base.replace("'[0-9] *'", "'[0-9] *'") + const diff = "- regexp_replace(ssn, '[0-9] *', '*', 'g') as ssn\n+ regexp_replace(ssn, '[0-9] *', '*', 'g') as ssn\n" + expectReportedPii(await piiRuns(head, base, diff, ["ssn"]), ["ssn"], "none") + // Through a CTE the masked name reaches the final select as a raw column: the + // CTE body's signature must keep the literal's spacing too. + const cteBase = `with masked as (\n ${base}\n)\nselect customer_id, ssn from masked` + const cteHead = cteBase.replace("'[0-9] *'", "'[0-9] *'") + expectReportedPii(await piiRuns(cteHead, cteBase, diff, ["ssn"]), ["ssn"], "none") + // Spacing outside the literal is still a reformat, not new exposure. + const reformatted = base.replace("regexp_replace(ssn, ", "regexp_replace(\n ssn, ") + for (const { reviewers, env } of await piiRuns(reformatted, base, diff, ["ssn"])) + 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. From fdf1480bfa31f3a7218d2bc81c6157bb1ccf5d00 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:07:26 +0530 Subject: [PATCH 64/81] fix(review): skip a summary marker this token cannot edit, and read `/user` only when needed - With an app or Actions token every `Bot` account's marker comment is a candidate. A candidate `updateComment` refuses (403) or that was deleted (404) is skipped for the next one, else a new summary is created. `botLogin` then comes from the comment actually written, so another bot's `altimate-finding:` markers no longer suppress inline findings. - `/user` is read only when the PR has a marker comment. Without one the summary is created and its author is the account, so a transient `/user` failure cannot lose the review. With one, a transient failure is retried once after 1s, then still fails the post. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/post-github.ts | 37 +++++++++++++----- .../test/altimate/review-noise.test.ts | 38 +++++++++++++++++-- 2 files changed, 62 insertions(+), 13 deletions(-) diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index f825f6ab45..4cb52e6cc0 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -89,6 +89,11 @@ function describeError(e: any): string { /** Headline of a review this bot posted (see verdictHeadline). */ const BOT_REVIEW_RE = /(Approved|Reviewed with comments|Changes requested)\b.*\((trivial|lite|full) tier/ +const statusOf = (e: any): number | undefined => e?.status ?? e?.response?.status + +/** Wait before retrying a transient `/user` failure, so a 429 or a brief 5xx can clear. */ +const SELF_RETRY_DELAY_MS = 1000 + /** The token's own login, or `undefined` for a token that cannot read `/user` * (an app or Actions token). A transient failure is retried once, then thrown. */ async function authenticatedLogin(octo: Octokit): Promise { @@ -96,9 +101,10 @@ async function authenticatedLogin(octo: Octokit): Promise { try { return (await octo.rest.users.getAuthenticated()).data.login } catch (e: any) { - const status = e?.status ?? e?.response?.status + const status = statusOf(e) if (status === 401 || status === 403 || status === 404) return undefined if (attempt > 0) throw e + await new Promise((resolve) => setTimeout(resolve, SELF_RETRY_DELAY_MS)) } } } @@ -126,15 +132,26 @@ export async function postGitHubReview( // comment's original author. The account is the authenticated user (a PAT); // an app/Actions token cannot read `/user` (401/403/404), and then only a Bot // account's comment counts (a person's account is never type `Bot`). Any - // other failure is retried once, then fails the post: guessing would create - // a duplicate summary and re-post every inline finding. - const selfLogin = await authenticatedLogin(octo) - const prior = existing.find( - (c) => c.body?.includes(REVIEW_MARKER) && (selfLogin ? c.user?.login === selfLogin : c.user?.type === "Bot"), - ) - 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 }) + // other `/user` failure is retried once, then fails the post: guessing would + // create a duplicate summary. With no marker comment at all there is nothing + // to decide, so `/user` is not read and a transient failure there cannot + // lose the review. + const markers = existing.filter((c) => c.body?.includes(REVIEW_MARKER)) + const selfLogin = markers.length ? await authenticatedLogin(octo) : undefined + const candidates = markers.filter((c) => (selfLogin ? c.user?.login === selfLogin : c.user?.type === "Bot")) + let upserted: { data: { id: number; user?: { login?: string } | null } } | undefined + for (const c of candidates) { + try { + upserted = await octo.rest.issues.updateComment({ owner, repo, comment_id: c.id, body: summary }) + break + } catch (e: any) { + // Another Bot account's comment (403) or one deleted meanwhile (404) is + // not ours: try the next candidate, else create a new summary. + const status = statusOf(e) + if (status !== 403 && status !== 404) throw e + } + } + upserted ??= 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 = selfLogin ?? upserted.data.user?.login diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 9cfbf960c8..5f97217854 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -654,6 +654,7 @@ describe("postGitHubReview", () => { ) { const reviewCalls: any[] = [] const summaryCalls: string[] = [] + const selfCalls = { count: 0 } const fail = async () => { throw new Error("listing failed") } @@ -678,17 +679,21 @@ describe("postGitHubReview", () => { listComments: paged(opts.issueComments ?? []), createComment: async () => { summaryCalls.push("create") - return { data: { id: 1, user: { login: BOT } } } + return { data: { id: 1, user: { login: opts.self ?? BOT } } } }, - // GitHub returns the comment's original author, not the token's account. + // GitHub returns the comment's original author, not the token's account, + // and refuses (403) to edit a comment another account posted. updateComment: async (p: { comment_id: number }) => { summaryCalls.push(`update ${p.comment_id}`) const author = opts.issueComments?.find((c) => c.id === p.comment_id)?.user ?? { login: BOT } + if (author.login !== (opts.self ?? BOT)) + throw Object.assign(new Error("Resource not accessible by integration"), { status: 403 }) return { data: { id: p.comment_id, user: author } } }, }, users: { getAuthenticated: async () => { + selfCalls.count++ const status = opts.selfErrors?.shift() ?? (opts.self ? undefined : 403) if (status) throw Object.assign(new Error(status === 403 ? "Resource not accessible by integration" : "Bad gateway"), { status }) return { data: { login: opts.self } } @@ -707,7 +712,7 @@ describe("postGitHubReview", () => { }, }, } - return { octo: octo as any, reviewCalls, summaryCalls } + return { octo: octo as any, reviewCalls, summaryCalls, selfCalls } } const noLine = buildEnvelope({ findings: [finding()], tier: "lite", mode: "comment" }) @@ -900,6 +905,33 @@ describe("postGitHubReview", () => { expect(twice.reviewCalls).toEqual([]) }) + test("another Bot account's summary marker is not adopted by an app token", async () => { + const env = buildEnvelope({ findings: [finding({ startLine: 3, title: "m: a" })], tier: "lite", mode: "comment" }) + const [first] = inlineComments(env, new Set(), undefined) + const other = { id: 5, body: `${REVIEW_MARKER}\nother bot`, user: { login: "other-app[bot]", type: "Bot" } } + // Only the other bot's marker: its comment cannot be edited, so a new summary + // is created, and its finding markers do not suppress this bot's inline comment. + const alone = fakeOcto({ issueComments: [other], reviewComments: [{ body: first.body, user: { login: "other-app[bot]" } }] }) + const r = await postGitHubReview(env, target, alone.octo) + expect(alone.summaryCalls).toEqual(["update 5", "create"]) + expect(r.summaryCommentId).toBe(1) + expect(r.inlineSkippedAsPosted).toBe(0) + expect(alone.reviewCalls[0].comments.map((c: { line: number }) => c.line)).toEqual([3]) + // The other bot's marker first, this bot's own after it: this bot's is updated. + const both = fakeOcto({ issueComments: [other, { id: 6, body: `${REVIEW_MARKER}\nmine`, user: { login: BOT, type: "Bot" } }] }) + expect((await postGitHubReview(env, target, both.octo)).summaryCommentId).toBe(6) + expect(both.summaryCalls).toEqual(["update 5", "update 6"]) + }) + + test("without a summary marker on the PR, `/user` is not read and its failure cannot lose the review", async () => { + const env = buildEnvelope({ findings: [finding({ startLine: 3, title: "m: a" })], tier: "lite", mode: "comment" }) + const pat = fakeOcto({ self: "local-dev", selfErrors: [502, 503] }) + await postGitHubReview(env, target, pat.octo) + expect(pat.selfCalls.count).toBe(0) + expect(pat.summaryCalls).toEqual(["create"]) + expect(pat.reviewCalls).toHaveLength(1) + }) + test("a deleted file gets no inline comment; a pure rename without a patch keeps its comments", async () => { const env = buildEnvelope({ findings: [ From e8e509ee203f1f8fe4cefc9e33d6abfce2a9ad6f Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:08:35 +0530 Subject: [PATCH 65/81] fix(review): cap a grouped bullet's model list, body and detail together A grouped bullet could reach about 1.9k characters (title, eight model names, a 600-character body and a 600-character per-model detail), so "the first critical always fits" held only for single bullets. The model list now keeps whole names within 200 characters and counts the rest. With a per-model detail, the body takes half of the 600-character body budget and the detail keeps whole entries in what is left. A grouped bullet now stays within about 1.1k, the size of a single one. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 34 ++++++++++++------- .../test/altimate/review-noise.test.ts | 22 ++++++++++++ 2 files changed, 43 insertions(+), 13 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 8a117fc25f..377fb10998 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -226,6 +226,9 @@ const BULLET_BODY_MAX = 600 // As for the title (a wide model's PII title lists every column), so a single // bullet always fits the room the capped notes leave. const BULLET_TITLE_MAX = 200 +// A grouped bullet's model list; its body and per-model detail share +// BULLET_BODY_MAX, so a grouped bullet is no larger than a single one. +const BULLET_NAMES_MAX = 200 /** `clip`, never ending inside a code span: an unpaired backtick is cut back. */ function clipTitle(text: string, max: number): string { @@ -258,27 +261,32 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou // (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 same = g.every((f) => f.body === g[0].body) - const body = bodyOf(same ? oneLine(g[0].body) : blankNames(oneLine(g[0].body))) + const listed = takeWhole( + names.slice(0, 8).map((n) => `\`${n}\``), + BULLET_NAMES_MAX, + ", ", + ) + const shown = listed.join(", ") + const more = names.length > listed.length ? `${listed.length ? " " : ""}(+${names.length - listed.length} more)` : "" // Members that differ by more than their model (another function, a second // column on one model): list each member's own values. const values = g.map((f) => ({ f, v: distinguishingValues(f) })) const differ = values.some(({ v }) => v.join("\u0000") !== values[0].v.join("\u0000")) - // Whole entries that fit the body budget, so a cut never lands inside a - // code span or drops the count of the rest. + const hasDetail = differ && values.some(({ v }) => v.length) + // Show a body verbatim only when every member says exactly that; + // otherwise its names belong to one model, so show the blanked form. With + // a per-model detail the body takes half the budget and the detail the rest. + const same = g.every((f) => f.body === g[0].body) + const bodyText = same ? oneLine(g[0].body) : blankNames(oneLine(g[0].body)) + const body = hasDetail ? clip(bodyText, BULLET_BODY_MAX / 2) : bodyOf(bodyText) + // Whole entries that fit, so a cut never lands inside a code span or drops + // the count of the rest. const entries = values .slice(0, 8) .map(({ f, v }) => `\`${f.model ?? f.file}\`: ${v.map((x) => `\`${x}\``).join(", ") || "—"}`) - const kept = takeWhole(entries, BULLET_BODY_MAX, " · ") + const kept = takeWhole(entries, BULLET_BODY_MAX - body.length, " · ") const rest = values.length - kept.length - const detail = - differ && values.some(({ v }) => v.length) - ? ` ${kept.join(" · ")}${rest ? `${kept.length ? " " : ""}(+${rest} more)` : ""} \n` - : "" + const detail = hasDetail ? ` ${kept.join(" · ")}${rest ? `${kept.length ? " " : ""}(+${rest} more)` : ""} \n` : "" const unverified = g.some((f) => f.degraded) ? " · _unverified_" : "" out.push({ text: diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 5f97217854..200cbcc964 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -351,6 +351,28 @@ describe("summary grouping and budget", () => { expect(renderSummary(env, { maxChars: Infinity })).toContain("column_number_299)") }) + test("a grouped bullet is no larger than a single one: model list, body and detail are capped together", () => { + // Nine long-named models, each with a long title, a long body and its own long values. + const fs = Array.from({ length: 9 }, (_, i) => { + const model = `model_${i}_${"m".repeat(60)}` + return finding({ + severity: "critical", + category: "pii_exposure", + model, + file: `models/marts/${model}.sql`, + title: `${model}: exposes PII columns (${Array.from({ length: 40 }, (_, k) => `col_${k}`).join(", ")})`, + body: ["a", "b", "c"].map((x) => `\`${x}_${i}_${"y".repeat(40)}\``).join(", ") + " are exposed. " + "Confirm masking. ".repeat(60), + }) + }) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "full", mode: "gate" })) + const start = md.indexOf("- **") + const bullet = md.slice(start, md.indexOf("", start) + "".length) + expect(bullet).toContain("9 findings across 9 model(s)") + expect(bullet.length).toBeLessThanOrEqual(1200) + expect((bullet.match(/`/g) ?? []).length % 2).toBe(0) + expect(md.length).toBeLessThanOrEqual(SUMMARY_BUDGET_CHARS) + }) + test("a critical that does not fit stops the listing: no later, shorter finding jumps ahead of it", () => { // Twelve criticals with long bodies (each clipped, still ~700 chars) cannot // all fit; the short suggestions after them must not be listed instead. From cd547e6f70de8fed81cf6b8c30f4dd49a0000719 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:21:22 +0530 Subject: [PATCH 66/81] fix(review): decide the posting account before adopting a summary comment A token with write access may be able to edit a comment another account posted, so a 403 from `updateComment` is not a reliable ownership check. An app/Actions token used to try every `Bot` marker comment, and a successful edit of another bot's summary made that bot's login ours for the inline dedup. - The account is now decided before writing: `ALTIMATE_REVIEW_BOT_LOGIN` when set (new, for GitHub App installation tokens), else the `/user` login (a PAT), else `github-actions[bot]` when `GITHUB_ACTIONS=true` and `/user` is refused. Only a marker comment by that login is adopted. - With no known account (an app token outside Actions without the override), no marker comment is adopted and a new summary is created each run. A duplicate summary is recoverable; overwriting another bot's comment and taking its finding markers as ours is not. - The 403/404 fallback to the next candidate, then a new summary, stays as a secondary guard. - `ALTIMATE_REVIEW_BOT_LOGIN` is documented in the dbt PR review docs. Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 7 +++ .../src/altimate/review/post-github.ts | 40 ++++++++----- .../opencode/test/altimate/review-ci.test.ts | 16 +++++- .../test/altimate/review-noise.test.ts | 56 ++++++++++++++----- 4 files changed, 88 insertions(+), 31 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 7b7cac73ac..ecdb3684b8 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -254,6 +254,13 @@ dropped on the next run. `--post` targets **GitHub** PRs (it reads `GITHUB_TOKEN run with `--json`/`--output` and post the verdict using that platform's own API — native GitLab posting is not yet built in. +The summary comment is updated in place only if the token's own account posted it. +For a personal access token, the account is the `/user` login. For Actions' own +`GITHUB_TOKEN`, it is `github-actions[bot]`. A GitHub App installation token cannot +read `/user`, so set `ALTIMATE_REVIEW_BOT_LOGIN` to the app's bot login (for example +`my-app[bot]`). Without it, outside Actions, each run posts a new summary comment +rather than risk editing another bot's comment. + ## Configuration — `.altimate/review.yml` Per-repo configuration, the analogue of an `AGENTS.md`. Tune the rubric, choose diff --git a/packages/opencode/src/altimate/review/post-github.ts b/packages/opencode/src/altimate/review/post-github.ts index 4cb52e6cc0..1d7d38ef00 100644 --- a/packages/opencode/src/altimate/review/post-github.ts +++ b/packages/opencode/src/altimate/review/post-github.ts @@ -28,6 +28,11 @@ export interface GitHubTarget { owner: string repo: string prNumber: number + /** The account the token posts as, when set explicitly (`ALTIMATE_REVIEW_BOT_LOGIN`, + * e.g. `my-app[bot]` for a GitHub App installation token). */ + botLogin?: string + /** Running in GitHub Actions (`GITHUB_ACTIONS=true`). */ + actions?: boolean } /** Resolve owner/repo/prNumber from the GitHub Actions environment. */ @@ -51,7 +56,8 @@ export async function resolveGitHubTarget(): Promise { const fromEnv = process.env["ALTIMATE_PR_NUMBER"] if (!prNumber && fromEnv) prNumber = Number(fromEnv) if (!prNumber) return undefined - return { token, owner, repo, prNumber } + const botLogin = process.env["ALTIMATE_REVIEW_BOT_LOGIN"]?.trim() || undefined + return { token, owner, repo, prNumber, botLogin, actions: process.env["GITHUB_ACTIONS"] === "true" } } export interface PostResult { @@ -94,6 +100,9 @@ const statusOf = (e: any): number | undefined => e?.status ?? e?.response?.statu /** Wait before retrying a transient `/user` failure, so a 429 or a brief 5xx can clear. */ const SELF_RETRY_DELAY_MS = 1000 +/** The account Actions' own `GITHUB_TOKEN` posts as. */ +const ACTIONS_BOT_LOGIN = "github-actions[bot]" + /** The token's own login, or `undefined` for a token that cannot read `/user` * (an app or Actions token). A transient failure is retried once, then thrown. */ async function authenticatedLogin(octo: Octokit): Promise { @@ -128,25 +137,28 @@ export async function postGitHubReview( per_page: 100, }) // Only a summary this token's own account posted is ours to update: anyone - // with edit rights can post the marker, and `updateComment` returns the - // comment's original author. The account is the authenticated user (a PAT); - // an app/Actions token cannot read `/user` (401/403/404), and then only a Bot - // account's comment counts (a person's account is never type `Bot`). Any - // other `/user` failure is retried once, then fails the post: guessing would - // create a duplicate summary. With no marker comment at all there is nothing - // to decide, so `/user` is not read and a transient failure there cannot - // lose the review. + // can post the marker, and a token with write access may be able to edit a + // comment another account posted, so the account is decided before writing: + // `ALTIMATE_REVIEW_BOT_LOGIN` when set, else the `/user` login (a PAT), else + // `github-actions[bot]` for a token in Actions that cannot read `/user`. A + // transient `/user` failure is retried once, then fails the post. With no + // known account (an app token outside Actions without the override) no + // marker comment is adopted and a new summary is created each run: a + // duplicate summary is recoverable, overwriting another bot's comment and + // taking its finding markers as ours is not. With no marker comment at all + // there is nothing to decide, so `/user` is not read. const markers = existing.filter((c) => c.body?.includes(REVIEW_MARKER)) - const selfLogin = markers.length ? await authenticatedLogin(octo) : undefined - const candidates = markers.filter((c) => (selfLogin ? c.user?.login === selfLogin : c.user?.type === "Bot")) + let selfLogin = target.botLogin + if (!selfLogin && markers.length) selfLogin = (await authenticatedLogin(octo)) ?? (target.actions ? ACTIONS_BOT_LOGIN : undefined) + const candidates = selfLogin ? markers.filter((c) => c.user?.login === selfLogin) : [] let upserted: { data: { id: number; user?: { login?: string } | null } } | undefined for (const c of candidates) { try { upserted = await octo.rest.issues.updateComment({ owner, repo, comment_id: c.id, body: summary }) break } catch (e: any) { - // Another Bot account's comment (403) or one deleted meanwhile (404) is - // not ours: try the next candidate, else create a new summary. + // A comment this token may not edit after all (403) or one deleted + // meanwhile (404): try the next candidate, else create a new summary. const status = statusOf(e) if (status !== 403 && status !== 404) throw e } @@ -154,7 +166,7 @@ export async function postGitHubReview( upserted ??= 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 = selfLogin ?? upserted.data.user?.login + const botLogin = upserted.data.user?.login ?? selfLogin // 2. Post a review. `env.verdict` arrives already mode-gated from // buildEnvelope (comment mode softened REQUEST_CHANGES → COMMENT upstream); diff --git a/packages/opencode/test/altimate/review-ci.test.ts b/packages/opencode/test/altimate/review-ci.test.ts index 7f82d9caff..8d850026dd 100644 --- a/packages/opencode/test/altimate/review-ci.test.ts +++ b/packages/opencode/test/altimate/review-ci.test.ts @@ -3,7 +3,15 @@ import { resolveGitHubTarget } from "../../src/altimate/review/post-github" import { ReviewCommand } from "../../src/cli/cmd/review" import { buildReviewSchemaContext } from "../../src/altimate/review/schema-context" -const ENV_KEYS = ["GITHUB_TOKEN", "GH_TOKEN", "GITHUB_REPOSITORY", "GITHUB_EVENT_PATH", "ALTIMATE_PR_NUMBER"] +const ENV_KEYS = [ + "GITHUB_TOKEN", + "GH_TOKEN", + "GITHUB_REPOSITORY", + "GITHUB_EVENT_PATH", + "ALTIMATE_PR_NUMBER", + "GITHUB_ACTIONS", + "ALTIMATE_REVIEW_BOT_LOGIN", +] const saved: Record = {} for (const k of ENV_KEYS) saved[k] = process.env[k] @@ -70,7 +78,11 @@ describe("resolveGitHubTarget", () => { process.env["GITHUB_REPOSITORY"] = "AltimateAI/altimate-bigquery-demo" process.env["ALTIMATE_PR_NUMBER"] = "42" const t = await resolveGitHubTarget() - expect(t).toEqual({ token: "tok", owner: "AltimateAI", repo: "altimate-bigquery-demo", prNumber: 42 }) + expect(t).toEqual({ token: "tok", owner: "AltimateAI", repo: "altimate-bigquery-demo", prNumber: 42, actions: false }) + // In Actions, with the posting account set explicitly. + process.env["GITHUB_ACTIONS"] = "true" + process.env["ALTIMATE_REVIEW_BOT_LOGIN"] = " my-app[bot] " + expect(await resolveGitHubTarget()).toMatchObject({ actions: true, botLogin: "my-app[bot]" }) }) test("returns undefined when PR number cannot be resolved", async () => { diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 200cbcc964..ccfd8b0c37 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -671,6 +671,8 @@ describe("postGitHubReview", () => { self?: string /** Statuses `/user` fails with first, one per call, before answering as above. */ selfErrors?: number[] + /** Comment ids `updateComment` refuses with 403; any other comment is edited. */ + refuse?: number[] createReview?: (call: number) => unknown } = {}, ) { @@ -703,13 +705,14 @@ describe("postGitHubReview", () => { summaryCalls.push("create") return { data: { id: 1, user: { login: opts.self ?? BOT } } } }, - // GitHub returns the comment's original author, not the token's account, - // and refuses (403) to edit a comment another account posted. + // Returns the comment's original author, not the token's account. A token + // with write access can edit another account's comment, so only the + // listed ids are refused. updateComment: async (p: { comment_id: number }) => { summaryCalls.push(`update ${p.comment_id}`) - const author = opts.issueComments?.find((c) => c.id === p.comment_id)?.user ?? { login: BOT } - if (author.login !== (opts.self ?? BOT)) + if (opts.refuse?.includes(p.comment_id)) throw Object.assign(new Error("Resource not accessible by integration"), { status: 403 }) + const author = opts.issueComments?.find((c) => c.id === p.comment_id)?.user ?? { login: BOT } return { data: { id: p.comment_id, user: author } } }, }, @@ -758,7 +761,7 @@ describe("postGitHubReview", () => { { filename: "models/late.sql", patch: PATCH }, ], }) - const r = await postGitHubReview(env, target, octo) + const r = await postGitHubReview(env, { ...target, actions: true }, octo) expect(summaryCalls).toEqual(["update 42"]) expect(r.inlineSkippedAsPosted).toBe(1) expect(reviewCalls[0].comments.map((c: { path: string; line: number }) => `${c.path}:${c.line}`)).toEqual(["models/late.sql:5"]) @@ -927,22 +930,45 @@ describe("postGitHubReview", () => { expect(twice.reviewCalls).toEqual([]) }) - test("another Bot account's summary marker is not adopted by an app token", async () => { + test("another account's summary marker is never edited, even when the token could edit it", async () => { const env = buildEnvelope({ findings: [finding({ startLine: 3, title: "m: a" })], tier: "lite", mode: "comment" }) const [first] = inlineComments(env, new Set(), undefined) const other = { id: 5, body: `${REVIEW_MARKER}\nother bot`, user: { login: "other-app[bot]", type: "Bot" } } - // Only the other bot's marker: its comment cannot be edited, so a new summary - // is created, and its finding markers do not suppress this bot's inline comment. + const mine = { id: 6, body: `${REVIEW_MARKER}\nmine`, user: { login: BOT, type: "Bot" } } + const actions = { ...target, actions: true } + // Actions token (`/user` 403s, so the account is `github-actions[bot]`): the + // other bot's marker is left alone, and its finding markers suppress nothing. const alone = fakeOcto({ issueComments: [other], reviewComments: [{ body: first.body, user: { login: "other-app[bot]" } }] }) - const r = await postGitHubReview(env, target, alone.octo) - expect(alone.summaryCalls).toEqual(["update 5", "create"]) - expect(r.summaryCommentId).toBe(1) + const r = await postGitHubReview(env, actions, alone.octo) + expect(alone.summaryCalls).toEqual(["create"]) expect(r.inlineSkippedAsPosted).toBe(0) expect(alone.reviewCalls[0].comments.map((c: { line: number }) => c.line)).toEqual([3]) - // The other bot's marker first, this bot's own after it: this bot's is updated. - const both = fakeOcto({ issueComments: [other, { id: 6, body: `${REVIEW_MARKER}\nmine`, user: { login: BOT, type: "Bot" } }] }) - expect((await postGitHubReview(env, target, both.octo)).summaryCommentId).toBe(6) - expect(both.summaryCalls).toEqual(["update 5", "update 6"]) + // The other bot's marker first, this bot's own after it: only this bot's is updated. + const both = fakeOcto({ issueComments: [other, mine] }) + expect((await postGitHubReview(env, actions, both.octo)).summaryCommentId).toBe(6) + expect(both.summaryCalls).toEqual(["update 6"]) + // An app token outside Actions without `ALTIMATE_REVIEW_BOT_LOGIN`: the account + // is unknown, so no marker is adopted and a new summary is created. + const unknown = fakeOcto({ issueComments: [other, mine] }) + await postGitHubReview(env, target, unknown.octo) + expect(unknown.summaryCalls).toEqual(["create"]) + // With the account set explicitly, its marker is updated and `/user` is not read. + const app = fakeOcto({ issueComments: [mine, { ...other, id: 7 }] }) + await postGitHubReview(env, { ...target, botLogin: "other-app[bot]" }, app.octo) + expect(app.summaryCalls).toEqual(["update 7"]) + expect(app.selfCalls.count).toBe(0) + }) + + test("a summary comment the token is refused to edit falls back to the next one, then a new summary", async () => { + const env = buildEnvelope({ findings: [finding({ startLine: 3, title: "m: a" })], tier: "lite", mode: "comment" }) + const marker = (id: number) => ({ id, body: `${REVIEW_MARKER}\n${id}`, user: { login: BOT, type: "Bot" } }) + const actions = { ...target, actions: true } + const next = fakeOcto({ issueComments: [marker(5), marker(6)], refuse: [5] }) + expect((await postGitHubReview(env, actions, next.octo)).summaryCommentId).toBe(6) + expect(next.summaryCalls).toEqual(["update 5", "update 6"]) + const none = fakeOcto({ issueComments: [marker(5)], refuse: [5] }) + expect((await postGitHubReview(env, actions, none.octo)).summaryCommentId).toBe(1) + expect(none.summaryCalls).toEqual(["update 5", "create"]) }) test("without a summary marker on the PR, `/user` is not read and its failure cannot lose the review", async () => { From a5f79d784f8ac19eb291f9273b5ab52ac72d669e Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:24:18 +0530 Subject: [PATCH 67/81] fix(review): leave more raw bases undecided in the PII proof The raw-base proof keeps a regex PII twin critical, so a wrong proof is a false REQUEST_CHANGES. - Any `*` token not preceded by a word counts as a star: `*except(email)`, `as struct *`, `object_construct(*)`. `count(*)` reads no column and is ignored. Spaced multiplication (`a * b`) also matches, which only leaves the base undecided. - `--` inside a double-quoted identifier (`"legacy--id"`) is no longer a comment, either in the proof's name check or in `maskSql`, which had hidden the rest of the line from the select-list parser. - Each twin column must be selected raw by the head's final select on its line. A line inside a masking expression (`sha2(\n ssn\n) as x`) proves nothing. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 27 +++++++++++++------ .../src/altimate/review/rule-catalog.ts | 5 ++-- .../opencode/test/altimate/review.test.ts | 20 ++++++++++++++ 3 files changed, 42 insertions(+), 10 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 35287081c1..8ea181ac65 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1109,23 +1109,30 @@ interface ModelContext { /** * The raw (uncompiled) base cannot expose any of the source columns `names`: - * none appears in it as a word outside comments, no select item is a `*`, its + * none appears in it as a word outside comments, no select item reads a `*`, its * only Jinja expressions are `ref`, `source`, `config` or `this`, and its only * Jinja statements are control flow (`if`/`for`/`set` and their ends), which * emit no text of their own. A macro (`dbt_utils.star(…)`), a variable, a * `{{ col }}` loop, an `{% include %}` or a `{% call %}` block could emit any * column, so any other tag proves nothing. String literals still count as * evidence: a JSON path (`payload:ssn`, `'$.ssn'`) can expose the column. + * A `*` is any `*` token not preceded by a word (`*`, `c.*`, `*except(email)`, + * `as struct *`, `object_construct(*)`); `count(*)` reads no column. Spaced + * multiplication (`a * b`) also matches, which only leaves the base undecided. */ const RAW_BASE_PLAIN_EXPR = /^\{\{-?\s*(?:(?:ref|source|config)\s*\([^{}]*\)|this)\s*-?\}\}$/ const RAW_BASE_SILENT_TAG = /^\{%[-+]?\s*(?:if|elif|else|endif|for|endfor|set|endset)\b[\s\S]*%\}$/ +const RAW_BASE_STAR = /(?:^|[\s.(])\*(?=\s|$|[a-z(),])/i function rawBaseLacks(oldSql: string | undefined, names: string[]): boolean { if (!oldSql || !names.length) return false if (!(oldSql.match(/\{\{[\s\S]*?\}\}/g) ?? []).every((e) => RAW_BASE_PLAIN_EXPR.test(e))) return false if (!(oldSql.match(/\{%[\s\S]*?%\}/g) ?? []).every((t) => RAW_BASE_SILENT_TAG.test(t))) return false - if (selectItems(oldSql).some((i) => /(?:^|\.)\*(?:\s|$)/.test(i.text))) return false - // Comments out, literals kept (one pass, so `--` inside a literal is not a comment). - const code = oldSql.replace(/\{#[\s\S]*?#\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'/g, (m) => (m.startsWith("'") ? m : " ")) + if (selectItems(oldSql).some((i) => RAW_BASE_STAR.test(i.text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ")))) return false + // Comments out, literals and quoted identifiers kept (one pass, so `--` inside + // `'…'` or `"…"` is not a comment). + const code = oldSql.replace(/\{#[\s\S]*?#\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"/g, (m) => + m.startsWith("'") || m.startsWith('"') ? m : " ", + ) return names.every((n) => !new RegExp(`(? { const ctx = ctxByPath.get(f.file) if (!ctx || !hasOldSide(ctx.file) || ctx.engineOldSql) return false - const result = (f.evidence?.result ?? {}) as { column?: string; items?: SelectItemColumn[] } - const columns = [result.column, ...(result.items ?? []).map((it) => it.column)] - return rawBaseLacks(ctx.oldSql, columns.filter((c): c is string => !!c)) + const result = (f.evidence?.result ?? {}) as { column?: string; line?: string; items?: SelectItemColumn[] } + const hits = result.items?.length ? result.items : result.column ? [{ column: result.column, line: result.line ?? "" }] : [] + const selectedRaw = ({ column, line }: { column: string; line: string }) => + headItemsOnLine(f.file, line).some((i) => i.scope === ROOT_SCOPE && i.rawColumn?.toLowerCase() === column) + return hits.length > 0 && hits.every(selectedRaw) && rawBaseLacks(ctx.oldSql, hits.map((h) => h.column)) } const merged = flat.filter((f) => { const tool = f.evidence?.tool diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 9145aa0f74..b07300bce7 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -283,10 +283,11 @@ export interface SelectItem { * Blank comments, Jinja tags and string-literal contents to spaces, and Jinja * expressions to `_`, keeping every offset and newline in place so positions * still map to source lines. One left-to-right pass, so `--` inside a literal or - * a quote inside a comment is not misread. + * a double-quoted identifier, or a quote inside a comment, is not misread. */ function maskSql(sql: string, keepLiterals = false): string { - return sql.replace(/\{#[\s\S]*?#\}|\{%[\s\S]*?%\}|\{\{[\s\S]*?\}\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'/g, (m) => { + return sql.replace(/\{#[\s\S]*?#\}|\{%[\s\S]*?%\}|\{\{[\s\S]*?\}\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"/g, (m) => { + if (m.startsWith('"')) return m if (m.startsWith("{{")) return m.replace(/[^\n]/g, "_") if (m.startsWith("'")) return keepLiterals ? m : `'${m.slice(1, -1).replace(/[^\n]/g, " ")}'` return m.replace(/[^\n]/g, " ") diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index be8aa8eda5..cdc6474b46 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -3218,6 +3218,8 @@ describe("orchestrate", () => { for (const base of [ "select customer_id\nfrom {{ ref('customers') }}\n{% if is_incremental() %}\nwhere updated_at > (select max(updated_at) from {{ this }})\n{% endif %}", "{% set days = 3 %}\nselect customer_id -- ssn moved to the vault\nfrom {{ ref('customers') }} /* no ssn here */", + // `count(*)` reads no column. + "select customer_id, count(*) as orders\nfrom {{ ref('customers') }}\ngroup by 1", ]) expect(await blocks(base)).toEqual({ base, critical: true, verdict: "REQUEST_CHANGES" }) const aliasBase = "select customer_id,\n email as contact\nfrom {{ ref('customers') }}" @@ -3232,8 +3234,26 @@ describe("orchestrate", () => { "select customer_id{% if var('wide', false) %}, *{% endif %}\nfrom {{ ref('customers') }}", "select {% if var('wide', false) %}*{% else %}customer_id{% endif %}\nfrom {{ ref('customers') }}", "select customer_id, json_extract(payload, '$.ssn') as tax_ref\nfrom {{ ref('customers') }}", + // A `*` with no space after it, after `as struct`, or as a function argument. + "select *except(email)\nfrom {{ ref('customers') }}", + "select as struct *\nfrom {{ ref('customers') }}", + "select customer_id, object_construct(*) as payload\nfrom {{ ref('customers') }}", + // `--` inside a double-quoted identifier is not a comment. + 'select "legacy--id", ssn\nfrom {{ ref(\'customers\') }}', + 'select "legacy--id", *\nfrom {{ ref(\'customers\') }}', ]) expect(await blocks(base)).toEqual({ base, critical: false, verdict: expect.not.stringMatching(/^REQUEST_CHANGES$/) }) + // A twin line inside a masking expression is not a raw select of the column. + const plainBase = "select customer_id\nfrom {{ ref('customers') }}" + expect( + await blocks(plainBase, "select customer_id,\n sha2(\n ssn\n ) as tax_ref\nfrom {{ ref('customers') }}", "+ sha2(\n+ ssn\n+ ) as tax_ref\n"), + ).toEqual({ base: plainBase, critical: false, verdict: expect.not.stringMatching(/^REQUEST_CHANGES$/) }) + // Case does not matter for the raw select. + expect(await blocks(plainBase, "select customer_id,\n SSN\nfrom {{ ref('customers') }}", "+ SSN\n")).toEqual({ + base: plainBase, + critical: true, + verdict: "REQUEST_CHANGES", + }) }) test("without a compiled base, an added `c.ssn` over a raw base with no `ssn` still blocks", async () => { From 17d90017e7df950d2188aeba4f32b5e7363ea2e9 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 19:25:25 +0530 Subject: [PATCH 68/81] fix(review): never cut a grouped bullet's shortened body inside a code span With a per-model detail, the grouped body is clipped to half the body budget. A plain `clip` could end inside a backticked value and break the rendering. It now uses the same cut-back as titles. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 5 +++-- .../test/altimate/review-noise.test.ts | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 377fb10998..9e0c3e3cb7 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -230,7 +230,8 @@ const BULLET_TITLE_MAX = 200 // BULLET_BODY_MAX, so a grouped bullet is no larger than a single one. const BULLET_NAMES_MAX = 200 -/** `clip`, never ending inside a code span: an unpaired backtick is cut back. */ +/** `clip`, never ending inside a code span: an unpaired backtick is cut back. + * Used for titles and for a grouped bullet's shortened body. */ function clipTitle(text: string, max: number): string { const clipped = clip(text, max) if (clipped === text) return clipped @@ -278,7 +279,7 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou // a per-model detail the body takes half the budget and the detail the rest. const same = g.every((f) => f.body === g[0].body) const bodyText = same ? oneLine(g[0].body) : blankNames(oneLine(g[0].body)) - const body = hasDetail ? clip(bodyText, BULLET_BODY_MAX / 2) : bodyOf(bodyText) + const body = hasDetail ? clipTitle(bodyText, BULLET_BODY_MAX / 2) : bodyOf(bodyText) // Whole entries that fit, so a cut never lands inside a code span or drops // the count of the rest. const entries = values diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index ccfd8b0c37..cd661426b9 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -373,6 +373,27 @@ describe("summary grouping and budget", () => { expect(md.length).toBeLessThanOrEqual(SUMMARY_BUDGET_CHARS) }) + test("a grouped body shortened for its per-model detail never ends inside a code span", () => { + // The body's code span starts before the half-budget cut and runs past it. + const fs = Array.from({ length: 3 }, (_, i) => + finding({ + severity: "warning", + category: "sql_quality", + model: `model_${i}`, + file: `models/model_${i}.sql`, + // Members differ by the title's value, so a per-model detail is shown; + // every body is the same, so it is shown verbatim. + title: `model_${i}: unsupported \`fn_${i}\``, + body: `${"word ".repeat(55)}\`${Array.from({ length: 30 }, (_, k) => `part${k}`).join(" ")}\` is unsupported.`, + }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + const start = md.indexOf("- **") + const body = md.slice(start).split("\n")[1] + expect(body).toContain("…") + expect((body.match(/`/g) ?? []).length % 2).toBe(0) + }) + test("a critical that does not fit stops the listing: no later, shorter finding jumps ahead of it", () => { // Twelve criticals with long bodies (each clipped, still ~700 chars) cannot // all fit; the short suggestions after them must not be listed instead. From 8f2e301ed103621860a367acf6130228d294f299 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 20:10:17 +0530 Subject: [PATCH 69/81] fix(review): accept a raw PII column selected in a CTE or subquery as proven new `provenNewTwin` required each twin column to be selected raw by the outermost select on its line. A new `ssn as tax_ref` inside an import CTE, carried to the final select as `tax_ref`, was therefore downgraded to an unknown-confidence warning and no longer blocked. The masking guard now rejects a twin only when its line lies inside a head select item, in any scope, that does not select the column raw (`sha2(\n ssn\n) as tax_ref`). A line in no select item keeps the earlier behaviour (the raw-base proof decides). Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/review/orchestrate.ts | 16 ++++-- .../opencode/test/altimate/review.test.ts | 55 +++++++++++++++++++ 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 8ea181ac65..e44509d5f2 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1591,17 +1591,21 @@ export async function runReview(input: OrchestrateInput): Promise { const ctx = ctxByPath.get(f.file) if (!ctx || !hasOldSide(ctx.file) || ctx.engineOldSql) return false const result = (f.evidence?.result ?? {}) as { column?: string; line?: string; items?: SelectItemColumn[] } const hits = result.items?.length ? result.items : result.column ? [{ column: result.column, line: result.line ?? "" }] : [] - const selectedRaw = ({ column, line }: { column: string; line: string }) => - headItemsOnLine(f.file, line).some((i) => i.scope === ROOT_SCOPE && i.rawColumn?.toLowerCase() === column) - return hits.length > 0 && hits.every(selectedRaw) && rawBaseLacks(ctx.oldSql, hits.map((h) => h.column)) + const notMasked = ({ column, line }: { column: string; line: string }) => { + const items = headItemsOnLine(f.file, line) + return !items.length || items.some((i) => i.rawColumn?.toLowerCase() === column) + } + return hits.length > 0 && hits.every(notMasked) && rawBaseLacks(ctx.oldSql, hits.map((h) => h.column)) } const merged = flat.filter((f) => { const tool = f.evidence?.tool diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index cdc6474b46..f73187f569 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -3256,6 +3256,61 @@ describe("orchestrate", () => { }) }) + test("raw-base proof: a raw column aliased in a CTE or subquery still blocks, a masked one stays undecided", async () => { + const cteBase = "with src as (\n select\n customer_id\n from {{ ref('customers') }}\n)\nselect\n customer_id\nfrom src" + const subBase = "select s.customer_id\nfrom (\n select customer_id\n from {{ ref('customers') }}\n) s" + const cases = [ + { + name: "CTE alias carried to the final select", + base: cteBase, + head: "with src as (\n select\n customer_id,\n ssn as tax_ref\n from {{ ref('customers') }}\n)\nselect\n customer_id,\n tax_ref\nfrom src", + diff: "- customer_id\n+ customer_id,\n+ ssn as tax_ref\n- customer_id\n+ customer_id,\n+ tax_ref\n", + critical: true, + }, + { + name: "subquery alias carried to the final select", + base: subBase, + head: "select s.customer_id,\n s.tax_ref\nfrom (\n select customer_id,\n ssn as tax_ref\n from {{ ref('customers') }}\n) s", + diff: "-select s.customer_id\n+select s.customer_id,\n+ s.tax_ref\n- select customer_id\n+ select customer_id,\n+ ssn as tax_ref\n", + critical: true, + }, + { + name: "multi-line sha2 in a CTE", + base: cteBase, + head: "with src as (\n select\n customer_id,\n sha2(\n ssn\n ) as tax_ref\n from {{ ref('customers') }}\n)\nselect\n customer_id,\n tax_ref\nfrom src", + diff: "- customer_id\n+ customer_id,\n+ sha2(\n+ ssn\n+ ) as tax_ref\n- customer_id\n+ customer_id,\n+ tax_ref\n", + critical: false, + }, + { + name: "multi-line regexp_replace in a subquery", + base: subBase, + head: "select s.customer_id,\n s.tax_ref\nfrom (\n select customer_id,\n regexp_replace(\n ssn,\n '[0-9]',\n '*'\n ) as tax_ref\n from {{ ref('customers') }}\n) s", + diff: "-select s.customer_id\n+select s.customer_id,\n+ s.tax_ref\n- select customer_id\n+ select customer_id,\n+ regexp_replace(\n+ ssn,\n+ '[0-9]',\n+ '*'\n+ ) as tax_ref\n", + critical: false, + }, + ] + for (const reviewers of [[], ["dbt_patterns"]]) { + for (const c of cases) { + const env = await runReview({ + changedFiles: [{ path: "models/marts/m1.sql", status: "modified" as const, diff: c.diff }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content(c.head, c.base), + }) + const twins = env.findings.filter(isTwin) + expect({ reviewers, name: c.name, twins: twins.length > 0 }).toEqual({ reviewers, name: c.name, twins: true }) + expect({ + reviewers, + name: c.name, + critical: twins.some((f) => f.severity === "critical"), + blocks: env.verdict === "REQUEST_CHANGES", + }).toEqual({ reviewers, name: c.name, critical: c.critical, blocks: c.critical }) + } + } + }) + test("without a compiled base, an added `c.ssn` over a raw base with no `ssn` still blocks", async () => { for (const reviewers of [[], ["dbt_patterns"]]) { const env = await runReview({ From a0a3310e24c82d4fd061ca674f22db54bcd28b72 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 20:10:45 +0530 Subject: [PATCH 70/81] docs(review): say what an App token inside Actions does without `ALTIMATE_REVIEW_BOT_LOGIN` Co-Authored-By: Claude Opus 5.5 --- docs/docs/usage/dbt-pr-review.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index ecdb3684b8..a2c64eaf79 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -259,7 +259,10 @@ For a personal access token, the account is the `/user` login. For Actions' own `GITHUB_TOKEN`, it is `github-actions[bot]`. A GitHub App installation token cannot read `/user`, so set `ALTIMATE_REVIEW_BOT_LOGIN` to the app's bot login (for example `my-app[bot]`). Without it, outside Actions, each run posts a new summary comment -rather than risk editing another bot's comment. +rather than risk editing another bot's comment. Inside Actions, an App token without +the variable is treated as `github-actions[bot]`, so it never finds the summary it +posted earlier and adds a new one on every run; set `ALTIMATE_REVIEW_BOT_LOGIN` +whenever the review posts with an App token. ## Configuration — `.altimate/review.yml` From 05795d408c23d79c04824c6ff8f6a03e2b2fe350 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 20:12:04 +0530 Subject: [PATCH 71/81] fix(review): never split or half-close a multi-backtick code span when clipping `clipTitle` counted backticks for parity, so a cut inside a triple- backtick span kept two of its three ticks. It now pairs backtick runs by length (a span closes on the next run of its own length), cuts back to the opening run of a span left open, and drops a run the cut splits. Text with single backticks only clips exactly as before. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/review/format.ts | 19 ++++++++++---- .../test/altimate/review-noise.test.ts | 25 +++++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index 9e0c3e3cb7..a73b5da7a0 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -230,14 +230,23 @@ const BULLET_TITLE_MAX = 200 // BULLET_BODY_MAX, so a grouped bullet is no larger than a single one. const BULLET_NAMES_MAX = 200 -/** `clip`, never ending inside a code span: an unpaired backtick is cut back. - * Used for titles and for a grouped bullet's shortened body. */ +/** `clip`, never ending inside a code span: a span left open is cut back to + * its opening run. A span opens on a run of backticks and closes on the next + * run of the same length (a double-backtick span may hold a single backtick), + * and a run the cut splits is dropped whole. Used for titles and for a grouped + * bullet's shortened body. */ function clipTitle(text: string, max: number): string { const clipped = clip(text, max) if (clipped === text) return clipped - const body = clipped.slice(0, -1) - const ticks = (body.match(/`/g) ?? []).length - return ticks % 2 ? `${body.slice(0, body.lastIndexOf("`")).trimEnd()}…` : clipped + let body = clipped.slice(0, -1) + if (body.endsWith("`") && text[body.length] === "`") body = body.replace(/`+$/, "") + let open: { len: number; at: number } | undefined + for (const m of body.matchAll(/`+/g)) { + if (!open) open = { len: m[0].length, at: m.index } + else if (m[0].length === open.len) open = undefined + } + if (open) body = body.slice(0, open.at) + return body === clipped.slice(0, -1) ? clipped : `${body.trimEnd()}…` } /** Render findings of one severity as bullets. With `group`, findings that say diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index cd661426b9..0536fc8dad 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -394,6 +394,31 @@ describe("summary grouping and budget", () => { expect((body.match(/`/g) ?? []).length % 2).toBe(0) }) + test("a grouped body shortened inside a multi-backtick code span cuts before the span's opening run", () => { + // A span closes only on a run of its own length; a single backtick inside a + // double-backtick span does not close it. + const spans = [ + `\`\`\`${Array.from({ length: 30 }, (_, k) => `part${k}`).join(" ")}\`\`\``, + `\`\`${Array.from({ length: 15 }, (_, k) => `part${k}`).join(" ")} \` ${Array.from({ length: 15 }, (_, k) => `more${k}`).join(" ")}\`\``, + ] + for (const span of spans) { + const fs = Array.from({ length: 3 }, (_, i) => + finding({ + severity: "warning", + category: "sql_quality", + model: `model_${i}`, + file: `models/model_${i}.sql`, + title: `model_${i}: unsupported \`fn_${i}\``, + body: `${"word ".repeat(55)}${span} is unsupported.`, + }), + ) + const md = renderSummary(buildEnvelope({ findings: fs, tier: "lite", mode: "comment" })) + const start = md.indexOf("- **") + const body = md.slice(start).split("\n")[1] + expect(body.trim()).toBe(`${"word ".repeat(55).trim()}…`) + } + }) + test("a critical that does not fit stops the listing: no later, shorter finding jumps ahead of it", () => { // Twelve criticals with long bodies (each clipped, still ~700 chars) cannot // all fit; the short suggestions after them must not be listed instead. From f992c0753c5e3a1272761f9693c32a2ed8abde05 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 20:12:31 +0530 Subject: [PATCH 72/81] fix(review): list the shorter model names after one longer than the list budget A grouped bullet's model list stopped at the first name longer than its 200-character budget. Such a name is now only counted in `(+N more)`. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/review/format.ts | 7 ++++++- packages/opencode/test/altimate/review-noise.test.ts | 8 ++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/review/format.ts b/packages/opencode/src/altimate/review/format.ts index a73b5da7a0..225cdd0af7 100644 --- a/packages/opencode/src/altimate/review/format.ts +++ b/packages/opencode/src/altimate/review/format.ts @@ -271,8 +271,13 @@ function bulletsFor(items: Finding[], group: boolean): Array<{ text: string; cou // (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) { + // A name longer than the whole list's budget is only counted, so it does + // not stop the shorter names after it from being listed. const listed = takeWhole( - names.slice(0, 8).map((n) => `\`${n}\``), + names + .map((n) => `\`${n}\``) + .filter((n) => n.length <= BULLET_NAMES_MAX) + .slice(0, 8), BULLET_NAMES_MAX, ", ", ) diff --git a/packages/opencode/test/altimate/review-noise.test.ts b/packages/opencode/test/altimate/review-noise.test.ts index 0536fc8dad..e41aebf810 100644 --- a/packages/opencode/test/altimate/review-noise.test.ts +++ b/packages/opencode/test/altimate/review-noise.test.ts @@ -312,6 +312,14 @@ describe("summary grouping and budget", () => { for (const m of ms) expect(local).toContain(`\`models/${m}.sql\``) }) + test("a model name longer than the model-list budget is counted and the shorter names after it are listed", () => { + const ms = [`m_${"x".repeat(250)}`, "m_b", "m_c"] + const fs = ms.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).toContain("3 findings across 3 model(s): `m_b`, `m_c` (+1 more)") + expect(md).not.toContain("x".repeat(250)) + }) + 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++) From f4d5ce6d83ffbc8a50d0d79fddf8b7edb08a2e4e Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 21:51:11 +0530 Subject: [PATCH 73/81] fix(review): withhold the raw-base PII proof only on evidence the column is masked or never reaches the output Without a compiled base, a regex PII twin whose column the raw base cannot expose is proven new and blocks. Since `445f304f3b` the proof also required the column to be a raw item of the final select, which stopped the block for raw PII that reaches the output through a CTE alias (`ssn as tax_ref` in a CTE, `tax_ref` in the final select). The proof now follows the column through the head's raw SQL (`rawReach`) and is withheld only on evidence that it does not reach the output unmasked: - its line lies inside select items that read it only inside masking calls or a window clause (`sha2(\n ssn\n)`), or in a `*` that excludes it; - every item carrying it sits in a CTE or FROM subquery that no reading query passes on unmasked: hashed, dropped, excluded by `* exclude`, or read only by an `in` / `exists` condition; - its line is in a clause that selects nothing (`order by\n ssn`) and nothing in the head may expose the column. Readers are found by the FROM/JOIN sources the parser already resolves, so a `*` spans its own sources only (`select * from final` no longer reads an earlier CTE). `* exclude | except | replace | rename` are followed, a later union branch outputs under the first branch's name, and a chain of CTEs is followed to the end. An expression keeps the value unless every read sits in a masking call (hash, encryption, mask by name, a part of a string, a count or length, a date part): `coalesce(ssn, '')`, `max(ssn)` and `replace(ssn, '-', '')` still block, on one line or several. Anything the analysis cannot follow counts as reaching, so the twin blocks as before the proof was narrowed: scalar and lateral subqueries, table functions or `unpivot` over the column, whole-row selects, Jinja column lists or variables, sources that did not parse, CTE column lists, a parenthesised `with`, clause words used as column names, Jinja glued to a clause word. The proof is computed once per finding, and each file's base and head are parsed once: a model with 300 added PII lines took about 3 s and now takes about 50 ms. Co-Authored-By: Claude --- .../src/altimate/review/orchestrate.ts | 89 +++- .../src/altimate/review/rule-catalog.ts | 494 +++++++++++++++++- .../test/altimate/review-rule-catalog.test.ts | 214 ++++++++ .../opencode/test/altimate/review.test.ts | 123 ++++- 4 files changed, 871 insertions(+), 49 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index e44509d5f2..240ca286a6 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -16,12 +16,15 @@ import { type ReviewMode, type ReviewScope, type VerdictEnvelope, buildEnvelope, import { detectModelPatterns, detectSchemaYmlPatterns, splitDiff } from "./dbt-patterns" import { type FinalOutputs, + type RawReach, type RelationPrefixes, type SelectItem, type SelectItemColumn, finalOutputs, + rawReach, refCovered, ROOT_SCOPE, + SILENT_JINJA_TAG, normalizeSelectLine, selectItems, } from "./rule-catalog" @@ -1121,18 +1124,22 @@ interface ModelContext { * multiplication (`a * b`) also matches, which only leaves the base undecided. */ const RAW_BASE_PLAIN_EXPR = /^\{\{-?\s*(?:(?:ref|source|config)\s*\([^{}]*\)|this)\s*-?\}\}$/ -const RAW_BASE_SILENT_TAG = /^\{%[-+]?\s*(?:if|elif|else|endif|for|endfor|set|endset)\b[\s\S]*%\}$/ const RAW_BASE_STAR = /(?:^|[\s.(])\*(?=\s|$|[a-z(),])/i -function rawBaseLacks(oldSql: string | undefined, names: string[]): boolean { - if (!oldSql || !names.length) return false - if (!(oldSql.match(/\{\{[\s\S]*?\}\}/g) ?? []).every((e) => RAW_BASE_PLAIN_EXPR.test(e))) return false - if (!(oldSql.match(/\{%[\s\S]*?%\}/g) ?? []).every((t) => RAW_BASE_SILENT_TAG.test(t))) return false - if (selectItems(oldSql).some((i) => RAW_BASE_STAR.test(i.text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ")))) return false +/** What `rawBaseLacks` reads from a raw base, parsed once per file: its code + * without comments, or `undefined` when the base is undecided for every column. */ +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 // Comments out, literals and quoted identifiers kept (one pass, so `--` inside // `'…'` or `"…"` is not a comment). - const code = oldSql.replace(/\{#[\s\S]*?#\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"/g, (m) => + return oldSql.replace(/\{#[\s\S]*?#\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"/g, (m) => m.startsWith("'") || m.startsWith('"') ? m : " ", ) +} +function rawBaseLacks(code: string | undefined, names: string[]): boolean { + if (code === undefined || !names.length) return false return names.every((n) => !new RegExp(`(? { + // The 1-based head lines equal to `line` (normalised). + const headLineNumbers = (file: string, line: string) => { const r = reindentInfo(file) const normalized = normalizeSelectLine(line) if (!r || !normalized) return [] - const lineNos = r.headLines.flatMap((l, i) => (l === normalized ? [i + 1] : [])) - return r.head.filter((i) => lineNos.some((n) => i.startLine <= n && n <= i.endLine)) + return r.headLines.flatMap((l, i) => (l === normalized ? [i + 1] : [])) + } + // Head select items spanning any head line equal to `line` (normalised). + const headItemsOnLine = (file: string, line: string) => { + const lineNos = headLineNumbers(file, line) + return (reindentInfo(file)?.head ?? []).filter((i) => lineNos.some((n) => i.startLine <= n && n <= i.endLine)) } const isReindented = (file: string, line: string) => { const r = reindentInfo(file) @@ -1591,21 +1602,59 @@ export async function runReview(input: OrchestrateInput): Promise() + const headReach = (file: string) => { + if (!headReachByFile.has(file)) { + const sql = ctxByPath.get(file)?.newSql + headReachByFile.set(file, sql ? rawReach(sql) : undefined) + } + return headReachByFile.get(file) + } + const rawBaseCodeByFile = new Map() + 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() const provenNewTwin = (f: Finding) => { + let proven = provenByFinding.get(f) + if (proven === undefined) provenByFinding.set(f, (proven = proveNewTwin(f))) + return proven + } + const proveNewTwin = (f: Finding) => { const ctx = ctxByPath.get(f.file) if (!ctx || !hasOldSide(ctx.file) || ctx.engineOldSql) return false const result = (f.evidence?.result ?? {}) as { column?: string; line?: string; items?: SelectItemColumn[] } const hits = result.items?.length ? result.items : result.column ? [{ column: result.column, line: result.line ?? "" }] : [] - const notMasked = ({ column, line }: { column: string; line: string }) => { - const items = headItemsOnLine(f.file, line) - return !items.length || items.some((i) => i.rawColumn?.toLowerCase() === column) + if (!hits.length || !rawBaseLacks(baseCode(f.file), hits.map((h) => h.column))) return false + const reach = headReach(f.file) + const head = reindentInfo(f.file)?.head ?? [] + const mayReachOutput = (hit: { column: string; line: string }) => { + const column = hit.column.toLowerCase() + const lineNos = headLineNumbers(f.file, hit.line) + if (!reach || !lineNos.length) return true + // Any head line with this text counts: the diff does not say which one it is. + return lineNos.some((n) => { + const items = head.filter((i) => i.startLine <= n && n <= i.endLine) + if (items.length) return items.some((i) => reach.passes(i, column)) + return !reach.inClause(n) || reach.mayExpose(column) + }) } - return hits.length > 0 && hits.every(notMasked) && rawBaseLacks(ctx.oldSql, hits.map((h) => h.column)) + return hits.every(mayReachOutput) } const merged = flat.filter((f) => { const tool = f.evidence?.tool diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index b07300bce7..c226f60140 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -417,6 +417,27 @@ interface ParsedSelects { items: SelectItem[] /** Per `scope#branch`, the sources its FROM / JOIN clauses read. */ sources: Map + /** Per `scope#branch`, the masked text of its FROM/JOIN source list: table + * names, aliases and table-function or `pivot`/`unpivot` arguments, without + * the bodies of FROM subqueries and without join conditions. */ + sourceText: Map + /** `scope#branch` selects with a source the parser could not name: a + * parenthesised join, a Jinja expression other than `ref`/`source`/`this`, a + * comma-joined source after a join condition, or no source at all in a + * select that holds a Jinja expression (which may be its FROM). */ + unknownSources: Set + /** Nested queries that are the operand of `in`, `exists`, `any`, `some` or + * `all`: their rows decide a condition and never reach an output. */ + predicates: Set + /** The SQL has a shape whose scopes, select lists or output names are not + * modelled: a CTE column list (`a (x, y) as (…)`), a `with` inside + * parentheses, `select as struct|value`, or a select list that stops at a + * clause word used as a column (`select topic, offset, ssn from …`). */ + unmodelled: boolean + /** Items holding a Jinja expression that may stand for a raw column or a + * column list: an item without an alias, or one whose expression is not a + * macro call (`{{ col }} as x`). */ + jinjaItems: Set } /** Offset of the `)` closing the `(` at `open` in masked SQL, or the end. */ @@ -446,16 +467,21 @@ function parseSelects(sql: string): ParsedSelects { } const items: SelectItem[] = [] const sources = new Map() + const sourceText = new Map() + const unknownSources = new Set() + const predicates = new Set() + const jinjaItems = new Set() + let unmodelled = false // The scope each nested query's `(` opens, so a FROM subquery is a named source. const parenScope = new Map() // Each select's scope, branch and the offset its select list ends at. - const selects: Array<{ scope: string; branch: number; end: number }> = [] + const selects: Array<{ scope: string; branch: number; start: number; end: number }> = [] const scopes: string[] = [ROOT_SCOPE] const branches = new Map() // `name as (`, or `name (col, …) as (`: a column list still names the CTE, whose // outputs then keep the body's own names (so a renamed column resolves to nothing). const cteHead = new RegExp( - String.raw`(${SEGMENT})\s*(?:\([^()]*\)\s*)?\s+as\s*(?:(?:not\s+)?materialized\s*)?$`, + String.raw`(${SEGMENT})\s*(\([^()]*\)\s*)?\s+as\s*(?:(?:not\s+)?materialized\s*)?$`, "i", ) const tableRef = new RegExp(String.raw`^\s*((?:${SEGMENT}\s*\.\s*)*${SEGMENT})`, "i") @@ -483,6 +509,23 @@ function parseSelects(sql: string): ParsedSelects { nestedKeys.add(key) return key } + // A `from` of the same select after `at`: at its nesting level, before a set + // operator or the end of the query (`is distinct from` is not one). + const fromAhead = (at: number) => { + let depth = 0 + for (let j = at; j < s.length; j++) { + const d = s[j] + if (d === "(") depth++ + else if (d === ")") { + if (--depth < 0) return false + } else if (d === ";" && depth === 0) return false + else if (depth === 0 && !isWordChar(s[j - 1])) { + if (SET_OPERATOR.test(s.slice(j, j + 10))) return false + if (/^from\b/i.test(s.slice(j, j + 5)) && !/\bdistinct\s+$/i.test(s.slice(Math.max(0, j - 12), j))) return true + } + } + return false + } for (let i = 0; i < s.length; i++) { const c = s[i] if (c === "(") { @@ -490,10 +533,19 @@ function parseSelects(sql: string): ParsedSelects { const cte = cteHead.exec(s.slice(Math.max(0, i - 200), i)) // A CTE body is named by its CTE; a nested query gets its own scope; any // other parenthesis (a call, a grouping) stays in its parent's scope. - if (cte && !/^as$/i.test(cte[1])) scopes.push(unquote(cte[1])) - else if (/^[\s(]*select\b/i.test(s.slice(i + 1, i + 200))) { + if (/^\s*with\b/i.test(s.slice(i + 1, i + 50))) unmodelled = true + if (cte && !/^as$/i.test(cte[1])) { + scopes.push(unquote(cte[1])) + if (cte[2]) unmodelled = true + } else if (/^[\s(]*select\b/i.test(s.slice(i + 1, i + 200))) { scopes.push(nestedKey(parent, i)) parenScope.set(i, scopes[scopes.length - 1]) + const before = s.slice(Math.max(0, i - 40), i) + if ( + /(?:^|[^\w$."\x60])(?:in|exists|any|some)\s*$/i.test(before) || + (/(?:^|[^\w$."\x60])all\s*$/i.test(before) && !/\b(?:union|intersect|except|minus)\s+all\s*$/i.test(before)) + ) + predicates.add(scopes[scopes.length - 1]) } else scopes.push(parent) continue } @@ -514,6 +566,7 @@ function parseSelects(sql: string): ParsedSelects { const prefix = /^\s+(?:(?:distinct|all)\b|top\s+\d+\b)?/i.exec(s.slice(start, start + 100)) if (prefix) start += prefix[0].length } + if (/^\s*as\s+(?:struct|value)\b/i.test(s.slice(start, start + 40))) unmodelled = true let depth = 0 let itemStart = start let position = 0 @@ -523,7 +576,7 @@ function parseSelects(sql: string): ParsedSelects { if (!raw.trim()) return const first = itemStart + (raw.length - raw.trimStart().length) const last = itemStart + raw.trimEnd().length - 1 - items.push({ + const item: SelectItem = { ...describeItem(raw), exact: normalizeItem(withLiterals.slice(itemStart, stop)), scope, @@ -531,7 +584,13 @@ function parseSelects(sql: string): ParsedSelects { position: position++, startLine: lineOf(first), endLine: lineOf(last), - }) + } + items.push(item) + // Jinja expressions of the item (masked to `_`, so not ones inside a literal). + const jinja = [...sql.slice(itemStart, stop).matchAll(/\{\{[\s\S]*?\}\}/g)].filter( + (m) => s[itemStart + m.index!] === "_", + ) + if (jinja.length && (!splitAlias(item.text).alias || jinja.some((m) => !m[0].includes("(")))) jinjaItems.add(item) } for (let j = start; j <= s.length; j++) { const d = s[j] @@ -554,23 +613,39 @@ function parseSelects(sql: string): ParsedSelects { // `* except (…)` (BigQuery) is one item, not a set operation. !(/^except\b/i.test(s.slice(j, j + 7)) && /\*\s*$/.test(s.slice(itemStart, j))) ) { + // A list that stops at any other clause word while this select still + // has a FROM ahead stopped at a column named like one (`offset`, `window`). + if (!/^from\b/i.test(s.slice(j, j + 5)) && !SET_OPERATOR.test(s.slice(j, j + 10)) && fromAhead(j)) unmodelled = true push(j) end = j break } } - selects.push({ scope, branch, end }) + selects.push({ scope, branch, start, end }) } // Sources read at each select's own level: the table, CTE or subquery after // `from`, `join`, or a `,` inside a FROM list, with its alias, up to the end of // the select (`)`, `;`, a set operator). const aliasRe = new RegExp(String.raw`^\s+(?:as\s+)?(${SEGMENT})`, "i") const segmentRe = new RegExp(SEGMENT, "g") - for (const { scope, branch, end } of selects) { + for (const { scope, branch, start, end } of selects) { + const key = `${scope}#${branch}` const read: Source[] = [] let inFrom = false + // Inside a join's `on` / `using` condition: a `,` at this level starts a + // comma-joined source (`join b on … , lateral flatten(…) f`). + let inCondition = false let depth = 0 - for (let j = end; j < s.length; j++) { + // The source list's own text, one segment per source: from after `from`, + // `join` or `,` to the next of them or the word that ends the list. + let text = "" + let segment = -1 + const closeSegment = (stop: number) => { + if (segment >= 0) text += ` ${s.slice(segment, stop)}` + segment = -1 + } + let j = end + for (; j < s.length; j++) { const d = s[j] if (depth === 0 && (d === ")" || d === ";")) break if (d === "(") depth++ @@ -580,6 +655,7 @@ function parseSelects(sql: string): ParsedSelects { if (boundary && SET_OPERATOR.test(s.slice(j, j + 10))) break const kw = boundary ? /^(from|join)\b/i.exec(s.slice(j, j + 5)) : null if (kw || (inFrom && d === ",")) { + closeSegment(j) const after = j + (kw ? kw[0].length : 1) const lead = after + (/^\s*/.exec(s.slice(after, after + 200))?.[0].length ?? 0) let name: string | undefined @@ -609,14 +685,33 @@ function parseSelects(sql: string): ParsedSelects { const src: Source = short && short !== name ? { name, short } : { name } if (alias && !NOT_A_SOURCE_ALIAS.has(unquote(alias))) src.alias = unquote(alias) read.push(src) - } + // A Jinja source that is not a relation call could name anything, a CTE included. + if (short?.startsWith("{{") && !/^\{\{[-+]?(?:(?:ref|source)\(|this[-+]?\}\}$)/.test(short)) unknownSources.add(key) + } else unknownSources.add(key) + // A FROM subquery's body is its own scope: only its alias belongs to this list. + segment = s[lead] === "(" && name ? rest : after inFrom = true j = after - 1 - } else if (boundary && FROM_LIST_END.test(s.slice(j, j + 10))) inFrom = false + inCondition = false + } else if (inCondition && d === ",") { + // Not read as a source (the resolvers keep their source list): its text + // counts, and the select reads something unnamed. + closeSegment(j) + segment = j + 1 + unknownSources.add(key) + } else if (boundary && FROM_LIST_END.test(s.slice(j, j + 10))) { + closeSegment(j) + inCondition = inFrom || inCondition ? /^(?:on|using)\b/i.test(s.slice(j, j + 6)) : false + inFrom = false + } } - sources.set(`${scope}#${branch}`, read) + closeSegment(j) + // No source parsed, yet a Jinja expression in the select: it may hold the FROM. + if (!read.length && /(? 0, starRaw, prefixes } } +/** A Jinja statement tag that emits no text of its own: control flow and `set`. */ +export const SILENT_JINJA_TAG = /^\{%[-+]?\s*(?:if|elif|else|endif|for|endfor|set|endset)\b[\s\S]*%\}$/ + +// Calls whose result does not reveal their argument: hashes, encryption and +// masking (by name, so a project's own `mask_ssn(…)` counts), a part of a +// string, a count or a length, and a date reduced to a part or a difference. +// Any other call (`coalesce`, `trim`, `max`, `replace`, a cast) keeps the value. +const MASKING_NAME = + /hash|md5|hmac|fingerprint|encrypt|cipher|mask|redact|anonymi[sz]e|pseudonymi[sz]e|tokeni[sz]e|obfuscate|scramble|(?:^|_)(?:sha|crc)(?:\d|_|$)/i +const MASKING_EXACT = new Set( + "left right substr substring regexp_replace translate length len char_length character_length count count_if countif approx_count_distinct datediff date_diff timestampdiff timestamp_diff months_between age date_trunc datetrunc extract date_part datepart year".split( + " ", + ), +) +// `unmask(…)`, `decrypt(…)`, `detokenize(…)` undo one. +const isMaskingCall = (name: string) => + MASKING_EXACT.has(name.toLowerCase()) || (MASKING_NAME.test(name) && !/^(?:de|un)/i.test(name)) +const NULL_TEST = new RegExp(String.raw`(? { + let e = splitAlias(text).expr + for (let m = /\(\s*select\b/i.exec(e); m; m = /\(\s*select\b/i.exec(e)) + e = `${e.slice(0, m.index)} ${e.slice(closingParen(e, m.index) + 1)}` + const call = /(? string[] +} + +const STAR_HEAD = new RegExp(String.raw`^((?:${SEGMENT}\s*\.\s*)*)\*`) +const SEGMENT_ONLY = new RegExp(String.raw`^${SEGMENT}$`) + +function starItem(text: string): StarItem | undefined { + const head = STAR_HEAD.exec(text) + if (!head) { + // A `*` inside the item that is not a multiplication (an operand on both + // sides): `object_construct(*)`, `struct(t.*)`, `as struct *`. `count(*)` + // reads no column. + const t = text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ") + for (let i = t.indexOf("*"); i >= 0; i = t.indexOf("*", i + 1)) { + const prev = /(\S)\s*$/.exec(t.slice(0, i))?.[1] + const next = /^\s*(\S)/.exec(t.slice(i + 1))?.[1] + const product = !!prev && /[\w$)"'\x60\]]/.test(prev) && !!next && /[\w$("'\x60.+-]/.test(next) + if (!product) return { opaque: true, carries: (c) => [c] } + } + return undefined + } + const segments = [...head[1].matchAll(new RegExp(SEGMENT, "g"))].map((m) => unquote(m[0])) + const qualifier = segments.length ? segments[segments.length - 1] : undefined + const dropped = new Set() + // Entries of `replace (…)` then `rename (…)`, in the order they apply: the + // columns each entry's value comes from (unmasked), and its name. + const steps: Array<{ kind: "replace" | "rename"; from: string[]; to: string }> = [] + let rest = text.slice(head[0].length) + while (rest.trim()) { + const m = /^\s*(exclude|except|replace|rename)\b\s*/i.exec(rest) + if (!m) return { qualifier, opaque: true, carries: (c) => [c] } + rest = rest.slice(m[0].length) + let list: string + if (rest.startsWith("(")) { + const close = closingParen(rest, 0) + list = rest.slice(1, close) + rest = rest.slice(close + 1) + } else { + // One bare entry: `exclude ssn`, `rename a as b`. + const bare = new RegExp(String.raw`^${SEGMENT}(?:\s+as\s+${SEGMENT})?`, "i").exec(rest) + if (!bare) return { qualifier, opaque: true, carries: (c) => [c] } + list = bare[0] + rest = rest.slice(bare[0].length) + } + const kind = m[1].toLowerCase() + for (const entry of topLevelItems(list)) { + if (!entry.trim()) continue + if (kind === "exclude" || kind === "except") { + if (!SEGMENT_ONLY.test(entry.trim())) return { qualifier, opaque: true, carries: (c) => [c] } + dropped.add(unquote(entry.trim())) + continue + } + // `expr as name`: a raw column under `name`, or an expression that masks it. + const item = describeItem(entry) + const { alias } = splitAlias(item.text) + if (!alias) return { qualifier, opaque: true, carries: (c) => [c] } + const from = item.rawColumn ? [item.rawColumn] : unmaskedReads(item.text).map((r) => r.column) + steps.push({ kind: kind as "replace" | "rename", from, to: unquote(alias) }) + } + } + const carries = (column: string) => { + if (dropped.has(column)) return [] + let names = new Set([column]) + for (const step of steps) { + if (step.kind === "rename") { + if (step.from.some((f) => names.delete(f))) names.add(step.to) + continue + } + // `replace (expr as to)`: `to` now holds `expr`. It still holds the column + // only when `expr` reads it unmasked. + const kept = step.from.some((f) => names.has(f)) + names.delete(step.to) + if (kept) names.add(step.to) + } + return [...names] + } + return { qualifier, carries } +} + +const wordIn = (text: string | undefined, word: string, dotted = true) => + !!text && + new RegExp( + `(? boolean + /** The value this item outputs may reach the model's final output unmasked. */ + reaches: (item: SelectItem) => boolean + /** The item may pass `column`'s value on to the final output unmasked: it + * carries it and reaches the output, or is a `*` that does not exclude or + * mask it and whose name for it reaches the output. */ + passes: (item: SelectItem, column: string) => boolean + /** The final output may expose a column named `column` raw: through an item + * that carries it and reaches the output, or through a `*` (or a Jinja + * column list) over a table whose columns the SQL does not list. */ + mayExpose: (column: string) => boolean + /** The 1-based `line` sits in a clause that selects nothing: the nearest + * clause word before it, outside closed parentheses, is `where`, `group by`, + * `order by`, `partition by`, `having`, `qualify`, `on`, `using`, `from` or + * `join`. `false` when that cannot be told (no clause word, or `select`). */ + inClause: (line: number) => boolean +} + +// Jinja expressions are masked to `_`, a word character: one glued to a clause +// word (`{{ config() }}select`, `from{{ ref('x') }}`) hides that word. +const JINJA_GLUED_KEYWORD = + /\}\}(?=(?:select|from|join|union|intersect|except|minus|with|where|on|using|as)\b)|(? SILENT_JINJA_TAG.test(t)) + const byKey = new Map() + const firstNames = new Map() + for (const item of items) { + const key = `${item.scope}#${item.branch}` + const list = byKey.get(key) + if (list) list.push(item) + else byKey.set(key, [item]) + if (item.branch === 0) firstNames.set(`${item.scope}\u0000${item.position}`, item.name) + } + // A later set-operation branch outputs under the first branch's name. + const outName = (item: SelectItem) => + item.branch === 0 ? item.name : (firstNames.get(`${item.scope}\u0000${item.position}`) ?? item.name) + const scopes = new Set(items.map((i) => i.scope)) + const fromSubqueries = new Set() + for (const list of sources.values()) for (const src of list) if (src.name.includes(">")) fromSubqueries.add(src.name) + const inPredicate = (scope: string) => { + for (let at = scope.length; at > 0; at = scope.lastIndexOf(">", at - 1)) if (predicates.has(scope.slice(0, at))) return true + return false + } + const naming = (src: Source) => [src.alias, src.name, src.short].filter((x): x is string => !!x) + // Every select whose rows can reach an output (not the operand of a + // condition), with the selects it is nested in, at any depth. + const keyed = [...sources.keys()].map((key) => ({ key, scope: key.slice(0, key.lastIndexOf("#")) })) + const selects = keyed + .filter((sel) => !inPredicate(sel.scope)) + .map((sel) => ({ ...sel, outer: keyed.filter((o) => sel.scope.startsWith(`${o.scope}>`)) })) + const stars = new Map() + const starOf = (item: SelectItem) => { + if (!stars.has(item)) stars.set(item, starItem(item.text)) + return stars.get(item) + } + // An expression item's unmasked reads. A `*` item names no column it reads + // (`* exclude (ssn)`), and a raw item is its column. + const readsByItem = new Map>() + const readsOf = (item: SelectItem) => { + let reads = readsByItem.get(item) + if (!reads) readsByItem.set(item, (reads = item.rawColumn || starOf(item) ? [] : unmaskedReads(item.text))) + return reads + } + + const reach = (scope: string, name: string | undefined, seen: Set): boolean => { + if (scope === ROOT_SCOPE) return true + if (scope.includes(">")) { + if (inPredicate(scope)) return false + // Not a FROM source: a scalar subquery, a lateral or a set-operation branch. + if (!fromSubqueries.has(scope)) return true + } + if (!name) return true + const visit = `${scope}\u0000${name}` + if (seen.has(visit)) return false + seen.add(visit) + for (const sel of selects) { + const own = (sources.get(sel.key) ?? []).filter((src) => src.name === scope) + const outerSelects = sel.outer + const outer = outerSelects.flatMap((o) => (sources.get(o.key) ?? []).filter((src) => src.name === scope)) + // Sources that did not parse, here or in an enclosing select, or a list + // that names the scope without parsing it as a source. + const blind = + unknownSources.has(sel.key) || + outerSelects.some((o) => unknownSources.has(o.key)) || + (!own.length && !scope.includes(">") && wordIn(sourceText.get(sel.key), scope, false)) + if (!own.length && !outer.length && !blind) continue + // A table function, `unpivot` or array join over the column moves its + // values under another name. + if (wordIn(sourceText.get(sel.key), name)) return true + const scopeNames = new Set([...own, ...outer].flatMap(naming)) + const otherNames = new Set( + [sel, ...outerSelects].flatMap((x) => (sources.get(x.key) ?? []).filter((src) => src.name !== scope).flatMap(naming)), + ) + // A qualifier names the scope, or no source the parser knows: an alias it + // did not read (`src pivot (…) p`) may still be the scope, so that counts. + const fromScope = (qualifier?: string) => + !qualifier || blind || scopeNames.has(qualifier) || !otherNames.has(qualifier) + for (const item of byKey.get(sel.key) ?? []) { + if (jinjaItems.has(item)) return true + const star = starOf(item) + if (star) { + // An unqualified `*` spans the select's own sources only. + if (star.qualifier ? !fromScope(star.qualifier) : !own.length && !blind) continue + // `x.*` over a struct column named like the output expands its fields. + if (star.qualifier === name && !scopeNames.has(name)) return true + if (star.opaque) return true + if (star.carries(name).some((carried) => reach(sel.scope, carried, seen))) return true + continue + } + // The name selected raw, or read by an expression that keeps its value. + const keeps = item.rawColumn + ? item.rawColumn === name && fromScope(item.rawQualifier) + : readsOf(item).some((r) => r.column === name && fromScope(r.qualifier)) + if (keeps) { + if (reach(sel.scope, outName(item), seen)) return true + continue + } + // The scope as a whole row: `select s from src s`, `to_json(s)`. + const row = (r: { qualifier?: string; column: string }) => !r.qualifier && scopeNames.has(r.column) + if (item.rawColumn ? !item.rawQualifier && scopeNames.has(item.rawColumn) : readsOf(item).some(row)) return true + } + } + return false + } + const memo = new Map() + const reachMemo = (scope: string, name: string | undefined) => { + const key = `${scope}\u0000${name ?? "\u0000"}` + let out = memo.get(key) + if (out === undefined) memo.set(key, (out = reach(scope, name, new Set()))) + return out + } + const carries = (item: SelectItem, column: string) => + item.rawColumn ? item.rawColumn === column : readsOf(item).some((r) => r.column === column) + const reaches = (item: SelectItem) => opaque || reachMemo(item.scope, outName(item)) + const passes = (item: SelectItem, column: string) => { + const star = starOf(item) + if (!star) return carries(item, column) && reaches(item) + if (star.opaque) return opaque || reachMemo(item.scope, undefined) + return star.carries(column).some((name) => opaque || reachMemo(item.scope, name)) + } + const exposeMemo = new Map() + const mayExpose = (column: string) => { + if (opaque) return true + let out = exposeMemo.get(column) + if (out !== undefined) return out + out = + items.some((i) => carries(i, column) && reaches(i)) || + selects.some((sel) => { + // A select reading a table whose columns are not listed in the SQL. + const tables = (sources.get(sel.key) ?? []).filter((src) => !scopes.has(src.name)) + if (!tables.length && !unknownSources.has(sel.key)) return false + const tableNames = new Set(tables.flatMap(naming)) + const derivedNames = new Set((sources.get(sel.key) ?? []).filter((src) => scopes.has(src.name)).flatMap(naming)) + return (byKey.get(sel.key) ?? []).some((item) => { + if (jinjaItems.has(item)) return reachMemo(sel.scope, column) + const star = starOf(item) + if (star) { + // A `*` qualified by a CTE or subquery passes that scope's columns only. + if (star.qualifier && derivedNames.has(star.qualifier) && !tableNames.has(star.qualifier)) return false + return star.opaque ? reachMemo(sel.scope, column) : star.carries(column).some((c) => reachMemo(sel.scope, c)) + } + // A table as a whole row. + return !!item.rawColumn && !item.rawQualifier && tableNames.has(item.rawColumn) && reachMemo(sel.scope, column) + }) + }) + exposeMemo.set(column, out) + return out + } + let masked: string | undefined + let lineStarts: number[] | undefined + const inClause = (line: number) => { + masked ??= maskSql(sql) + if (!lineStarts) { + lineStarts = [0] + for (let i = 0; i < masked.length; i++) if (masked[i] === "\n") lineStarts.push(i + 1) + } + const start = lineStarts[line - 1] + if (start === undefined) return false + // Backwards from the line, skipping parentheses that closed before it. + let depth = 0 + for (let i = start - 1; i >= 0; i--) { + const c = masked[i] + if (c === ")") depth++ + else if (c === "(") depth = Math.max(0, depth - 1) + else if (depth === 0 && !isWordChar(masked[i - 1]) && /[a-z]/i.test(c)) { + const word = CLAUSE_WORD.exec(masked.slice(i, i + 24)) + if (word) return SELECTS_NOTHING.test(word[1].replace(/\s+/g, " ")) + } + } + return false + } + return { items, carries, reaches, passes, mayExpose, inClause } +} + /** 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 { diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 3c7c6b4569..816b45a98d 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -4,6 +4,7 @@ import { ruleMatches, inputFromExample, finalOutputs, + rawReach, refCovered, selectItemColumns, selectItems, @@ -328,3 +329,216 @@ describe("finalOutputs().raw", () => { expect(asObject(rawOf(sql))).toEqual({ a: ["t.ssn"], c: ["t.email"] }) }) }) + +describe("rawReach", () => { + const REF = "{{ ref('customers') }}" + const OTHER = "{{ ref('spouses') }}" + // `src` reads `ssn` raw under the output name `tax_ref`; `rest` is the SQL after it. + const src = (rest: string, item = "ssn as tax_ref") => `with src as (\n select customer_id,\n ${item}\n from ${REF}\n)${rest}` + // Whether the item selecting `ssn` raw (the one on a line of its own) reaches the output. + const reaches = (sql: string) => { + const r = rawReach(sql) + const hit = r.items.filter((i) => i.rawColumn === "ssn") + expect({ sql, items: hit.length }).toEqual({ sql, items: 1 }) + return r.reaches(hit[0]) + } + const check = (cases: Array<[string, string, boolean]>) => { + for (const [name, sql, expected] of cases) expect({ name, reaches: reaches(sql) }).toEqual({ name, reaches: expected }) + } + + test("an item of the final select reaches the output; a CTE or FROM-subquery item follows its readers", () => { + check([ + ["final select", `select customer_id, ssn from ${REF}`, true], + ["later union branch of the final select", `select customer_id, region from ${OTHER}\nunion all\nselect ssn, customer_id from ${REF}`, true], + ["carried by name", src("\nselect customer_id, tax_ref from src"), true], + ["carried under a new alias, qualified", src("\nselect s.customer_id, s.tax_ref as t from src as s"), true], + ["quoted and upper-case names", src('\nselect "CUSTOMER_ID", "TAX_REF" from "SRC"'), true], + ["backtick names", "with `src` as (\n select customer_id,\n ssn as tax_ref\n from " + REF + "\n)\nselect `tax_ref` from `src`", true], + ["dropped by the final select", src("\nselect customer_id from src"), false], + ["never read", src(`\nselect customer_id from ${OTHER}`), false], + ["two CTEs, carried", src(", b as (\n select customer_id, tax_ref as x from src\n)\nselect x from b"), true], + ["two CTEs, dropped in the second", src(", b as (\n select customer_id from src\n)\nselect customer_id from b"), false], + ["FROM subquery, carried", `select s.customer_id, s.tax_ref\nfrom (\n select customer_id,\n ssn as tax_ref\n from ${REF}\n) s`, true], + ["FROM subquery, dropped", `select s.customer_id\nfrom (\n select customer_id,\n ssn as tax_ref\n from ${REF}\n) s`, false], + ["subquery inside a CTE", `with src as (\n select q.customer_id, q.tax_ref\n from (\n select customer_id,\n ssn as tax_ref\n from ${REF}\n ) q\n)\nselect tax_ref from src`, true], + ["read by another qualifier's source only", src(`\nselect o.customer_id, o.tax_ref\nfrom ${OTHER} o\njoin src s on s.customer_id = o.customer_id`), false], + ["a physical table named like the CTE is not the CTE", src("", "ssn").replace("with src", "with customers") + ", o as (\n select * from analytics.customers\n)\nselect * from o", false], + ]) + }) + + test("a `*` carries the column unless it excludes or masks it", () => { + check([ + ["plain star", src("\nselect * from src"), true], + ["qualified star", src(`\nselect s.* from src s join ${OTHER} o using (customer_id)`), true], + ["star of another source", src(`\nselect o.* from ${OTHER} o join src s using (customer_id)`), false], + ["star chain through 35 import CTEs", "with " + Array.from({ length: 35 }, (_, i) => `c${i} as (select * from {{ ref('t${i}') }}),\n`).join("") + src(", mid as (\n select customer_id, tax_ref as b from src\n)\nselect b from mid").slice(5), true], + ["exclude another column", src("\nselect * exclude (customer_id) from src"), true], + ["exclude the column", src("\nselect * exclude (tax_ref) from src"), false], + ["exclude without parentheses, upper case", src("\nselect * EXCLUDE TAX_REF from src"), false], + ["except with no space", src("\nselect *except(tax_ref) from src"), false], + ["replace by a hash", src("\nselect * replace (sha2(tax_ref) as tax_ref) from src"), false], + ["replace another column", src("\nselect * replace (upper(customer_id) as customer_id) from src"), true], + ["replace that keeps the value", src("\nselect * replace (coalesce(tax_ref, '') as tax_ref) from src"), true], + ["rename, then selected under the new name", src(", mid as (\n select * exclude (customer_id) rename (tax_ref as t) from src\n)\nselect t from mid"), true], + ["rename, old name no longer carried", src(", mid as (\n select * rename (tax_ref as t) from src\n)\nselect tax_ref from mid"), false], + ["a star that cannot be named", src("\nselect * ilike '%ref%' from src"), true], + ["a star inside a call", src("\nselect object_construct(*) as payload from src"), true], + ["count(*) reads no column", src("\nselect count(*) as n from src"), false], + ["a product is not a star", src("\nselect customer_id * 2 as twice from src"), false], + ["hashed in `final`, then `select * from final`", src(", final as (\n select customer_id, sha2(tax_ref) as tax_ref from src\n)\nselect * from final"), false], + ]) + }) + + test("an expression keeps the value unless every read sits in a masking call", () => { + const final = (item: string) => src(`\nselect customer_id, ${item} from src`) + check([ + ["sha2", final("sha2(tax_ref) as h"), false], + ["hash under the same name", src(", final as (\n select sha2(tax_ref) as tax_ref from src\n)\nselect tax_ref from final"), false], + ["last four", final("'***-**-' || right(tax_ref, 4) as masked"), false], + ["a project's own masking macro or UDF", final("util.mask_ssn(tax_ref) as m"), false], + ["hash inside coalesce", final("coalesce(md5(tax_ref), 'none') as h"), false], + ["null test", final("case when tax_ref is null then 0 else 1 end as has_ref"), false], + ["window partition", final("row_number() over (partition by tax_ref order by customer_id) as rn"), false], + ["count", final("count(distinct tax_ref) as n"), false], + ["coalesce", final("coalesce(tax_ref, '') as t"), true], + ["max", final("max(tax_ref) as t"), true], + ["case that returns it", final("case when customer_id > 0 then tax_ref end as t"), true], + ["replace of a separator", final("replace(tax_ref, '-', '') as t"), true], + ["double cast", final("tax_ref::varchar::text as t"), true], + ["an undo of a mask", final("unmask(tax_ref) as t"), true], + ["kept by an expression, then dropped", src(", b as (\n select trim(tax_ref) as t from src\n)\nselect 1 as one from b"), false], + ]) + }) + + test("a later set-operation branch outputs under the first branch's name", () => { + const u = (rest: string) => `with u as (\n select customer_id, tax_id from ${OTHER}\n union all\n select customer_id,\n ssn\n from ${REF}\n)\n${rest}` + check([ + ["selected under the first branch's name", u("select tax_id from u"), true], + ["not selected", u("select customer_id from u"), false], + ["its own name is not an output", u("select customer_id from u where tax_id is not null"), false], + ]) + }) + + test("a condition's operand reaches nothing; other nested queries count as reaching", () => { + check([ + ["exists", src(`\nselect o.* from ${OTHER} o\nwhere exists (select * from src s where s.customer_id = o.customer_id)`), false], + ["in", src(`\nselect * from ${OTHER} o\nwhere o.customer_id in (select tax_ref from src)`), false], + ["any", src(`\nselect * from ${OTHER} o\nwhere o.customer_id = any (select tax_ref from src)`), false], + ["nested in a condition", src(`\nselect * from ${OTHER} o\nwhere o.customer_id in (select x.tax_ref from (select tax_ref from src) x)`), false], + ["scalar subquery in the select list", src(`\nselect o.customer_id, (select s.tax_ref from src s where s.customer_id = o.customer_id) as t\nfrom ${OTHER} o`), true], + ["parenthesised union branch", src(`\n(select customer_id, region from ${OTHER})\nunion all\n(select customer_id, tax_ref from src)`), true], + ["lateral subquery", src(`\nselect o.customer_id, l.x\nfrom ${OTHER} o, src s, lateral (select s.tax_ref as x) l`), true], + ]) + }) + + test("a reader whose columns cannot be named counts as reaching", () => { + check([ + ["unpivot over the column", src("\nselect customer_id, v from src unpivot (v for k in (tax_ref))"), true], + ["unnest of the column", src("\nselect s.customer_id, t from src s cross join unnest(s.tax_ref) as t"), true], + ["a table function over another column", src("\nselect s.customer_id, f.value as tag from src s, lateral flatten(input => s.tags) f"), false], + ["whole row", src("\nselect s from src s"), true], + ["whole row in a call", src("\nselect to_json(s) as j from src s"), true], + ["struct expansion of the column", src("\nselect tax_ref.* from src"), true], + ["an alias the parser did not read", src("\nselect p.* from src pivot (max(v) for k in ('a')) p"), true], + ["parenthesised join", src(`\nselect tax_ref from (src s join ${OTHER} o on o.customer_id = s.customer_id)`), true], + ["CTE column list", src("\nselect t from src").replace("with src as", "with src (customer_id, t) as"), true], + ["nested `with`", `select t.customer_id\nfrom (\n with a as (\n select customer_id,\n ssn\n from ${REF}\n )\n select * from a\n) t`, true], + ]) + }) + + test("Jinja: a column list or a variable may carry it, a macro call with an alias does not", () => { + check([ + ["incremental filter", src("\nselect customer_id from src\n{% if is_incremental() %}\nwhere updated_at > (select max(updated_at) from {{ this }})\n{% endif %}"), false], + ["incremental filter, carried", src("\nselect customer_id, tax_ref from src\n{% if is_incremental() %}\nwhere updated_at > (select max(updated_at) from {{ this }})\n{% endif %}"), true], + ["a macro that emits columns", src("\nselect {{ dbt_utils.star(from=ref('customers')) }} from src"), true], + ["a loop variable", src("\nselect customer_id, {% for c in cols %}{{ c }} as {{ c }}_v,{% endfor %} 1 as one from src"), true], + ["a macro call with an alias", src("\nselect customer_id, {{ dbt_utils.generate_surrogate_key(['tax_ref']) }} as k from src"), false], + ["a source named by a variable", src("\nselect tax_ref from {{ upstream }}"), true], + ["a source named by a variable, column not selected", src("\nselect customer_id from {{ upstream }}"), false], + ["a branch of a conditional FROM", src("\nselect tax_ref from {% if var('x') %} other {% else %} src {% endif %}"), true], + ["a tag that can emit text", src("\nselect customer_id\n{% include 'more.sql' %}\nfrom src"), true], + ]) + }) + + test("carries: raw, or read outside a masking call", () => { + const item = (text: string) => { + const r = rawReach(`select ${text} from t`) + return r.carries(r.items[0], "ssn") + } + expect(item("ssn")).toBe(true) + expect(item("c.ssn as tax_ref")).toBe(true) + expect(item("cast(ssn as varchar) as s")).toBe(true) + expect(item("coalesce(\n ssn,\n '') as s")).toBe(true) + expect(item("sha2(\n ssn\n) as s")).toBe(false) + expect(item("regexp_replace(ssn, '[0-9]', '*') as s")).toBe(false) + expect(item("row_number() over (partition by\n ssn\n order by id) as rn")).toBe(false) + expect(item("email")).toBe(false) + }) + + test("passes: a `*` item on the changed line passes the column unless it excludes or masks it", () => { + const star = (item: string, rest = "\nselect * from src") => { + const r = rawReach(`with src as (\n select ${item}\n from ${REF}\n)${rest}`) + return r.passes(r.items[0], "ssn") + } + expect(star("* rename (\n ssn as tax_ref\n )")).toBe(true) + expect(star("* rename (\n ssn as tax_ref\n )", "\nselect customer_id from src")).toBe(false) + expect(star("* exclude (\n ssn\n )")).toBe(false) + expect(star("* replace (\n sha2(ssn) as ssn\n )")).toBe(false) + expect(star("* replace (\n coalesce(ssn, '') as ssn\n )")).toBe(true) + expect(star("sha2(\n ssn\n ) as h")).toBe(false) + expect(star("coalesce(\n ssn,\n '') as tax_ref", "\nselect tax_ref from src")).toBe(true) + expect(star("coalesce(\n ssn,\n '') as tax_ref", "\nselect customer_id from src")).toBe(false) + }) + + test("mayExpose: a column no select item names is exposed only through a table's `*`", () => { + expect(rawReach(`select customer_id from ${REF} order by ssn`).mayExpose("ssn")).toBe(false) + expect(rawReach(`select sha2(ssn) as h, count(*) as n from ${REF} group by ssn`).mayExpose("ssn")).toBe(false) + expect(rawReach(`select * from ${REF} order by ssn`).mayExpose("ssn")).toBe(true) + expect(rawReach(`select * exclude (ssn) from ${REF}`).mayExpose("ssn")).toBe(false) + expect(rawReach(`with a as (select * from ${REF}) select customer_id from a order by ssn`).mayExpose("ssn")).toBe(false) + expect(rawReach(`with a as (select * from ${REF}) select * from a`).mayExpose("ssn")).toBe(true) + expect(rawReach(src("\nselect customer_id from src order by tax_ref")).mayExpose("ssn")).toBe(false) + expect(rawReach(src("\nselect * from src")).mayExpose("ssn")).toBe(true) + }) + + test("inClause: a line outside every select list is told apart only by the clause word before it", () => { + const at = (sql: string, text: string) => rawReach(sql).inClause(sql.split("\n").findIndex((l) => l.trim() === text) + 1) + expect(at(`select customer_id\nfrom ${REF}\norder by\n ssn`, "ssn")).toBe(true) + expect(at(`select customer_id, count(*) as n\nfrom ${REF}\ngroup by\n customer_id,\n ssn`, "ssn")).toBe(true) + expect(at(`select customer_id\nfrom ${REF}\nqualify row_number() over (\n partition by\n ssn\n order by updated_at) = 1`, "ssn")).toBe(true) + expect(at(`select customer_id\nfrom ${REF}\nwhere region = 'x'\n and\n ssn is not null`, "ssn is not null")).toBe(true) + // A keyword in a parenthesis that closed before the line says nothing about it. + expect(at(`select topic, offset, (select max(x) from u where k = 1),\n ssn\nfrom ${REF}`, "ssn")).toBe(false) + // The select word itself is hidden (glued to Jinja), or there is none. + expect(at(`{{ config(materialized='table') }}select\n customer_id,\n ssn\nfrom ${REF}`, "ssn")).toBe(false) + expect(at("ssn", "ssn")).toBe(false) + }) + + test("select lists the parser cannot see whole count as reaching", () => { + check([ + ["Jinja glued to `select`", `{{ config(materialized='table') }}with src as (\n select customer_id,\n ssn as tax_ref\n from ${REF}\n){{ hook() }}select customer_id from src`, true], + ["a clause word used as a column name", src("\nselect topic, offset, tax_ref from src"), true], + ["`select as struct`", src("\nselect array(select as struct tax_ref from src) as rows"), true], + ["a comma-joined source after a join condition", src(`\nselect o.customer_id, u.v\nfrom ${OTHER} o\njoin src s on s.customer_id = o.customer_id\n , unnest([s.tax_ref]) as u(v)`), true], + ["a comma-joined CTE after a join condition", `with a as (\n select customer_id from ${OTHER}\n), ` + src(`\nselect s.tax_ref\nfrom ${OTHER} o\njoin a on a.customer_id = o.customer_id\n , src s`).slice(5), true], + ["a FROM hidden in Jinja", src("\nselect tax_ref {{ from_src() }}"), true], + ]) + }) + + test("malformed SQL and deep chains do not throw or stall", () => { + for (const sql of ["ssn", "select\n ssn\nfrom", `with src as (\n select ssn from ${REF}\nselect customer_id from src`, "select customer_id))\nfrom src)", "with a as (select * from a) select * from a"]) { + const r = rawReach(sql) + for (const i of r.items) r.reaches(i) + r.mayExpose("ssn") + } + const n = 300 + const chain = + `with c0 as (\n select customer_id,\n ssn as x0\n from ${REF}\n)` + + Array.from({ length: n }, (_, i) => `, c${i + 1} as (\n select customer_id, x${i} as x${i + 1}, ${Array.from({ length: 30 }, (_, k) => `f${k}`).join(", ")} from c${i}\n)`).join("") + + `\nselect x${n} from c${n}` + const t0 = performance.now() + expect(reaches(chain)).toBe(true) + expect(reaches(chain.replace(`select x${n} from`, "select customer_id from"))).toBe(false) + expect(performance.now() - t0).toBeLessThan(2000) + }) +}) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index f73187f569..b6698f6f5c 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -3256,43 +3256,115 @@ describe("orchestrate", () => { }) }) - test("raw-base proof: a raw column aliased in a CTE or subquery still blocks, a masked one stays undecided", async () => { - const cteBase = "with src as (\n select\n customer_id\n from {{ ref('customers') }}\n)\nselect\n customer_id\nfrom src" - const subBase = "select s.customer_id\nfrom (\n select customer_id\n from {{ ref('customers') }}\n) s" - const cases = [ + test("raw-base proof: the column blocks when it reaches the final output unmasked, and stays undecided when masked, dropped or only tested", async () => { + const REF = "{{ ref('customers') }}" + const OTHER = "{{ ref('spouses') }}" + const cteBase = `with src as (\n select\n customer_id\n from ${REF}\n)\nselect\n customer_id\nfrom src` + const subBase = `select s.customer_id\nfrom (\n select customer_id\n from ${REF}\n) s` + const plainBase = `select customer_id\nfrom ${REF}` + // `src` with one more item on its own line, then the rest of the model. + const src = (item: string, rest: string) => `with src as (\n select\n customer_id,\n ${item}\n from ${REF}\n)${rest}` + const cases: Array<{ name: string; base: string; head: string; critical: boolean }> = [ + // Reaches the output unmasked: blocks. + { name: "CTE alias carried to the final select", base: cteBase, head: src("ssn as tax_ref", "\nselect\n customer_id,\n tax_ref\nfrom src"), critical: true }, + { + name: "subquery alias carried to the final select", + base: subBase, + head: `select s.customer_id,\n s.tax_ref\nfrom (\n select customer_id,\n ssn as tax_ref\n from ${REF}\n) s`, + critical: true, + }, + { name: "two CTEs", base: cteBase, head: src("ssn as x", ", b as (\n select customer_id, x\n from src\n)\nselect\n customer_id,\n x\nfrom b"), critical: true }, + { name: "`select *` over the CTE", base: cteBase, head: src("ssn", "\nselect * from src"), critical: true }, + { name: "`* exclude` of another column", base: cteBase, head: src("ssn", "\nselect * exclude (customer_id)\nfrom src"), critical: true }, { - name: "CTE alias carried to the final select", + name: "alias chain after 35 `select *` import CTEs", base: cteBase, - head: "with src as (\n select\n customer_id,\n ssn as tax_ref\n from {{ ref('customers') }}\n)\nselect\n customer_id,\n tax_ref\nfrom src", - diff: "- customer_id\n+ customer_id,\n+ ssn as tax_ref\n- customer_id\n+ customer_id,\n+ tax_ref\n", + head: + "with " + + Array.from({ length: 35 }, (_, i) => `c${i} as (select * from {{ ref('t${i}') }}),\n`).join("") + + src("ssn as a", ", mid as (\n select customer_id, a as b\n from src\n)\nselect\n customer_id,\n b\nfrom mid").slice(5), critical: true, }, { - name: "subquery alias carried to the final select", - base: subBase, - head: "select s.customer_id,\n s.tax_ref\nfrom (\n select customer_id,\n ssn as tax_ref\n from {{ ref('customers') }}\n) s", - diff: "-select s.customer_id\n+select s.customer_id,\n+ s.tax_ref\n- select customer_id\n+ select customer_id,\n+ ssn as tax_ref\n", + name: "second union branch, selected under the first branch's name", + base: cteBase, + head: `with u as (\n select customer_id, tax_id from ${OTHER}\n union all\n select\n customer_id,\n ssn\n from ${REF}\n)\nselect customer_id, tax_id\nfrom u`, + critical: true, + }, + { + name: "scalar subquery in the final select", + base: cteBase, + head: src("ssn as tax_ref", `\nselect\n o.customer_id,\n (select s.tax_ref from src s where s.customer_id = o.customer_id) as tax_ref\nfrom ${OTHER} o`), critical: true, }, + { name: "multi-line coalesce keeps the value", base: plainBase, head: `select customer_id,\n coalesce(\n ssn,\n ''\n ) as tax_ref\nfrom ${REF}`, critical: true }, + { name: "kept by `max` in the final select", base: cteBase, head: src("ssn as tax_ref", "\nselect\n customer_id,\n max(tax_ref) as tax_ref\nfrom src\ngroup by 1"), critical: true }, + { name: "a Jinja column list in the final select", base: cteBase, head: src("ssn", "\nselect\n {{ dbt_utils.star(from=ref('customers'), except=['region']) }}\nfrom src"), critical: true }, + // Masked, dropped, or only tested: undecided. { name: "multi-line sha2 in a CTE", base: cteBase, - head: "with src as (\n select\n customer_id,\n sha2(\n ssn\n ) as tax_ref\n from {{ ref('customers') }}\n)\nselect\n customer_id,\n tax_ref\nfrom src", - diff: "- customer_id\n+ customer_id,\n+ sha2(\n+ ssn\n+ ) as tax_ref\n- customer_id\n+ customer_id,\n+ tax_ref\n", + head: src("sha2(\n ssn\n ) as tax_ref", "\nselect\n customer_id,\n tax_ref\nfrom src"), critical: false, }, { name: "multi-line regexp_replace in a subquery", base: subBase, - head: "select s.customer_id,\n s.tax_ref\nfrom (\n select customer_id,\n regexp_replace(\n ssn,\n '[0-9]',\n '*'\n ) as tax_ref\n from {{ ref('customers') }}\n) s", - diff: "-select s.customer_id\n+select s.customer_id,\n+ s.tax_ref\n- select customer_id\n+ select customer_id,\n+ regexp_replace(\n+ ssn,\n+ '[0-9]',\n+ '*'\n+ ) as tax_ref\n", + head: `select s.customer_id,\n s.tax_ref\nfrom (\n select customer_id,\n regexp_replace(\n ssn,\n '[0-9]',\n '*'\n ) as tax_ref\n from ${REF}\n) s`, + critical: false, + }, + { name: "raw in the import CTE, hashed in the final select", base: cteBase, head: src("ssn", "\nselect\n customer_id,\n sha2(ssn) as tax_ref\nfrom src"), critical: false }, + { name: "raw in the import CTE, dropped by the final select", base: cteBase, head: src("ssn as tax_ref", "\nselect\n customer_id\nfrom src"), critical: false }, + { + name: "hashed in `final`, then `select * from final`", + base: cteBase, + head: src("ssn", ", final as (\n select customer_id, sha2(ssn) as tax_ref\n from src\n)\nselect * from final"), + critical: false, + }, + { + name: "hashed under the same name", + base: cteBase, + head: src("ssn", ", final as (\n select customer_id, sha2(ssn) as ssn\n from src\n)\nselect customer_id, ssn\nfrom final"), + critical: false, + }, + { name: "`* exclude` of the column", base: cteBase, head: src("ssn", "\nselect * exclude (ssn)\nfrom src"), critical: false }, + { + name: "read only by an `exists` condition", + base: cteBase, + head: src("ssn", `\nselect o.*\nfrom ${OTHER} o\nwhere exists (select * from src s where s.customer_id = o.customer_id)`), + critical: false, + }, + { name: "`order by` line, not selected", base: plainBase, head: `select customer_id\nfrom ${REF}\norder by\n ssn`, critical: false }, + { + name: "window partition line", + base: plainBase, + head: `select\n customer_id,\n row_number() over (partition by\n ssn\n order by customer_id) as rn\nfrom ${REF}`, critical: false, }, ] + // A line diff of base → head. + const diffOf = (base: string, head: string) => { + const a = base.split("\n") + const b = head.split("\n") + const lcs = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0)) + for (let i = a.length - 1; i >= 0; i--) + for (let j = b.length - 1; j >= 0; j--) lcs[i][j] = a[i] === b[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 < a.length || j < b.length) { + if (i < a.length && j < b.length && a[i] === b[j]) { + i++ + j++ + } else if (j < b.length && (i >= a.length || lcs[i][j + 1] >= lcs[i + 1][j])) out.push(`+${b[j++]}`) + else out.push(`-${a[i++]}`) + } + return `${out.join("\n")}\n` + } for (const reviewers of [[], ["dbt_patterns"]]) { for (const c of cases) { const env = await runReview({ - changedFiles: [{ path: "models/marts/m1.sql", status: "modified" as const, diff: c.diff }], + changedFiles: [{ path: "models/marts/m1.sql", status: "modified" as const, diff: diffOf(c.base, c.head) }], config: { ...DEFAULT_REVIEW_CONFIG, reviewers }, rubric: DEFAULT_RUBRIC, mode: "gate", @@ -3311,6 +3383,25 @@ describe("orchestrate", () => { } }) + test("the raw-base proof parses each file once however many PII lines it adds", async () => { + // 300 added PII lines in a 3,000-column CTE: the proof is asked twice per line. + const cols = Array.from({ length: 3000 }, (_, i) => ` c${i},`).join("\n") + const pii = Array.from({ length: 300 }, (_, i) => ` ssn as t${i},`).join("\n") + const base = `with src as (\n select\n${cols}\n customer_id\n from {{ ref('customers') }}\n)\nselect * from src` + const head = `with src as (\n select\n${cols}\n${pii}\n customer_id\n from {{ ref('customers') }}\n)\nselect customer_id from src` + const t0 = performance.now() + const env = await runReview({ + changedFiles: [{ path: "models/marts/m1.sql", status: "modified" as const, diff: `${pii.split("\n").map((l) => `+${l}`).join("\n")}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content(head, base), + }) + expect(env.findings.filter(isTwin).length).toBeGreaterThan(0) + expect(performance.now() - t0).toBeLessThan(1500) + }) + test("without a compiled base, an added `c.ssn` over a raw base with no `ssn` still blocks", async () => { for (const reviewers of [[], ["dbt_patterns"]]) { const env = await runReview({ From 601f1a7a1b9ff2e2d6d978fee241c8289372aff4 Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 21:51:11 +0530 Subject: [PATCH 74/81] docs(review): say when PII blocks without a compiled base, and what an App token in Actions re-posts Co-Authored-By: Claude --- docs/docs/usage/dbt-pr-review.md | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index a2c64eaf79..86e628b892 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -260,9 +260,11 @@ For a personal access token, the account is the `/user` login. For Actions' own read `/user`, so set `ALTIMATE_REVIEW_BOT_LOGIN` to the app's bot login (for example `my-app[bot]`). Without it, outside Actions, each run posts a new summary comment rather than risk editing another bot's comment. Inside Actions, an App token without -the variable is treated as `github-actions[bot]`, so it never finds the summary it -posted earlier and adds a new one on every run; set `ALTIMATE_REVIEW_BOT_LOGIN` -whenever the review posts with an App token. +the variable is treated as `github-actions[bot]`: it never finds the summary it +posted earlier and adds a new one on every run, and if the PR already has a +`github-actions[bot]` summary it updates that one and no longer recognises its own +inline comments, so they are posted again. Set `ALTIMATE_REVIEW_BOT_LOGIN` whenever +the review posts with an App token. ## Configuration — `.altimate/review.yml` @@ -315,7 +317,15 @@ rubric: - **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. + 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 + 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 + through CTEs and subqueries. A column that is hashed, masked or dropped on the + way (`sha2(ssn)`, `right(ssn, 4)`, `* exclude (ssn)`) stays a warning; one that + only passes through a value-preserving expression (`coalesce(ssn, '')`, + `max(ssn)`) still blocks. ### Risk-tier path tokens From 79308b874280d50a3f27b25ae5ec488a7737d51b Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 22:16:56 +0530 Subject: [PATCH 75/81] fix(review): count every shape the PII reach analysis does not model as reaching the output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An adversarial pass over `rawReach` found shapes where a raw column reaches the output while the analysis said it did not. Each is now followed or counted as reaching: - a line inside a FROM/JOIN source (`unnest([\n ssn\n])`, `unpivot`, `pivot`, `match_recognize`, `lateral flatten`) is not in a clause that selects nothing; - a column list on a CTE or subquery alias (`from c as t(x)`), `union … by name`, a parenthesised set-operation branch, a DDL wrapper or a second statement are not modelled, and set-operation branches that do not line up item for item have unknown output positions; - `select all (select …)` is a scalar subquery, not a condition; - a literal spanning lines, an unpaired quote or a `#` may mean the masker misread the quoting (a backslash-escaped quote, a `#` comment), and a doubled select prefix (`distinct top 10`) pollutes the first item: nothing then shows a column masked; - an alias that came out of Jinja is an unknown name, and a macro call that names the column (`dbt.safe_cast("ssn", …)`) may emit it raw; - a later item of the same select may read an alias (`ssn as raw, raw as tax_ref`), a reader may select a field of the column (`tax.v`), a positional column (`$2`) or a column pattern (`columns('…')`); - another column output under the PII name (`tax_id_number as ssn`) carries it; - a CTE that reads its own name with `*` reads the table of that name. Readers and their items are indexed once per file, so deeply nested subqueries (800 levels) take about 0.2 s instead of 1.9 s. Co-Authored-By: Claude --- .../src/altimate/review/rule-catalog.ts | 364 +++++++++++++----- .../test/altimate/review-rule-catalog.test.ts | 57 +++ 2 files changed, 334 insertions(+), 87 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index c226f60140..35c5fef623 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -285,8 +285,9 @@ export interface SelectItem { * still map to source lines. One left-to-right pass, so `--` inside a literal or * a double-quoted identifier, or a quote inside a comment, is not misread. */ +const MASKED_TOKEN = /\{#[\s\S]*?#\}|\{%[\s\S]*?%\}|\{\{[\s\S]*?\}\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"/g function maskSql(sql: string, keepLiterals = false): string { - return sql.replace(/\{#[\s\S]*?#\}|\{%[\s\S]*?%\}|\{\{[\s\S]*?\}\}|\/\*[\s\S]*?\*\/|--[^\n]*|'(?:[^']|'')*'|"(?:[^"]|"")*"/g, (m) => { + return sql.replace(MASKED_TOKEN, (m) => { if (m.startsWith('"')) return m if (m.startsWith("{{")) return m.replace(/[^\n]/g, "_") if (m.startsWith("'")) return keepLiterals ? m : `'${m.slice(1, -1).replace(/[^\n]/g, " ")}'` @@ -430,14 +431,28 @@ interface ParsedSelects { * `all`: their rows decide a condition and never reach an output. */ predicates: Set /** The SQL has a shape whose scopes, select lists or output names are not - * modelled: a CTE column list (`a (x, y) as (…)`), a `with` inside - * parentheses, `select as struct|value`, or a select list that stops at a - * clause word used as a column (`select topic, offset, ssn from …`). */ + * modelled: a column list on a CTE or on a CTE/subquery alias (`a (x, y) as + * (…)`, `from c as t(x)`), a `with` inside parentheses, a parenthesised + * set-operation branch, `union … by name`, a select list that stops at a + * clause word used as a column (`select topic, offset, ssn from …`), or a + * statement other than one query. */ unmodelled: boolean + /** The select items themselves may be wrong: quoting the masker may have + * misread (a literal spanning lines, an unpaired quote, a `#`: a + * backslash-escaped quote or a `#` comment with an apostrophe swallows + * SQL), or a select prefix it does not strip (`distinct top 10`, `as + * struct`) became part of the first item. */ + misread: boolean /** Items holding a Jinja expression that may stand for a raw column or a * column list: an item without an alias, or one whose expression is not a * macro call (`{{ col }} as x`). */ jinjaItems: Set + /** Per item, the text of its Jinja macro calls that are not masking calls + * (`{{ dbt.safe_cast("ssn", "varchar") }}`): a column they name may come + * out raw. */ + jinjaCalls: Map + /** Offsets `[start, stop)` of every FROM/JOIN source segment (as `sourceText`). */ + sourceRanges: Array<[number, number]> } /** Offset of the `)` closing the `(` at `open` in masked SQL, or the end. */ @@ -471,7 +486,18 @@ function parseSelects(sql: string): ParsedSelects { const unknownSources = new Set() const predicates = new Set() const jinjaItems = new Set() - let unmodelled = false + const jinjaCalls = new Map() + const sourceRanges: Array<[number, number]> = [] + const cteNames = new Set() + let misread = + (sql.match(MASKED_TOKEN) ?? []).some((m) => m.startsWith("'") && m.includes("\n")) || + (s.match(/'/g)?.length ?? 0) % 2 === 1 || + s.includes("#") + // One query only: a DDL/DML wrapper or a second statement is not a model. + let unmodelled = + /^[\s_]*(?:create|insert|merge|update|delete|alter|drop)\b/i.test(s) || + /;\s*\S/.test(s) || + /\b(?:union|intersect|except|minus)\s+(?:all\s+|distinct\s+)?by\s+name\b/i.test(s) // The scope each nested query's `(` opens, so a FROM subquery is a named source. const parenScope = new Map() // Each select's scope, branch and the offset its select list ends at. @@ -536,16 +562,22 @@ function parseSelects(sql: string): ParsedSelects { if (/^\s*with\b/i.test(s.slice(i + 1, i + 50))) unmodelled = true if (cte && !/^as$/i.test(cte[1])) { scopes.push(unquote(cte[1])) + cteNames.add(unquote(cte[1])) if (cte[2]) unmodelled = true } else if (/^[\s(]*select\b/i.test(s.slice(i + 1, i + 200))) { scopes.push(nestedKey(parent, i)) parenScope.set(i, scopes[scopes.length - 1]) const before = s.slice(Math.max(0, i - 40), i) + const setOperand = /\b(?:union|intersect|except|minus)(?:\s+all|\s+distinct)?\s*$/i.test(before) if ( /(?:^|[^\w$."\x60])(?:in|exists|any|some)\s*$/i.test(before) || - (/(?:^|[^\w$."\x60])all\s*$/i.test(before) && !/\b(?:union|intersect|except|minus)\s+all\s*$/i.test(before)) + // `union all (…)` is a branch and `select all (…)` a scalar subquery. + (/(?:^|[^\w$."\x60])all\s*$/i.test(before) && !setOperand && !/\bselect\s+all\s*$/i.test(before)) ) predicates.add(scopes[scopes.length - 1]) + // A parenthesised set-operation branch: its select is not a numbered branch. + else if (setOperand || /^\s*(?:union|intersect|except|minus)\b/i.test(s.slice(closingParen(s, i) + 1, closingParen(s, i) + 30))) + unmodelled = true } else scopes.push(parent) continue } @@ -566,7 +598,7 @@ function parseSelects(sql: string): ParsedSelects { const prefix = /^\s+(?:(?:distinct|all)\b|top\s+\d+\b)?/i.exec(s.slice(start, start + 100)) if (prefix) start += prefix[0].length } - if (/^\s*as\s+(?:struct|value)\b/i.test(s.slice(start, start + 40))) unmodelled = true + if (/^\s*(?:as\s+(?:struct|value)|distinct|all|top|percent|with\s+ties)\b/i.test(s.slice(start, start + 40))) misread = true let depth = 0 let itemStart = start let position = 0 @@ -591,6 +623,11 @@ function parseSelects(sql: string): ParsedSelects { (m) => s[itemStart + m.index!] === "_", ) if (jinja.length && (!splitAlias(item.text).alias || jinja.some((m) => !m[0].includes("(")))) jinjaItems.add(item) + const calls = jinja.filter((m) => { + const macro = /([A-Za-z_]\w*)\s*\(/.exec(m[0])?.[1] + return !!macro && !isMaskingCall(macro) + }) + if (calls.length) jinjaCalls.set(item, calls.map((m) => m[0]).join(" ")) } for (let j = start; j <= s.length; j++) { const d = s[j] @@ -641,7 +678,10 @@ function parseSelects(sql: string): ParsedSelects { let text = "" let segment = -1 const closeSegment = (stop: number) => { - if (segment >= 0) text += ` ${s.slice(segment, stop)}` + if (segment >= 0) { + text += ` ${s.slice(segment, stop)}` + sourceRanges.push([segment, stop]) + } segment = -1 } let j = end @@ -681,9 +721,15 @@ function parseSelects(sql: string): ParsedSelects { } } if (name) { - const alias = aliasRe.exec(s.slice(rest, rest + 200))?.[1] + const aliased = aliasRe.exec(s.slice(rest, rest + 200)) + const alias = aliased?.[1] const src: Source = short && short !== name ? { name, short } : { name } - if (alias && !NOT_A_SOURCE_ALIAS.has(unquote(alias))) src.alias = unquote(alias) + 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. + if ((s[lead] === "(" || cteNames.has(name)) && /^\s*\(/.test(s.slice(rest + aliased![0].length, rest + aliased![0].length + 20))) + unmodelled = true + } read.push(src) // A Jinja source that is not a relation call could name anything, a CTE included. if (short?.startsWith("{{") && !/^\{\{[-+]?(?:(?:ref|source)\(|this[-+]?\}\}$)/.test(short)) unknownSources.add(key) @@ -711,7 +757,7 @@ function parseSelects(sql: string): ParsedSelects { sources.set(key, read) sourceText.set(key, text) } - return { items, sources, sourceText, unknownSources, predicates, unmodelled, jinjaItems } + return { items, sources, sourceText, unknownSources, predicates, unmodelled, misread, jinjaItems, jinjaCalls, sourceRanges } } /** @@ -1066,7 +1112,7 @@ export const SILENT_JINJA_TAG = /^\{%[-+]?\s*(?:if|elif|else|endif|for|endfor|se // string, a count or a length, and a date reduced to a part or a difference. // Any other call (`coalesce`, `trim`, `max`, `replace`, a cast) keeps the value. const MASKING_NAME = - /hash|md5|hmac|fingerprint|encrypt|cipher|mask|redact|anonymi[sz]e|pseudonymi[sz]e|tokeni[sz]e|obfuscate|scramble|(?:^|_)(?:sha|crc)(?:\d|_|$)/i + /hash|md5|hmac|fingerprint|surrogate_key|encrypt|cipher|mask|redact|anonymi[sz]e|pseudonymi[sz]e|tokeni[sz]e|obfuscate|scramble|(?:^|_)(?:sha|crc)(?:\d|_|$)/i const MASKING_EXACT = new Set( "left right substr substring regexp_replace translate length len char_length character_length count count_if countif approx_count_distinct datediff date_diff timestampdiff timestamp_diff months_between age date_trunc datetrunc extract date_part datepart year".split( " ", @@ -1117,6 +1163,8 @@ const SEGMENT_ONLY = new RegExp(String.raw`^${SEGMENT}$`) function starItem(text: string): StarItem | undefined { const head = STAR_HEAD.exec(text) if (!head) { + // A positional column (`$2`) or a column pattern (`columns('ss.')`) names nothing. + if (/(? [c] } // A `*` inside the item that is not a multiplication (an operand on both // sides): `object_construct(*)`, `struct(t.*)`, `as struct *`. `count(*)` // reads no column. @@ -1205,16 +1253,17 @@ export interface RawReach { reaches: (item: SelectItem) => boolean /** The item may pass `column`'s value on to the final output unmasked: it * carries it and reaches the output, or is a `*` that does not exclude or - * mask it and whose name for it reaches the output. */ + * mask it and whose name for it reaches the output. Always, when the SQL's + * quoting or select prefix may have been misread. */ passes: (item: SelectItem, column: string) => boolean /** The final output may expose a column named `column` raw: through an item * that carries it and reaches the output, or through a `*` (or a Jinja * column list) over a table whose columns the SQL does not list. */ mayExpose: (column: string) => boolean - /** The 1-based `line` sits in a clause that selects nothing: the nearest - * clause word before it, outside closed parentheses, is `where`, `group by`, - * `order by`, `partition by`, `having`, `qualify`, `on`, `using`, `from` or - * `join`. `false` when that cannot be told (no clause word, or `select`). */ + /** The 1-based `line` sits in a clause that selects nothing: it is outside + * every FROM/JOIN source, and the nearest clause word before it, outside + * closed parentheses, is `where`, `group by`, `order by`, `partition by`, + * `having`, `qualify` or `on`. `false` when that cannot be told. */ inClause: (line: number) => boolean } @@ -1224,7 +1273,7 @@ const JINJA_GLUED_KEYWORD = /\}\}(?=(?:select|from|join|union|intersect|except|minus|with|where|on|using|as)\b)|(? SILENT_JINJA_TAG.test(t)) - const byKey = new Map() const firstNames = new Map() + const byKey = new Map() for (const item of items) { const key = `${item.scope}#${item.branch}` const list = byKey.get(key) @@ -1273,6 +1328,8 @@ export function rawReach(sql: string): RawReach { // A later set-operation branch outputs under the first branch's name. const outName = (item: SelectItem) => item.branch === 0 ? item.name : (firstNames.get(`${item.scope}\u0000${item.position}`) ?? item.name) + // A name that came out of Jinja (`ssn as {{ col }}`) is not known. + const unknownName = (name: string | undefined) => !name || /_{4,}/.test(name) const scopes = new Set(items.map((i) => i.scope)) const fromSubqueries = new Set() for (const list of sources.values()) for (const src of list) if (src.name.includes(">")) fromSubqueries.add(src.name) @@ -1281,12 +1338,6 @@ export function rawReach(sql: string): RawReach { return false } const naming = (src: Source) => [src.alias, src.name, src.short].filter((x): x is string => !!x) - // Every select whose rows can reach an output (not the operand of a - // condition), with the selects it is nested in, at any depth. - const keyed = [...sources.keys()].map((key) => ({ key, scope: key.slice(0, key.lastIndexOf("#")) })) - const selects = keyed - .filter((sel) => !inPredicate(sel.scope)) - .map((sel) => ({ ...sel, outer: keyed.filter((o) => sel.scope.startsWith(`${o.scope}>`)) })) const stars = new Map() const starOf = (item: SelectItem) => { if (!stars.has(item)) stars.set(item, starItem(item.text)) @@ -1301,6 +1352,134 @@ export function rawReach(sql: string): RawReach { return reads } + // Every select whose rows can reach an output (not the operand of a + // condition): its own sources, those of the selects it is nested in, the + // words of its source list, and its items by the column they carry. + interface Select { + key: string + scope: string + own: Source[] + outer: Source[] + /** Sources that did not parse, here or in an enclosing select. */ + blind: boolean + /** Every identifier in the source list (`s.tags` → `s`, `tags`). */ + words: Set + /** Identifiers of the source list that stand alone (no dot beside them). */ + bare: Set + stars: SelectItem[] + jinja: SelectItem[] + calls: SelectItem[] + /** Non-star items by a column they select raw or read unmasked. */ + byColumn: Map + /** Non-star items by the first segment of a dotted path they hold (`tax.v` → `tax`). */ + byPathHead: Map + } + const WORD = /["\x60]?([A-Za-z_][\w$]*)["\x60]?/g + const BARE = /(? ({ key, scope: key.slice(0, key.lastIndexOf("#")) })) + const push = (map: Map, k: string, item: SelectItem) => { + const list = map.get(k) + if (!list) map.set(k, [item]) + else if (list[list.length - 1] !== item) list.push(item) + } + const selects: Select[] = keyed + .filter((sel) => !inPredicate(sel.scope)) + .map((sel) => { + const enclosing = keyed.filter((o) => sel.scope.startsWith(`${o.scope}>`)) + const text = sourceText.get(sel.key) ?? "" + const out: Select = { + ...sel, + own: sources.get(sel.key) ?? [], + outer: enclosing.flatMap((o) => sources.get(o.key) ?? []), + blind: unknownSources.has(sel.key) || enclosing.some((o) => unknownSources.has(o.key)), + words: new Set([...text.matchAll(WORD)].map((m) => m[1].toLowerCase())), + bare: new Set([...text.matchAll(BARE)].map((m) => m[1].toLowerCase())), + stars: [], + jinja: [], + calls: [], + byColumn: new Map(), + byPathHead: new Map(), + } + for (const item of byKey.get(sel.key) ?? []) { + if (jinjaItems.has(item)) out.jinja.push(item) + if (jinjaCalls.has(item)) out.calls.push(item) + if (starOf(item)) { + out.stars.push(item) + continue + } + if (item.rawColumn) push(out.byColumn, item.rawColumn, item) + else for (const r of readsOf(item)) push(out.byColumn, r.column, item) + for (const m of item.text.matchAll(PATH)) push(out.byPathHead, m[1].toLowerCase(), item) + } + return out + }) + const selectsOfScope = new Map() + const selectByKey = new Map() + for (const sel of selects) { + selectByKey.set(sel.key, sel) + const list = selectsOfScope.get(sel.scope) + if (list) list.push(sel) + else selectsOfScope.set(sel.scope, [sel]) + } + // The names an item's value leaves its select under: its own output name, + // and that of any item of the same select reading it by its alias (`ssn as + // raw, raw as tax_ref`), which some engines allow. + const leaving = new Map>() + const leavesAs = (item: SelectItem) => { + let out = leaving.get(item) + if (out) return out + const sel = selectByKey.get(`${item.scope}#${item.branch}`) + const names = new Set() + const seen = new Set([item]) + for (const queue = [item]; queue.length; ) { + const cur = queue.pop()! + names.add(outName(cur)) + if (!cur.name) continue + for (const other of sel?.byColumn.get(cur.name) ?? []) { + const byAlias = other.rawColumn ? !other.rawQualifier : readsOf(other).some((r) => r.column === cur.name && !r.qualifier) + if (!byAlias || seen.has(other)) continue + seen.add(other) + queue.push(other) + } + } + leaving.set(item, (out = [...names])) + return out + } + // Set-operation branches pair their items by position. That holds only when + // every branch lists as many items with its `*` items at the same places + // (`select *, 'a' as src … union all select *, 'b' …`). + const misaligned = new Map() + const branchesMisaligned = (scope: string) => { + let out = misaligned.get(scope) + if (out === undefined) { + const shapes = (selectsOfScope.get(scope) ?? []).map((sel) => + (byKey.get(sel.key) ?? []).map((i) => (starOf(i) || jinjaItems.has(i) ? "*" : "c")).join(""), + ) + out = shapes.some((shape) => shape !== shapes[0]) + misaligned.set(scope, out) + } + return out + } + // The selects that can read a scope: those naming it in FROM/JOIN, those + // nested in one that does (a correlated read), those whose source list names + // it without parsing it as a source, and those whose sources did not parse. + const readersByName = new Map>() + const blindSelects = selects.filter((sel) => sel.blind) + for (const sel of selects) { + for (const name of new Set([...sel.own.map((src) => src.name), ...sel.outer.map((src) => src.name), ...sel.bare])) { + const set = readersByName.get(name) + if (set) set.add(sel) + else readersByName.set(name, new Set([sel])) + } + } + const readers = new Map() + const readersOf = (scope: string) => { + let out = readers.get(scope) + if (!out) readers.set(scope, (out = [...new Set([...(readersByName.get(scope) ?? []), ...blindSelects])])) + return out + } + const reach = (scope: string, name: string | undefined, seen: Set): boolean => { if (scope === ROOT_SCOPE) return true if (scope.includes(">")) { @@ -1308,56 +1487,52 @@ export function rawReach(sql: string): RawReach { // Not a FROM source: a scalar subquery, a lateral or a set-operation branch. if (!fromSubqueries.has(scope)) return true } - if (!name) return true + if (unknownName(name) || branchesMisaligned(scope)) return true const visit = `${scope}\u0000${name}` if (seen.has(visit)) return false seen.add(visit) - for (const sel of selects) { - const own = (sources.get(sel.key) ?? []).filter((src) => src.name === scope) - const outerSelects = sel.outer - const outer = outerSelects.flatMap((o) => (sources.get(o.key) ?? []).filter((src) => src.name === scope)) - // Sources that did not parse, here or in an enclosing select, or a list - // that names the scope without parsing it as a source. - const blind = - unknownSources.has(sel.key) || - outerSelects.some((o) => unknownSources.has(o.key)) || - (!own.length && !scope.includes(">") && wordIn(sourceText.get(sel.key), scope, false)) - if (!own.length && !outer.length && !blind) continue + for (const sel of readersOf(scope)) { + const own = sel.own.filter((src) => src.name === scope) + const outer = sel.outer.filter((src) => src.name === scope) + const blind = sel.blind || (!own.length && !outer.length) // A table function, `unpivot` or array join over the column moves its // values under another name. - if (wordIn(sourceText.get(sel.key), name)) return true + if (sel.words.has(name!)) return true const scopeNames = new Set([...own, ...outer].flatMap(naming)) - const otherNames = new Set( - [sel, ...outerSelects].flatMap((x) => (sources.get(x.key) ?? []).filter((src) => src.name !== scope).flatMap(naming)), - ) + let others: Set | undefined + const otherNames = () => + (others ??= new Set([...sel.own, ...sel.outer].filter((src) => src.name !== scope).flatMap(naming))) // A qualifier names the scope, or no source the parser knows: an alias it // did not read (`src pivot (…) p`) may still be the scope, so that counts. const fromScope = (qualifier?: string) => - !qualifier || blind || scopeNames.has(qualifier) || !otherNames.has(qualifier) - for (const item of byKey.get(sel.key) ?? []) { - if (jinjaItems.has(item)) return true - const star = starOf(item) - if (star) { - // An unqualified `*` spans the select's own sources only. - if (star.qualifier ? !fromScope(star.qualifier) : !own.length && !blind) continue - // `x.*` over a struct column named like the output expands its fields. - if (star.qualifier === name && !scopeNames.has(name)) return true - if (star.opaque) return true - if (star.carries(name).some((carried) => reach(sel.scope, carried, seen))) return true - continue - } - // The name selected raw, or read by an expression that keeps its value. + !qualifier || blind || scopeNames.has(qualifier) || !otherNames().has(qualifier) + if (sel.jinja.length) return true + // A macro call naming the column may emit it raw (`dbt.safe_cast("ssn", …)`). + const carriedOn = (item: SelectItem) => leavesAs(item).some((as) => reach(sel.scope, as, seen)) + for (const item of sel.calls) if (wordIn(jinjaCalls.get(item), name!) && carriedOn(item)) return true + for (const item of sel.stars) { + const star = starOf(item)! + // An unqualified `*` spans the select's own sources only. + if (star.qualifier ? !fromScope(star.qualifier) : !own.length && !blind) continue + // `x.*` over a struct column named like the output expands its fields. + if (star.qualifier === name && !scopeNames.has(name!)) return true + if (star.opaque) return true + if (star.carries(name!).some((carried) => reach(sel.scope, carried, seen))) return true + } + // The name selected raw, or read by an expression that keeps its value. + for (const item of sel.byColumn.get(name!) ?? []) { const keeps = item.rawColumn - ? item.rawColumn === name && fromScope(item.rawQualifier) + ? fromScope(item.rawQualifier) : readsOf(item).some((r) => r.column === name && fromScope(r.qualifier)) - if (keeps) { - if (reach(sel.scope, outName(item), seen)) return true - continue - } - // The scope as a whole row: `select s from src s`, `to_json(s)`. - const row = (r: { qualifier?: string; column: string }) => !r.qualifier && scopeNames.has(r.column) - if (item.rawColumn ? !item.rawQualifier && scopeNames.has(item.rawColumn) : readsOf(item).some(row)) return true + if (keeps && carriedOn(item)) return true } + // A field of the column (`tax.v`, `tax.a.b`), when `tax` names no source. + if (!scopeNames.has(name!) && !otherNames().has(name!)) + for (const item of sel.byPathHead.get(name!) ?? []) if (carriedOn(item)) return true + // The scope as a whole row: `select s from src s`, `to_json(s)`. + for (const alias of scopeNames) + for (const item of sel.byColumn.get(alias) ?? []) + if (item.rawColumn ? !item.rawQualifier : readsOf(item).some((r) => r.column === alias && !r.qualifier)) return true } return false } @@ -1368,10 +1543,18 @@ export function rawReach(sql: string): RawReach { if (out === undefined) memo.set(key, (out = reach(scope, name, new Set()))) return out } - const carries = (item: SelectItem, column: string) => - item.rawColumn ? item.rawColumn === column : readsOf(item).some((r) => r.column === column) - const reaches = (item: SelectItem) => opaque || reachMemo(item.scope, outName(item)) + // An output under a PII name counts for that name whatever unmasked value it + // holds (`tax_id_number as ssn`). + const carries = (item: SelectItem, column: string) => { + if (jinjaItems.has(item) || wordIn(jinjaCalls.get(item), column)) return true + if (item.rawColumn) return item.rawColumn === column || item.name === column + const reads = readsOf(item) + return reads.some((r) => r.column === column) || (item.name === column && reads.length > 0) + } + const reaches = (item: SelectItem) => opaque || leavesAs(item).some((as) => reachMemo(item.scope, as)) const passes = (item: SelectItem, column: string) => { + // The item's own text cannot be trusted: nothing shows the column masked. + if (parsed.misread) return true const star = starOf(item) if (!star) return carries(item, column) && reaches(item) if (star.opaque) return opaque || reachMemo(item.scope, undefined) @@ -1383,24 +1566,27 @@ export function rawReach(sql: string): RawReach { let out = exposeMemo.get(column) if (out !== undefined) return out out = - items.some((i) => carries(i, column) && reaches(i)) || + items.some((i) => !starOf(i) && carries(i, column) && reaches(i)) || selects.some((sel) => { - // A select reading a table whose columns are not listed in the SQL. - const tables = (sources.get(sel.key) ?? []).filter((src) => !scopes.has(src.name)) + // A select reading a table whose columns are not listed in the SQL. A + // CTE that reads its own name reads the table of that name. + const isTable = (src: Source) => !scopes.has(src.name) || src.name === sel.scope + const tables = sel.own.filter(isTable) if (!tables.length && !unknownSources.has(sel.key)) return false const tableNames = new Set(tables.flatMap(naming)) - const derivedNames = new Set((sources.get(sel.key) ?? []).filter((src) => scopes.has(src.name)).flatMap(naming)) - return (byKey.get(sel.key) ?? []).some((item) => { - if (jinjaItems.has(item)) return reachMemo(sel.scope, column) - const star = starOf(item) - if (star) { - // A `*` qualified by a CTE or subquery passes that scope's columns only. - if (star.qualifier && derivedNames.has(star.qualifier) && !tableNames.has(star.qualifier)) return false - return star.opaque ? reachMemo(sel.scope, column) : star.carries(column).some((c) => reachMemo(sel.scope, c)) - } - // A table as a whole row. - return !!item.rawColumn && !item.rawQualifier && tableNames.has(item.rawColumn) && reachMemo(sel.scope, column) - }) + const derivedNames = new Set(sel.own.filter((src) => !isTable(src)).flatMap(naming)) + if (sel.jinja.length) return reachMemo(sel.scope, column) + if (sel.stars.some((item) => { + const star = starOf(item)! + // A `*` qualified by a CTE or subquery passes that scope's columns only. + if (star.qualifier && derivedNames.has(star.qualifier) && !tableNames.has(star.qualifier)) return false + return star.opaque ? reachMemo(sel.scope, column) : star.carries(column).some((c) => reachMemo(sel.scope, c)) + })) + return true + // A table as a whole row. + return [...tableNames].some((t) => + (sel.byColumn.get(t) ?? []).some((item) => !!item.rawColumn && !item.rawQualifier && reachMemo(sel.scope, column)), + ) }) exposeMemo.set(column, out) return out @@ -1415,6 +1601,10 @@ export function rawReach(sql: string): RawReach { } const start = lineStarts[line - 1] if (start === undefined) return false + // A FROM/JOIN source (`unnest([\n ssn\n])`, `unpivot (v for k in (\n ssn\n))`) + // can put the column in the output under another name. + const stop = lineStarts[line] ?? masked.length + if (sourceRanges.some(([from, to]) => from < stop && start < to)) return false // Backwards from the line, skipping parentheses that closed before it. let depth = 0 for (let i = start - 1; i >= 0; i--) { diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 816b45a98d..a153e2d053 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -525,6 +525,63 @@ describe("rawReach", () => { ]) }) + test("shapes the parser does not model block: every `ssn` line counts as reaching", () => { + // As the orchestrator asks it: the items on the line, else the clause it sits in. + const lineReaches = (sql: string) => { + const r = rawReach(sql) + return sql.split("\n").flatMap((text, at) => { + if (!/\bssn\b/i.test(text)) return [] + const items = r.items.filter((i) => i.startLine <= at + 1 && at + 1 <= i.endLine) + return [items.length ? items.some((i) => r.passes(i, "ssn")) : !r.inClause(at + 1) || r.mayExpose("ssn")] + }) + } + const cases: Array<[string, string]> = [ + ["`select all (select \u2026)` is a scalar subquery, not a condition", "select all\n (select\n ssn\n from customers limit 1) as x\nfrom t"], + ["a column list on a subquery alias renames its columns", "select x\nfrom (\n select\n ssn\n from customers\n) as t(x)"], + ["a column list on a CTE alias renames its columns", "with c as (\n select\n ssn\n from customers\n)\nselect tax\nfrom c as y(tax)"], + ["`union all by name` pairs columns by name", "with u as (\n select 1 as a, 2 as b from t\n union all by name\n select\n ssn as b,\n 3 as a\n from customers\n)\nselect b from u"], + ["a `*` in a later union branch lands under the first branch's names", "with c as (\n select\n id,\n ssn\n from customers\n),\nu as (\n select id, name as label from people\n union all\n select * from c\n)\nselect id, label from u"], + ["a `*` in the first union branch shifts the positions after it", "with u as (\n select *, 1 as k from a\n union all\n select 1,\n ssn,\n 3\n from customers\n)\nselect q from u"], + ["an array join in FROM over the column", "select c.id, v\nfrom customers c, unnest([\n c.ssn\n]) as v"], + ["`unpivot` in FROM over the column", "select id, val\nfrom customers unpivot (val for col in (\n ssn,\n name\n))"], + ["`pivot` in FROM over the column", "select id, a, b\nfrom customers pivot (max(\n ssn\n) for k in ('a', 'b'))"], + ["`lateral flatten` in FROM over the column", "select c.id, f.value as v\nfrom customers c,\nlateral flatten(input => array_construct(\n c.ssn\n)) f"], + ["a DDL wrapper is not one query", "create table out as (\n select\n ssn\n from customers\n)"], + ["a macro call that emits the column, on its own line", "select\n {{ dbt.safe_cast(\"ssn\", api.Column.translate_type(\"string\")) }} as tax_id\nfrom customers"], + ["`adapter.quote` of the column, on its own line", "select\n {{ adapter.quote(\"ssn\") }} as tax_id\nfrom customers"], + ["a reader's macro call that names the column", "with c as (\n select\n ssn\n from customers\n)\nselect {{ dbt.safe_cast(\"ssn\", \"varchar\") }} as tax_id from c"], + ["a `columns('\u2026')` pattern in the reader", "with c as (\n select\n id,\n ssn\n from customers\n)\nselect columns('id|ss.') from c"], + ["a backslash-escaped quote before the line", "select\n replace(name, '\\'', '') as n,\n ssn\nfrom customers"], + ["a `#` comment holding an apostrophe", "select\n id, # don't\n ssn\nfrom customers"], + ["`match_recognize` measures over the column", "select id, s\nfrom customers match_recognize (\n partition by id order by ts\n measures last(\n ssn\n ) as s\n pattern (a)\n define a as true\n)"], + ["a CTE named like the table it reads with `*`", "with customers as (\n select * from customers\n where\n ssn is not null\n)\nselect * from customers"], + ["a parenthesised first union branch", "with u as (\n (select id, name from people)\n union all\n select\n id,\n ssn\n from customers\n)\nselect id, name from u"], + ["`select distinct top n`", "select distinct top 10\n ssn\nfrom customers"], + ["`select top n distinct`", "select top 10 distinct\n ssn\nfrom customers"], + ["an alias that is a Jinja call", "with c as (\n select\n ssn as {{ var('tax_col') }}\n from customers\n)\nselect id, tax_ref from c"], + ["an alias that is a Jinja variable", "with c as (\n select\n ssn as {{ tax_col }}\n from customers\n)\nselect id, tax_ref from c"], + ["a struct field of the CTE's column", "with c as (\n select struct_pack(\n v := ssn\n ) as tax from customers\n)\nselect tax.v from c"], + ["a struct field of the CTE's column (BigQuery)", "with c as (\n select struct(\n ssn as v\n ) as tax from customers\n)\nselect tax.v from c"], + ["an array join in a CTE's FROM, then `select *`", "with x as (\n select c.id, v\n from customers c, unnest([\n c.ssn\n ]) as v\n)\nselect * from x"], + ["another column output under the PII name", "select\n id,\n tax_id_number as ssn\nfrom customers"], + ["a backslash-escaped quote that swallows the line", "select\n replace(name, '\\'', '') as n,\n ssn\nfrom customers\nwhere status = 'active'"], + ["a positional column in the reader", "with c as (\n select\n id,\n ssn\n from customers\n)\nselect $2 as tax_ref from c"], + ["a later item of the same select reading the alias", "with c as (\n select\n id,\n ssn as raw_ssn,\n raw_ssn as tax_ref\n from customers\n)\nselect id, tax_ref from c"], + ] + for (const [name, sql] of cases) { + const lines = lineReaches(sql) + expect({ name, lines: lines.length > 0, reaches: lines.every(Boolean) }).toEqual({ name, lines: true, reaches: true }) + } + }) + + test("deeply nested subqueries stay fast", () => { + const depth = 800 + const sql = "select x from " + "(select x from ".repeat(depth) + `(select\n ssn as x\n from ${REF}) t` + ") t".repeat(depth) + const t0 = performance.now() + expect(reaches(sql)).toBe(true) + expect(performance.now() - t0).toBeLessThan(3000) + }) + test("malformed SQL and deep chains do not throw or stall", () => { for (const sql of ["ssn", "select\n ssn\nfrom", `with src as (\n select ssn from ${REF}\nselect customer_id from src`, "select customer_id))\nfrom src)", "with a as (select * from a) select * from a"]) { const r = rawReach(sql) From c7a3d3dd1715905186cc463b8ff9036ade2487cf Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 22:48:11 +0530 Subject: [PATCH 76/81] fix(review): follow a PII column only through SQL recognised as plain select-from queries, and read columns by token MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A second adversarial pass found more shapes the reach analysis did not model. Listing such shapes one by one does not end, so the analysis now states what it does model and treats the rest as reaching the output: - the SQL is CTEs and queries of the form `select … from …` joined by set operators: a `select` that does not open its query (`from c select x`, pipe syntax, two Jinja alternatives of one body), a CTE or final query without a `select` (`table c`, `values`), a set operator not followed by a select (`by name`, `corresponding`), a CTE defined twice or named through Jinja are not modelled; - set-operation branches pair columns by position, which is computed through a plain `*` over a CTE or subquery and unknown otherwise (a `*` over a table or a join, a Jinja list), so `select * from a union all select * from b` with the columns in another order lands under the right name; - a column is read wherever its name stands in an item's unmasked expression, instead of through the structured reader, which drops `within group (order by …)`, a column named like a keyword (`partition`, `filter`), a method call (`ssn.lower()`) and a struct field; - an item holding a Jinja statement tag (a conditional mask or alias, a loop) or an expression glued to a name may be anything, and its name is unknown, as after `collate`; - an item split inside `[…]` / `{…}` and a quoted identifier holding a parenthesis mean the items were misread; - a quoted name that is not one word (`"Tax Ref"`) is matched in full, and `try_unmask(…)` / `reveal_…(…)` are not masking calls. The orchestrator asks about the analysis's own items, so what it knows about an item (Jinja in it) is not lost. Co-Authored-By: Claude --- .../src/altimate/review/orchestrate.ts | 4 +- .../src/altimate/review/rule-catalog.ts | 373 ++++++++++++------ .../test/altimate/review-rule-catalog.test.ts | 57 ++- 3 files changed, 315 insertions(+), 119 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 240ca286a6..64ff9ac1ad 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1642,14 +1642,14 @@ export async function runReview(input: OrchestrateInput): Promise h.column))) return false const reach = headReach(f.file) - const head = reindentInfo(f.file)?.head ?? [] const mayReachOutput = (hit: { column: string; line: string }) => { const column = hit.column.toLowerCase() const lineNos = headLineNumbers(f.file, hit.line) if (!reach || !lineNos.length) return true // Any head line with this text counts: the diff does not say which one it is. return lineNos.some((n) => { - const items = head.filter((i) => i.startLine <= n && n <= i.endLine) + // The analysis's own items: it knows them by identity. + const items = reach.items.filter((i) => i.startLine <= n && n <= i.endLine) if (items.length) return items.some((i) => reach.passes(i, column)) return !reach.inClause(n) || reach.mayExpose(column) }) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 35c5fef623..a724ec75c9 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -430,18 +430,24 @@ interface ParsedSelects { /** Nested queries that are the operand of `in`, `exists`, `any`, `some` or * `all`: their rows decide a condition and never reach an output. */ predicates: Set - /** The SQL has a shape whose scopes, select lists or output names are not - * modelled: a column list on a CTE or on a CTE/subquery alias (`a (x, y) as - * (…)`, `from c as t(x)`), a `with` inside parentheses, a parenthesised - * set-operation branch, `union … by name`, a select list that stops at a + /** The SQL is not, as a whole, CTEs and queries of the form `select … from …` + * joined by set operators, with names the parser can follow. Anything else + * is unmodelled: a `select` that does not open its query (`from c select + * x`, `|>`, two Jinja alternatives of one body), a CTE or a final query with + * no `select` (`table c`, `values`, a macro), a set operator not followed by + * a select (`union all by name`, `corresponding`), a parenthesised + * set-operation branch, a `with` inside parentheses, a column list on a CTE + * or on a CTE/subquery alias (`a (x, y) as (…)`, `from c as t(x)`), a CTE + * defined twice or named through Jinja, a select list that stops at a * clause word used as a column (`select topic, offset, ssn from …`), or a * statement other than one query. */ unmodelled: boolean /** The select items themselves may be wrong: quoting the masker may have * misread (a literal spanning lines, an unpaired quote, a `#`: a * backslash-escaped quote or a `#` comment with an apostrophe swallows - * SQL), or a select prefix it does not strip (`distinct top 10`, `as - * struct`) became part of the first item. */ + * SQL; a quoted identifier holding a parenthesis), a select prefix it does + * not strip (`distinct top 10`, `as struct`) became part of the first item, + * or an item was split inside `[…]` / `{…}`. */ misread: boolean /** Items holding a Jinja expression that may stand for a raw column or a * column list: an item without an alias, or one whose expression is not a @@ -453,6 +459,8 @@ interface ParsedSelects { jinjaCalls: Map /** Offsets `[start, stop)` of every FROM/JOIN source segment (as `sourceText`). */ sourceRanges: Array<[number, number]> + /** Per nested query, the offset of the `(` that opens it. */ + scopeOpen: Map } /** Offset of the `)` closing the `(` at `open` in masked SQL, or the end. */ @@ -492,12 +500,17 @@ function parseSelects(sql: string): ParsedSelects { let misread = (sql.match(MASKED_TOKEN) ?? []).some((m) => m.startsWith("'") && m.includes("\n")) || (s.match(/'/g)?.length ?? 0) % 2 === 1 || - s.includes("#") + s.includes("#") || + (s.match(/"(?:[^"]|"")*"|\x60[^\x60]*\x60/g) ?? []).some((quoted) => /[()]/.test(quoted)) // One query only: a DDL/DML wrapper or a second statement is not a model. + // A set operator is followed by its next select (not `by name`, `table c`). let unmodelled = /^[\s_]*(?:create|insert|merge|update|delete|alter|drop)\b/i.test(s) || /;\s*\S/.test(s) || - /\b(?:union|intersect|except|minus)\s+(?:all\s+|distinct\s+)?by\s+name\b/i.test(s) + s.includes("|>") || + /(?() + const selectScopes = new Set() // The scope each nested query's `(` opens, so a FROM subquery is a named source. const parenScope = new Map() // Each select's scope, branch and the offset its select list ends at. @@ -561,12 +574,16 @@ function parseSelects(sql: string): ParsedSelects { // other parenthesis (a call, a grouping) stays in its parent's scope. if (/^\s*with\b/i.test(s.slice(i + 1, i + 50))) unmodelled = true if (cte && !/^as$/i.test(cte[1])) { - scopes.push(unquote(cte[1])) - cteNames.add(unquote(cte[1])) - if (cte[2]) unmodelled = true + const name = unquote(cte[1]) + scopes.push(name) + // A column list, a second definition (Jinja alternatives), or a name + // that came out of Jinja or collides with a nested query's key. + if (cte[2] || cteNames.has(name) || name.includes(">") || /_{4,}/.test(name)) unmodelled = true + cteNames.add(name) } else if (/^[\s(]*select\b/i.test(s.slice(i + 1, i + 200))) { scopes.push(nestedKey(parent, i)) parenScope.set(i, scopes[scopes.length - 1]) + scopeOpen.set(scopes[scopes.length - 1], i) const before = s.slice(Math.max(0, i - 40), i) const setOperand = /\b(?:union|intersect|except|minus)(?:\s+all|\s+distinct)?\s*$/i.test(before) if ( @@ -587,6 +604,18 @@ function parseSelects(sql: string): ParsedSelects { } if ((c !== "s" && c !== "S") || isWordChar(s[i - 1]) || !/^select\b/i.test(s.slice(i, i + 7))) continue const scope = scopes[scopes.length - 1] + selectScopes.add(scope) + // A select opens its query: after `(`, the `)` of the CTE list, a set + // operator, or nothing but Jinja at the start. After anything else (`from + // c select x`, a second Jinja alternative) the query is not `select … from …`. + const lead = s.slice(0, i).trimEnd() + if ( + lead && + !/[()]$/.test(lead) && + !/(? raw.split(ch).length - 1 + if (count("[") !== count("]") || count("{") !== count("}")) misread = true + const source = sql.slice(itemStart, stop) // Jinja expressions of the item (masked to `_`, so not ones inside a literal). - const jinja = [...sql.slice(itemStart, stop).matchAll(/\{\{[\s\S]*?\}\}/g)].filter( - (m) => s[itemStart + m.index!] === "_", + const jinja = [...source.matchAll(/\{\{[\s\S]*?\}\}/g)].filter((m) => s[itemStart + m.index!] === "_") + if ( + (jinja.length && (!splitAlias(item.text).alias || jinja.some((m) => !m[0].includes("(")))) || + // A statement tag in the item (a conditional wrapper or alias, a loop), + // or an expression glued to a name (`ssn{{ suffix }}`): its text is not its SQL. + source.includes("{%") || + /[\w$]\{\{|\}\}[\w$]/.test(source) ) - if (jinja.length && (!splitAlias(item.text).alias || jinja.some((m) => !m[0].includes("(")))) jinjaItems.add(item) + jinjaItems.add(item) const calls = jinja.filter((m) => { const macro = /([A-Za-z_]\w*)\s*\(/.exec(m[0])?.[1] return !!macro && !isMaskingCall(macro) @@ -679,8 +717,10 @@ function parseSelects(sql: string): ParsedSelects { let segment = -1 const closeSegment = (stop: number) => { if (segment >= 0) { - text += ` ${s.slice(segment, stop)}` - sourceRanges.push([segment, stop]) + const part = s.slice(segment, stop) + text += ` ${part}` + // Without the white space around it, so the range holds no line it only touches. + if (part.trim()) sourceRanges.push([segment + part.length - part.trimStart().length, segment + part.trimEnd().length]) } segment = -1 } @@ -714,6 +754,8 @@ function parseSelects(sql: string): ParsedSelects { const at = after + ref[0].length - last.length // A Jinja `{{ ref('x') }}` is masked to underscores: name it by its source text. short = /^_+$/.test(last) ? sql.slice(at, at + last.length).replace(/\s+/g, "").toLowerCase() : unquote(last) + // A name partly out of Jinja (`stg_{{ src }}`) could be anything, a CTE included. + if (!/^_+$/.test(last) && /_{4,}/.test(last)) unknownSources.add(key) // Database and schema stay part of the identity: `restricted.customers` // and `public.customers` are different tables. name = [...segments.slice(0, -1).map(unquote), short].join(".") @@ -757,7 +799,9 @@ function parseSelects(sql: string): ParsedSelects { sources.set(key, read) sourceText.set(key, text) } - return { items, sources, sourceText, unknownSources, predicates, unmodelled, misread, jinjaItems, jinjaCalls, sourceRanges } + // Every CTE and the final query hold a select (not `table c`, `values`, a macro). + if (!selectScopes.has(ROOT_SCOPE) || [...cteNames].some((name) => !selectScopes.has(name))) unmodelled = true + return { items, sources, sourceText, unknownSources, predicates, unmodelled, misread, jinjaItems, jinjaCalls, sourceRanges, scopeOpen } } /** @@ -1118,22 +1162,29 @@ const MASKING_EXACT = new Set( " ", ), ) -// `unmask(…)`, `decrypt(…)`, `detokenize(…)` undo one. +// `unmask(…)`, `decrypt(…)`, `try_detokenize(…)`, `reveal_masked(…)` undo one. const isMaskingCall = (name: string) => - MASKING_EXACT.has(name.toLowerCase()) || (MASKING_NAME.test(name) && !/^(?:de|un)/i.test(name)) + MASKING_EXACT.has(name.toLowerCase()) || + (MASKING_NAME.test(name) && !/(?:^|_)(?:de|un)|reveal|plain|clear|raw/i.test(name)) const NULL_TEST = new RegExp(String.raw`(? { +function unmaskedExpr(text: string): string { let e = splitAlias(text).expr for (let m = /\(\s*select\b/i.exec(e); m; m = /\(\s*select\b/i.exec(e)) e = `${e.slice(0, m.index)} ${e.slice(closingParen(e, m.index) + 1)}` + const clause = /\)\s*(?:over|filter)\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 call = /(? { + const re = new RegExp( + String.raw`(? = [] + for (const m of expr.matchAll(re)) if (!m[3]) out.push({ qualifier: m[1] ? unquote(m[1]) : undefined, path: !!m[2] }) + return out } /** What a `*` select item passes on: which source it spans and under which @@ -1181,8 +1245,8 @@ function starItem(text: string): StarItem | undefined { const qualifier = segments.length ? segments[segments.length - 1] : undefined const dropped = new Set() // Entries of `replace (…)` then `rename (…)`, in the order they apply: the - // columns each entry's value comes from (unmasked), and its name. - const steps: Array<{ kind: "replace" | "rename"; from: string[]; to: string }> = [] + // unmasked expression each entry's value comes from, and its name. + const steps: Array<{ kind: "replace" | "rename"; from?: string; expr: string; to: string }> = [] let rest = text.slice(head[0].length) while (rest.trim()) { const m = /^\s*(exclude|except|replace|rename)\b\s*/i.exec(rest) @@ -1212,8 +1276,7 @@ function starItem(text: string): StarItem | undefined { const item = describeItem(entry) const { alias } = splitAlias(item.text) if (!alias) return { qualifier, opaque: true, carries: (c) => [c] } - const from = item.rawColumn ? [item.rawColumn] : unmaskedReads(item.text).map((r) => r.column) - steps.push({ kind: kind as "replace" | "rename", from, to: unquote(alias) }) + steps.push({ kind: kind as "replace" | "rename", from: item.rawColumn, expr: unmaskedExpr(item.text), to: unquote(alias) }) } } const carries = (column: string) => { @@ -1221,12 +1284,12 @@ function starItem(text: string): StarItem | undefined { let names = new Set([column]) for (const step of steps) { if (step.kind === "rename") { - if (step.from.some((f) => names.delete(f))) names.add(step.to) + if (step.from && names.delete(step.from)) names.add(step.to) continue } // `replace (expr as to)`: `to` now holds `expr`. It still holds the column - // only when `expr` reads it unmasked. - const kept = step.from.some((f) => names.has(f)) + // only when `expr` names it unmasked. + const kept = [...names].some((n) => columnUses(step.expr, n).length > 0) names.delete(step.to) if (kept) names.add(step.to) } @@ -1246,8 +1309,9 @@ const wordIn = (text: string | undefined, word: string, dotted = true) => export interface RawReach { /** Every select item of the SQL, as `selectItems` returns them. */ items: SelectItem[] - /** The item's output keeps `column`'s value: it selects it raw, or reads it in - * an expression outside any masking call (`coalesce(ssn, '')`, not `sha2(ssn)`). */ + /** The item's output keeps `column`'s value: it names the column outside any + * masking call (`ssn`, `coalesce(ssn, '')`, not `sha2(ssn)`), or outputs an + * unmasked value under that name (`tax_id_number as ssn`). */ carries: (item: SelectItem, column: string) => boolean /** The value this item outputs may reach the model's final output unmasked. */ reaches: (item: SelectItem) => boolean @@ -1286,10 +1350,11 @@ const SELECTS_NOTHING = /^(?:where|group by|order by|partition by|having|qualify * or correlated from a query nested in one that does) selects the item's * output name raw, or through a `*` that spans the scope and neither excludes * nor masks it, or in an expression that keeps its value (`coalesce(x, '')`, - * `max(x)`), and that query's own output reaches it in turn (`with a as (select - * ssn as x …), b as (select x from a) select x from b`). A query that reads the - * name only inside masking calls (`sha2(x)`, `right(x, 4)`), or does not select - * it, stops it. + * `max(x)`, a field `x.v`), and that query's own output reaches it in turn + * (`with a as (select ssn as x …), b as (select x from a) select x from b`). A + * column is read wherever its name stands in an item's unmasked expression + * (`unmaskedExpr`), so no kind of expression hides one. A query that names it + * only inside masking calls (`sha2(x)`, `right(x, 4)`), or not at all, stops it. * * Counted as reaching, because the names leaving them are unknown: * a nested query that is not a FROM source (a scalar subquery in a select @@ -1310,7 +1375,7 @@ const SELECTS_NOTHING = /^(?:where|group by|order by|partition by|having|qualify */ export function rawReach(sql: string): RawReach { const parsed = parseSelects(sql) - const { items, sources, sourceText, unknownSources, predicates, jinjaItems, jinjaCalls, sourceRanges } = parsed + const { items, sources, sourceText, unknownSources, predicates, jinjaItems, jinjaCalls, sourceRanges, scopeOpen } = parsed const opaque = parsed.unmodelled || parsed.misread || @@ -1325,16 +1390,21 @@ export function rawReach(sql: string): RawReach { else byKey.set(key, [item]) if (item.branch === 0) firstNames.set(`${item.scope}\u0000${item.position}`, item.name) } - // A later set-operation branch outputs under the first branch's name. - const outName = (item: SelectItem) => - item.branch === 0 ? item.name : (firstNames.get(`${item.scope}\u0000${item.position}`) ?? item.name) // A name that came out of Jinja (`ssn as {{ col }}`) is not known. const unknownName = (name: string | undefined) => !name || /_{4,}/.test(name) const scopes = new Set(items.map((i) => i.scope)) const fromSubqueries = new Set() for (const list of sources.values()) for (const src of list) if (src.name.includes(">")) fromSubqueries.add(src.name) + // The operand of a condition, at any depth. One inside a FROM source + // (`pivot (… for k in (select …))`) is not a condition. + const conditions = new Set( + [...predicates].filter((scope) => { + const at = scopeOpen.get(scope) + return at === undefined || !sourceRanges.some(([from, to]) => from <= at && at < to) + }), + ) const inPredicate = (scope: string) => { - for (let at = scope.length; at > 0; at = scope.lastIndexOf(">", at - 1)) if (predicates.has(scope.slice(0, at))) return true + for (let at = scope.length; at > 0; at = scope.lastIndexOf(">", at - 1)) if (conditions.has(scope.slice(0, at))) return true return false } const naming = (src: Source) => [src.alias, src.name, src.short].filter((x): x is string => !!x) @@ -1343,21 +1413,24 @@ export function rawReach(sql: string): RawReach { if (!stars.has(item)) stars.set(item, starItem(item.text)) return stars.get(item) } - // An expression item's unmasked reads. A `*` item names no column it reads - // (`* exclude (ssn)`), and a raw item is its column. - const readsByItem = new Map>() - const readsOf = (item: SelectItem) => { - let reads = readsByItem.get(item) - if (!reads) readsByItem.set(item, (reads = item.rawColumn || starOf(item) ? [] : unmaskedReads(item.text))) - return reads + // An item's expression without its masked parts (`unmaskedExpr`): a column it + // still names keeps its value. A `*` item names no column it reads. + const exprs = new Map() + const exprOf = (item: SelectItem) => { + let expr = exprs.get(item) + if (expr === undefined) exprs.set(item, (expr = starOf(item) ? "" : unmaskedExpr(item.text))) + return expr } + // `ssn collate "C"` reads as an implicit alias: the output name is not known. + const namedByGuess = (item: SelectItem) => jinjaItems.has(item) || /\bcollate\s+\S+$/i.test(item.text) // Every select whose rows can reach an output (not the operand of a // condition): its own sources, those of the selects it is nested in, the - // words of its source list, and its items by the column they carry. + // words of its source list, and its items by the identifiers they name. interface Select { key: string scope: string + items: SelectItem[] own: Source[] outer: Source[] /** Sources that did not parse, here or in an enclosing select. */ @@ -1369,20 +1442,12 @@ export function rawReach(sql: string): RawReach { stars: SelectItem[] jinja: SelectItem[] calls: SelectItem[] - /** Non-star items by a column they select raw or read unmasked. */ - byColumn: Map - /** Non-star items by the first segment of a dotted path they hold (`tax.v` → `tax`). */ - byPathHead: Map + /** Non-star items by each identifier their unmasked expression names. */ + byWord: Map } const WORD = /["\x60]?([A-Za-z_][\w$]*)["\x60]?/g const BARE = /(? ({ key, scope: key.slice(0, key.lastIndexOf("#")) })) - const push = (map: Map, k: string, item: SelectItem) => { - const list = map.get(k) - if (!list) map.set(k, [item]) - else if (list[list.length - 1] !== item) list.push(item) - } const selects: Select[] = keyed .filter((sel) => !inPredicate(sel.scope)) .map((sel) => { @@ -1390,6 +1455,7 @@ export function rawReach(sql: string): RawReach { const text = sourceText.get(sel.key) ?? "" const out: Select = { ...sel, + items: byKey.get(sel.key) ?? [], own: sources.get(sel.key) ?? [], outer: enclosing.flatMap((o) => sources.get(o.key) ?? []), blind: unknownSources.has(sel.key) || enclosing.some((o) => unknownSources.has(o.key)), @@ -1398,22 +1464,27 @@ export function rawReach(sql: string): RawReach { stars: [], jinja: [], calls: [], - byColumn: new Map(), - byPathHead: new Map(), + byWord: new Map(), } - for (const item of byKey.get(sel.key) ?? []) { + for (const item of out.items) { if (jinjaItems.has(item)) out.jinja.push(item) if (jinjaCalls.has(item)) out.calls.push(item) if (starOf(item)) { out.stars.push(item) continue } - if (item.rawColumn) push(out.byColumn, item.rawColumn, item) - else for (const r of readsOf(item)) push(out.byColumn, r.column, item) - for (const m of item.text.matchAll(PATH)) push(out.byPathHead, m[1].toLowerCase(), item) + for (const word of new Set([...exprOf(item).matchAll(WORD)].map((m) => m[1].toLowerCase()))) { + const list = out.byWord.get(word) + if (list) list.push(item) + else out.byWord.set(word, [item]) + } } return out }) + // The items of a select that may name `name`. A quoted name that is not one + // word (`"Tax Ref"`, `"a.b"`) is in no word index: every item is looked at. + const itemsNaming = (sel: Select | undefined, name: string) => + !sel ? [] : /^[A-Za-z_][\w$]*$/.test(name) ? (sel.byWord.get(name) ?? []) : sel.items.filter((i) => !starOf(i)) const selectsOfScope = new Map() const selectByKey = new Map() for (const sel of selects) { @@ -1434,11 +1505,10 @@ export function rawReach(sql: string): RawReach { const seen = new Set([item]) for (const queue = [item]; queue.length; ) { const cur = queue.pop()! - names.add(outName(cur)) + names.add(namedByGuess(cur) ? undefined : outName(cur)) if (!cur.name) continue - for (const other of sel?.byColumn.get(cur.name) ?? []) { - const byAlias = other.rawColumn ? !other.rawQualifier : readsOf(other).some((r) => r.column === cur.name && !r.qualifier) - if (!byAlias || seen.has(other)) continue + for (const other of itemsNaming(sel, cur.name)) { + if (seen.has(other) || !columnUses(exprOf(other), cur.name).some((use) => !use.qualifier)) continue seen.add(other) queue.push(other) } @@ -1446,21 +1516,85 @@ export function rawReach(sql: string): RawReach { leaving.set(item, (out = [...names])) return out } - // Set-operation branches pair their items by position. That holds only when - // every branch lists as many items with its `*` items at the same places - // (`select *, 'a' as src … union all select *, 'b' …`). + // The columns a select outputs, in order, when the SQL gives them: each item + // is one column, and a plain `*` over one CTE or subquery is that scope's + // columns. Not known for a `*` over a table, over a join, with modifiers, or + // for a Jinja list. + interface Layout { + names: Array + /** The output position each item starts at. */ + offsets: Map + /** For a `*` item, the columns it expands to. */ + spans: Map> + } + const layouts = new Map() + const layoutOf = (sel: Select): Layout | undefined => { + if (layouts.has(sel)) return layouts.get(sel) + layouts.set(sel, undefined) // a scope that reads itself has no known layout + const out: Layout = { names: [], offsets: new Map(), spans: new Map() } + for (const item of sel.items) { + out.offsets.set(item, out.names.length) + const star = starOf(item) + if (!star) { + if (jinjaItems.has(item)) return undefined + out.names.push(namedByGuess(item) ? undefined : item.name) + continue + } + if (star.opaque || !STAR.test(item.text) || sel.blind) return undefined + const spanned = star.qualifier ? sel.own.filter((src) => naming(src).includes(star.qualifier!)) : sel.own + const source = spanned.length === 1 && sel.own.length === (star.qualifier ? sel.own.length : 1) ? spanned[0] : undefined + const first = source && source.name !== sel.scope ? selectsOfScope.get(source.name)?.[0] : undefined + const columns = first && layoutOf(first)?.names + if (!columns) return undefined + out.spans.set(item, columns) + out.names.push(...columns) + } + layouts.set(sel, out) + return out + } + // Set-operation branches pair their columns by position. A scope's branches + // line up when every branch's columns are known and as many. A union of bare + // `select *` over tables only is followed by name: nothing this file names + // enters it. Otherwise the name a column leaves the scope under is unknown. const misaligned = new Map() const branchesMisaligned = (scope: string) => { let out = misaligned.get(scope) if (out === undefined) { - const shapes = (selectsOfScope.get(scope) ?? []).map((sel) => - (byKey.get(sel.key) ?? []).map((i) => (starOf(i) || jinjaItems.has(i) ? "*" : "c")).join(""), - ) - out = shapes.some((shape) => shape !== shapes[0]) + const branches = selectsOfScope.get(scope) ?? [] + const tableStar = (sel: Select) => + sel.items.length === 1 && + STAR.test(sel.items[0].text) && + !sel.blind && + sel.own.length > 0 && + sel.own.every((src) => !scopes.has(src.name)) + const widths = branches.map((sel) => layoutOf(sel)?.names.length) + out = branches.length > 1 && !branches.every(tableStar) && widths.some((w) => w === undefined || w !== widths[0]) misaligned.set(scope, out) } return out } + // The name the column at `position` of a select leaves its scope under: a + // later set-operation branch outputs under the first branch's names. + const nameAt = (sel: Select | undefined, position: number | undefined, own: string | undefined) => { + const first = sel && selectsOfScope.get(sel.scope)?.[0] + if (!sel || !first || first === sel) return own + const names = layoutOf(first)?.names + return names && position !== undefined ? names[position] : own + } + const outName = (item: SelectItem) => { + if (item.branch === 0) return item.name + const sel = selectByKey.get(`${item.scope}#${item.branch}`) + const layout = sel && layoutOf(sel) + if (!layout) return firstNames.get(`${item.scope}\u0000${item.position}`) ?? item.name + return nameAt(sel, layout.offsets.get(item), item.name) + } + // The name a `*` item passes `carried` on under (`column` being its name in + // the scope the `*` spans). + const starName = (sel: Select, item: SelectItem, column: string, carried: string) => { + const layout = layoutOf(sel) + const at = layout?.spans.get(item)?.indexOf(column) + return layout && at !== undefined && at >= 0 ? nameAt(sel, layout.offsets.get(item)! + at, carried) : carried + } // The selects that can read a scope: those naming it in FROM/JOIN, those // nested in one that does (a correlated read), those whose source list names // it without parsing it as a source, and those whose sources did not parse. @@ -1480,14 +1614,15 @@ export function rawReach(sql: string): RawReach { return out } - const reach = (scope: string, name: string | undefined, seen: Set): boolean => { + const reach = (scope: string, given: string | undefined, seen: Set): boolean => { if (scope === ROOT_SCOPE) return true if (scope.includes(">")) { if (inPredicate(scope)) return false // Not a FROM source: a scalar subquery, a lateral or a set-operation branch. if (!fromSubqueries.has(scope)) return true } - if (unknownName(name) || branchesMisaligned(scope)) return true + if (unknownName(given) || branchesMisaligned(scope)) return true + const name = given! const visit = `${scope}\u0000${name}` if (seen.has(visit)) return false seen.add(visit) @@ -1497,7 +1632,8 @@ export function rawReach(sql: string): RawReach { const blind = sel.blind || (!own.length && !outer.length) // A table function, `unpivot` or array join over the column moves its // values under another name. - if (sel.words.has(name!)) return true + if (sel.words.has(name) || (!/^[A-Za-z_][\w$]*$/.test(name) && wordIn(sourceText.get(sel.key), name))) return true + if (sel.jinja.length) return true const scopeNames = new Set([...own, ...outer].flatMap(naming)) let others: Set | undefined const otherNames = () => @@ -1506,33 +1642,29 @@ export function rawReach(sql: string): RawReach { // did not read (`src pivot (…) p`) may still be the scope, so that counts. const fromScope = (qualifier?: string) => !qualifier || blind || scopeNames.has(qualifier) || !otherNames().has(qualifier) - if (sel.jinja.length) return true - // A macro call naming the column may emit it raw (`dbt.safe_cast("ssn", …)`). const carriedOn = (item: SelectItem) => leavesAs(item).some((as) => reach(sel.scope, as, seen)) - for (const item of sel.calls) if (wordIn(jinjaCalls.get(item), name!) && carriedOn(item)) return true + // A macro call naming the column may emit it raw (`dbt.safe_cast("ssn", …)`). + for (const item of sel.calls) if (wordIn(jinjaCalls.get(item), name) && carriedOn(item)) return true for (const item of sel.stars) { const star = starOf(item)! // An unqualified `*` spans the select's own sources only. if (star.qualifier ? !fromScope(star.qualifier) : !own.length && !blind) continue // `x.*` over a struct column named like the output expands its fields. - if (star.qualifier === name && !scopeNames.has(name!)) return true + if (star.qualifier === name && !scopeNames.has(name)) return true if (star.opaque) return true - if (star.carries(name!).some((carried) => reach(sel.scope, carried, seen))) return true - } - // The name selected raw, or read by an expression that keeps its value. - for (const item of sel.byColumn.get(name!) ?? []) { - const keeps = item.rawColumn - ? fromScope(item.rawQualifier) - : readsOf(item).some((r) => r.column === name && fromScope(r.qualifier)) - if (keeps && carriedOn(item)) return true + if (star.carries(name).some((carried) => reach(sel.scope, starName(sel, item, name, carried), seen))) return true } - // A field of the column (`tax.v`, `tax.a.b`), when `tax` names no source. - if (!scopeNames.has(name!) && !otherNames().has(name!)) - for (const item of sel.byPathHead.get(name!) ?? []) if (carriedOn(item)) return true + // The name read where its value is kept: raw, in an expression outside + // masking calls, or as the head of a field or method (`tax.v`, + // `tax.lower()`) when it is not itself a source's name. + const isSource = scopeNames.has(name) || otherNames().has(name) + for (const item of itemsNaming(sel, name)) + if (columnUses(exprOf(item), name).some((use) => (use.path ? !isSource : fromScope(use.qualifier))) && carriedOn(item)) + return true // The scope as a whole row: `select s from src s`, `to_json(s)`. for (const alias of scopeNames) - for (const item of sel.byColumn.get(alias) ?? []) - if (item.rawColumn ? !item.rawQualifier : readsOf(item).some((r) => r.column === alias && !r.qualifier)) return true + for (const item of itemsNaming(sel, alias)) + if (columnUses(exprOf(item), alias).some((use) => !use.qualifier && !use.path)) return true } return false } @@ -1543,13 +1675,21 @@ export function rawReach(sql: string): RawReach { if (out === undefined) memo.set(key, (out = reach(scope, name, new Set()))) return out } - // An output under a PII name counts for that name whatever unmasked value it - // holds (`tax_id_number as ssn`). + // The item's output keeps `column`'s value: its unmasked expression still + // names the column, or it outputs some unmasked value under that name + // (`tax_id_number as ssn`), or Jinja in it may stand for it. const carries = (item: SelectItem, column: string) => { if (jinjaItems.has(item) || wordIn(jinjaCalls.get(item), column)) return true - if (item.rawColumn) return item.rawColumn === column || item.name === column - const reads = readsOf(item) - return reads.some((r) => r.column === column) || (item.name === column && reads.length > 0) + const expr = exprOf(item) + if (columnUses(expr, column).length > 0) return true + // Some other column, unmasked, under the PII name: an identifier that is + // neither a call nor a keyword is left in the expression. + return ( + item.name === column && + [...expr.matchAll(/(? !m[2] && !EXPR_KEYWORDS.has(m[1].toLowerCase()), + ) + ) } const reaches = (item: SelectItem) => opaque || leavesAs(item).some((as) => reachMemo(item.scope, as)) const passes = (item: SelectItem, column: string) => { @@ -1558,7 +1698,8 @@ export function rawReach(sql: string): RawReach { const star = starOf(item) if (!star) return carries(item, column) && reaches(item) if (star.opaque) return opaque || reachMemo(item.scope, undefined) - return star.carries(column).some((name) => opaque || reachMemo(item.scope, name)) + const sel = selectByKey.get(`${item.scope}#${item.branch}`) + return star.carries(column).some((name) => opaque || reachMemo(item.scope, sel ? starName(sel, item, column, name) : name)) } const exposeMemo = new Map() const mayExpose = (column: string) => { @@ -1576,16 +1717,20 @@ export function rawReach(sql: string): RawReach { const tableNames = new Set(tables.flatMap(naming)) const derivedNames = new Set(sel.own.filter((src) => !isTable(src)).flatMap(naming)) if (sel.jinja.length) return reachMemo(sel.scope, column) - if (sel.stars.some((item) => { - const star = starOf(item)! - // A `*` qualified by a CTE or subquery passes that scope's columns only. - if (star.qualifier && derivedNames.has(star.qualifier) && !tableNames.has(star.qualifier)) return false - return star.opaque ? reachMemo(sel.scope, column) : star.carries(column).some((c) => reachMemo(sel.scope, c)) - })) + if ( + sel.stars.some((item) => { + const star = starOf(item)! + // A `*` qualified by a CTE or subquery passes that scope's columns only. + if (star.qualifier && derivedNames.has(star.qualifier) && !tableNames.has(star.qualifier)) return false + return star.opaque ? reachMemo(sel.scope, column) : star.carries(column).some((c) => reachMemo(sel.scope, c)) + }) + ) return true // A table as a whole row. return [...tableNames].some((t) => - (sel.byColumn.get(t) ?? []).some((item) => !!item.rawColumn && !item.rawQualifier && reachMemo(sel.scope, column)), + itemsNaming(sel, t).some( + (item) => columnUses(exprOf(item), t).some((use) => !use.qualifier && !use.path) && reachMemo(sel.scope, column), + ), ) }) exposeMemo.set(column, out) @@ -1594,6 +1739,7 @@ export function rawReach(sql: string): RawReach { let masked: string | undefined let lineStarts: number[] | undefined const inClause = (line: number) => { + if (opaque) return false masked ??= maskSql(sql) if (!lineStarts) { lineStarts = [0] @@ -1605,6 +1751,9 @@ export function rawReach(sql: string): RawReach { // can put the column in the output under another name. const stop = lineStarts[line] ?? masked.length if (sourceRanges.some(([from, to]) => from < stop && start < to)) return false + // The line may open with the clause word itself (`on a.ssn = b.ssn`). + const opens = CLAUSE_WORD.exec(masked.slice(start, stop).trimStart().slice(0, 24)) + if (opens) return SELECTS_NOTHING.test(opens[1].replace(/\s+/g, " ")) // Backwards from the line, skipping parentheses that closed before it. let depth = 0 for (let i = start - 1; i >= 0; i--) { diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index a153e2d053..017a9936c7 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -530,7 +530,8 @@ describe("rawReach", () => { const lineReaches = (sql: string) => { const r = rawReach(sql) return sql.split("\n").flatMap((text, at) => { - if (!/\bssn\b/i.test(text)) return [] + // Lines the regex twin fires on: the column opens the line. + if (!/^\s*[\w.]*\bssn\b/i.test(text)) return [] const items = r.items.filter((i) => i.startLine <= at + 1 && at + 1 <= i.endLine) return [items.length ? items.some((i) => r.passes(i, "ssn")) : !r.inClause(at + 1) || r.mayExpose("ssn")] }) @@ -547,8 +548,6 @@ describe("rawReach", () => { ["`pivot` in FROM over the column", "select id, a, b\nfrom customers pivot (max(\n ssn\n) for k in ('a', 'b'))"], ["`lateral flatten` in FROM over the column", "select c.id, f.value as v\nfrom customers c,\nlateral flatten(input => array_construct(\n c.ssn\n)) f"], ["a DDL wrapper is not one query", "create table out as (\n select\n ssn\n from customers\n)"], - ["a macro call that emits the column, on its own line", "select\n {{ dbt.safe_cast(\"ssn\", api.Column.translate_type(\"string\")) }} as tax_id\nfrom customers"], - ["`adapter.quote` of the column, on its own line", "select\n {{ adapter.quote(\"ssn\") }} as tax_id\nfrom customers"], ["a reader's macro call that names the column", "with c as (\n select\n ssn\n from customers\n)\nselect {{ dbt.safe_cast(\"ssn\", \"varchar\") }} as tax_id from c"], ["a `columns('\u2026')` pattern in the reader", "with c as (\n select\n id,\n ssn\n from customers\n)\nselect columns('id|ss.') from c"], ["a backslash-escaped quote before the line", "select\n replace(name, '\\'', '') as n,\n ssn\nfrom customers"], @@ -560,13 +559,61 @@ describe("rawReach", () => { ["`select top n distinct`", "select top 10 distinct\n ssn\nfrom customers"], ["an alias that is a Jinja call", "with c as (\n select\n ssn as {{ var('tax_col') }}\n from customers\n)\nselect id, tax_ref from c"], ["an alias that is a Jinja variable", "with c as (\n select\n ssn as {{ tax_col }}\n from customers\n)\nselect id, tax_ref from c"], - ["a struct field of the CTE's column", "with c as (\n select struct_pack(\n v := ssn\n ) as tax from customers\n)\nselect tax.v from c"], ["a struct field of the CTE's column (BigQuery)", "with c as (\n select struct(\n ssn as v\n ) as tax from customers\n)\nselect tax.v from c"], ["an array join in a CTE's FROM, then `select *`", "with x as (\n select c.id, v\n from customers c, unnest([\n c.ssn\n ]) as v\n)\nselect * from x"], - ["another column output under the PII name", "select\n id,\n tax_id_number as ssn\nfrom customers"], ["a backslash-escaped quote that swallows the line", "select\n replace(name, '\\'', '') as n,\n ssn\nfrom customers\nwhere status = 'active'"], ["a positional column in the reader", "with c as (\n select\n id,\n ssn\n from customers\n)\nselect $2 as tax_ref from c"], ["a later item of the same select reading the alias", "with c as (\n select\n id,\n ssn as raw_ssn,\n raw_ssn as tax_ref\n from customers\n)\nselect id, tax_ref from c"], + ["`percentile_disc \u2026 within group (order by \u2026)` returns the ordered value", "with c as (\n select id, ssn from customers\n)\nselect\n percentile_disc(0.5) within group (\n order by\n ssn\n ) as tax_ref\nfrom c"], + ["`mode() within group (order by \u2026)` returns the ordered value", "select\n mode() within group (order by\n ssn\n ) as tax_ref\nfrom customers"], + ["a FROM-first final query", "with c as (\n select\n ssn as tax_ref\n from customers\n)\nfrom c"], + ["`from c select x`", "with c as (\n from customers\n select\n ssn as tax_ref\n)\nfrom c select tax_ref"], + ["`table c` as the final query", "with c as (\n select\n ssn as tax_ref\n from customers\n)\ntable c"], + ["`table c` as a CTE body", "with c as (\n select\n ssn as tax_ref\n from customers\n),\nd as (table c)\nselect tax_ref from d"], + ["a `pivot` statement", "pivot customers\non status\nusing count(*)\ngroup by\n ssn"], + ["a union of `select *` branches whose columns come in another order", "with a as (\n select id, md5(name) as h from customers\n),\nb as (\n select\n ssn,\n id\n from customers\n),\nu as (\n select * from a\n union all\n select * from b\n)\nselect id from u"], + ["a field of a struct column named like the PII column", "select\n ssn.number as tax_ref\nfrom customers"], + ["a Jinja call glued to the column name", "select\n ssn{{ var(\"ssn_suffix\", \"\") }} as tax_ref\nfrom customers"], + ["a dynamic `pivot \u2026 in (select \u2026)`", "with c as (select id, ssn, v from customers)\nselect * from c\npivot (max(v) for id in (select\n ssn\nfrom c))"], + ["a `values` query", "with c as (\n select\n ssn as tax_ref\n from customers\n)\nvalues ((select tax_ref from c limit 1))"], + ["`union all table c`", "with c as (\n select\n ssn as tax_ref\n from customers\n)\nselect 'x' as tax_ref from customers\nunion all\ntable c"], + ["a quoted alias with a space", "with c as (\n select\n ssn as \"Tax Ref\"\n from customers\n)\nselect \"Tax Ref\" from c"], + ["a quoted alias with a dot", "with c as (\n select\n ssn as \"a.b\"\n from customers\n)\nselect \"a.b\" from c"], + ["two Jinja alternatives of one CTE", "with\n{% if target.name == 'prod' %}\nc as (select md5(ssn) as h, id from customers),\nf as (select id as out from c)\n{% else %}\nc as (\n select\n ssn as tax_ref,\n id\n from customers\n),\nf as (select tax_ref as out from c)\n{% endif %}\nselect out from f"], + ["two Jinja alternatives of one CTE body", "with c as (\n {% if target.name == 'prod' %}\n select md5(ssn) as h, id from customers\n {% else %}\n select\n ssn as tax_ref,\n id\n from customers\n {% endif %}\n)\nselect {% if target.name == 'prod' %}id{% else %}tax_ref{% endif %} as out from c"], + ["`union all corresponding`", "with u as (\n select id, md5(ssn) as h from customers\n union all corresponding\n select\n ssn as h,\n id\n from customers\n)\nselect h from u"], + ["`collate` after the column", "with src as (\n select\n ssn collate nocase\n from customers\n)\nselect ssn from src"], + ["`collate \"C\"` read as an alias", "with src as (\n select\n ssn collate \"C\"\n from customers\n)\nselect ssn from src"], + ["pipe syntax", "with c as (\n select\n ssn as tax_ref\n from customers\n)\nfrom c\n|> select tax_ref"], + ["a quoted identifier holding a parenthesis", "select\n md5(\"a(\") || \n ssn as tax_ref\nfrom customers"], + ["a CTE named through Jinja", "with\n{% for src in ['a', 'b'] %}\n{{ src }}_c as (\n select\n ssn as tax_ref\n from {{ ref(src) }}\n),\n{% endfor %}\nf as (select tax_ref from a_c)\nselect tax_ref from f"], + ["a CTE named with a Jinja prefix", "with\n{% for src in ['a'] %}\nstg_{{ src }} as (\n select\n ssn as tax_ref\n from {{ ref(src) }}\n),\n{% endfor %}\nf as (select tax_ref from stg_a)\nselect tax_ref from f"], + ["a quoted CTE name holding `>`", "with c as (select id from customers where id in (select id from customers)),\n\"c>sub1\" as (\n select\n ssn as tax_ref\n from customers\n)\nselect tax_ref from \"c>sub1\""], + ["a list literal split at its commas", "with c as (\n select\n id,\n [\n md5(name),\n ssn,\n 'x'\n ] as arr\n from customers\n)\nselect arr from c"], + ["an array constructor split at its commas", "with c as (\n select\n id,\n array[\n md5(name),\n ssn\n ] as arr\n from customers\n)\nselect arr from c"], + ["a struct literal split at its commas", "with c as (\n select\n id,\n {\n 'h': md5(name),\n ssn: ssn\n } as s\n from customers\n)\nselect s from c"], + ["an alias chosen by a Jinja `if`", "with c as (\n select\n ssn as {% if target.name == 'dev' %}tax_ref{% else %}h{% endif %}\n from customers\n)\nselect {% if target.name == 'dev' %}tax_ref{% else %}md5(h){% endif %} as out from c"], + ["a mask applied only under a Jinja `if`", "select\n {% if target.name == 'prod' %}md5({% endif %}\n ssn\n {% if target.name == 'prod' %}){% endif %} as tax_ref\nfrom customers"], + ["a mask applied only under a Jinja `if`, in a CTE", "with c as (\n select\n {% if not var('expose_pii', false) %}sha2({% endif %}\n ssn\n {% if not var('expose_pii', false) %}, 256){% endif %} as tax_ref\n from customers\n)\nselect tax_ref from c"], + ["a CTE column named `filter`", "with c as (\n select\n ssn as filter\n from customers\n)\nselect coalesce(filter, '') as p from c"], + ["a CTE column named `partition`", "with c as (\n select\n ssn as partition\n from customers\n)\nselect coalesce(partition, '') as p from c"], + ["a CTE column named `separator`", "with c as (\n select\n ssn as separator\n from customers\n)\nselect coalesce(separator, '') as p from c"], + ["a CTE column named `escape`", "with c as (\n select\n ssn as escape\n from customers\n)\nselect coalesce(escape, '') as p from c"], + ["a CTE column named `within`", "with c as (\n select\n ssn as within\n from customers\n)\nselect coalesce(within, '') as p from c"], + ["a CTE column named `interval`", "with c as (\n select\n ssn as interval\n from customers\n)\nselect coalesce(interval, '') as p from c"], + ["a CTE column named `nulls`", "with c as (\n select\n ssn as nulls\n from customers\n)\nselect coalesce(nulls, '') as p from c"], + ["a CTE column named `over`", "with c as (\n select\n ssn as over\n from customers\n)\nselect coalesce(over, '') as p from c"], + ["a CTE column named `exists`", "with c as (\n select\n ssn as exists\n from customers\n)\nselect coalesce(exists, '') as p from c"], + ["a CTE column named `rlike`", "with c as (\n select\n ssn as rlike\n from customers\n)\nselect coalesce(rlike, '') as p from c"], + ["a CTE column named `regexp`", "with c as (\n select\n ssn as regexp\n from customers\n)\nselect coalesce(regexp, '') as p from c"], + ["a CTE column named `try_cast`", "with c as (\n select\n ssn as try_cast\n from customers\n)\nselect coalesce(try_cast, '') as p from c"], + ["a CTE column named `partition_raw`", "with c as (\n select\n ssn as partition\n from customers\n)\nselect partition as p from c"], + ["a method call on the column", "select\n ssn.lower() as tax_ref\nfrom customers"], + ["chained method calls on the column", "with c as (\n select\n ssn.trim().upper() as tax_ref\n from customers\n)\nselect tax_ref from c"], + ["a reader's method call on the column", "with c as (\n select\n ssn as tax_ref\n from customers\n)\nselect tax_ref.lower() as out from c"], + ["an `unpivot` statement", "unpivot customers\non\n ssn\ninto name k value v"], + ["a FROM-first CTE body", "with a as (\n select\n ssn as x\n from customers\n),\nb as (from a select x as tax_ref)\nselect tax_ref from b"], + ["a union whose first branch is a table's `select *`", "with b as (\n select\n ssn,\n id\n from customers\n),\nu as (\n select * from {{ ref('stg_other') }}\n union all\n select * from b\n)\nselect id from u"], ] for (const [name, sql] of cases) { const lines = lineReaches(sql) From 5533949879e19594ca8dac474f537900d1cad8af Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 23:19:11 +0530 Subject: [PATCH 77/81] fix(review): treat SQL that Jinja or the warehouse may lex differently as unread in the PII reach analysis A third adversarial pass found the remaining lost blocks in rare shapes: - the masker and Jinja or the warehouse can disagree on what is code: Jinja comment or statement delimiters inside a SQL comment or a literal (Jinja renders first), a backslash before a quote, `//` comments, `$$` strings, a block comment inside a block comment. Any of these marks the SQL misread, so nothing shows a column masked. Jinja left in a quoted identifier (`ssn as "{{ col }}"`) makes the item's name unknown; - a nested query's ancestry is tracked by scope, not by key prefix, so a FROM subquery whose alias collides with a condition's key is not taken for one; - the `replace` and `rename` lists of a `*` each apply to the star's own columns (`* rename (a as x, x as y)` leaves `a` under `x`; `* exclude (ssn) replace (ssn as name)` still carries it under `name`); - `ssn.*` on the changed line expands a struct column, and `ssn$raw` carries the column as the PII rule reads it. Nesting deeper than 64 levels is not followed, and the head is parsed once for the reindent check and the reach analysis. Co-Authored-By: Claude --- .../src/altimate/review/orchestrate.ts | 3 +- .../src/altimate/review/rule-catalog.ts | 94 +++++++++++++------ .../test/altimate/review-rule-catalog.test.ts | 35 +++++++ 3 files changed, 100 insertions(+), 32 deletions(-) diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 64ff9ac1ad..195a9b88a0 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1573,7 +1573,8 @@ export async function runReview(input: OrchestrateInput): Promise /** Per nested query, the offset of the `(` that opens it. */ scopeOpen: Map + /** Per nested query, the scope it is nested in. */ + scopeParent: Map } /** Offset of the `)` closing the `(` at `open` in masked SQL, or the end. */ @@ -497,10 +501,20 @@ function parseSelects(sql: string): ParsedSelects { const jinjaCalls = new Map() const sourceRanges: Array<[number, number]> = [] const cteNames = new Set() + const lexedApart = (m: string) => { + // A literal spanning lines, or holding Jinja comment or statement delimiters. + if (m.startsWith("'")) return m.includes("\n") || /\{[#%]|[#%]\}/.test(m) + // A SQL comment holding Jinja (rendered first), or another block comment (nested in some engines). + if (m.startsWith("--") || m.startsWith("/*")) return /\{[#%{]|[#%}]\}/.test(m) || m.indexOf("/*", 2) >= 0 + return false + } let misread = - (sql.match(MASKED_TOKEN) ?? []).some((m) => m.startsWith("'") && m.includes("\n")) || + (sql.match(MASKED_TOKEN) ?? []).some(lexedApart) || (s.match(/'/g)?.length ?? 0) % 2 === 1 || s.includes("#") || + s.includes("//") || + sql.includes("$$") || + sql.includes("\\'") || (s.match(/"(?:[^"]|"")*"|\x60[^\x60]*\x60/g) ?? []).some((quoted) => /[()]/.test(quoted)) // One query only: a DDL/DML wrapper or a second statement is not a model. // A set operator is followed by its next select (not `by name`, `table c`). @@ -510,6 +524,7 @@ function parseSelects(sql: string): ParsedSelects { s.includes("|>") || /(?() + const scopeParent = new Map() const selectScopes = new Set() // The scope each nested query's `(` opens, so a FROM subquery is a named source. const parenScope = new Map() @@ -578,12 +593,13 @@ function parseSelects(sql: string): ParsedSelects { scopes.push(name) // A column list, a second definition (Jinja alternatives), or a name // that came out of Jinja or collides with a nested query's key. - if (cte[2] || cteNames.has(name) || name.includes(">") || /_{4,}/.test(name)) unmodelled = true + if (cte[2] || cteNames.has(name) || name.includes(">") || /_{4,}|\{/.test(name)) unmodelled = true cteNames.add(name) } else if (/^[\s(]*select\b/i.test(s.slice(i + 1, i + 200))) { scopes.push(nestedKey(parent, i)) parenScope.set(i, scopes[scopes.length - 1]) scopeOpen.set(scopes[scopes.length - 1], i) + scopeParent.set(scopes[scopes.length - 1], parent) const before = s.slice(Math.max(0, i - 40), i) const setOperand = /\b(?:union|intersect|except|minus)(?:\s+all|\s+distinct)?\s*$/i.test(before) if ( @@ -658,7 +674,9 @@ function parseSelects(sql: string): ParsedSelects { // A statement tag in the item (a conditional wrapper or alias, a loop), // or an expression glued to a name (`ssn{{ suffix }}`): its text is not its SQL. source.includes("{%") || - /[\w$]\{\{|\}\}[\w$]/.test(source) + /[\w$]\{\{|\}\}[\w$]/.test(source) || + // Jinja left unmasked: it sits in a quoted identifier (`ssn as "{{ col }}"`). + raw.includes("{{") ) jinjaItems.add(item) const calls = jinja.filter((m) => { @@ -755,7 +773,7 @@ function parseSelects(sql: string): ParsedSelects { // A Jinja `{{ ref('x') }}` is masked to underscores: name it by its source text. short = /^_+$/.test(last) ? sql.slice(at, at + last.length).replace(/\s+/g, "").toLowerCase() : unquote(last) // A name partly out of Jinja (`stg_{{ src }}`) could be anything, a CTE included. - if (!/^_+$/.test(last) && /_{4,}/.test(last)) unknownSources.add(key) + if (!/^_+$/.test(last) && /_{4,}|\{/.test(last)) unknownSources.add(key) // Database and schema stay part of the identity: `restricted.customers` // and `public.customers` are different tables. name = [...segments.slice(0, -1).map(unquote), short].join(".") @@ -801,7 +819,7 @@ function parseSelects(sql: string): ParsedSelects { } // Every CTE and the final query hold a select (not `table c`, `values`, a macro). if (!selectScopes.has(ROOT_SCOPE) || [...cteNames].some((name) => !selectScopes.has(name))) unmodelled = true - return { items, sources, sourceText, unknownSources, predicates, unmodelled, misread, jinjaItems, jinjaCalls, sourceRanges, scopeOpen } + return { items, sources, sourceText, unknownSources, predicates, unmodelled, misread, jinjaItems, jinjaCalls, sourceRanges, scopeOpen, scopeParent } } /** @@ -1279,21 +1297,19 @@ function starItem(text: string): StarItem | undefined { steps.push({ kind: kind as "replace" | "rename", from: item.rawColumn, expr: unmaskedExpr(item.text), to: unquote(alias) }) } } + // Each list applies to the star's own columns, not to the list before it: + // the column keeps its slot unless it is excluded or replaced by an + // expression that does not name it; every `replace` entry naming it holds + // its value too; a `rename` then renames whatever name comes out. const carries = (column: string) => { - if (dropped.has(column)) return [] - let names = new Set([column]) - for (const step of steps) { - if (step.kind === "rename") { - if (step.from && names.delete(step.from)) names.add(step.to) - continue - } - // `replace (expr as to)`: `to` now holds `expr`. It still holds the column - // only when `expr` names it unmasked. - const kept = [...names].some((n) => columnUses(step.expr, n).length > 0) - names.delete(step.to) - if (kept) names.add(step.to) - } - return [...names] + const names = new Set() + const replaced = steps.filter((step) => step.kind === "replace" && step.to === column) + if (!dropped.has(column) && (!replaced.length || replaced.some((step) => columnUses(step.expr, column).length > 0))) + names.add(column) + for (const step of steps) + if (step.kind === "replace" && step.to !== column && columnUses(step.expr, column).length > 0) names.add(step.to) + const renamed = (name: string) => steps.find((step) => step.kind === "rename" && step.from === name)?.to ?? name + return [...new Set([...names].map(renamed))] } return { qualifier, carries } } @@ -1375,8 +1391,18 @@ const SELECTS_NOTHING = /^(?:where|group by|order by|partition by|having|qualify */ export function rawReach(sql: string): RawReach { const parsed = parseSelects(sql) - const { items, sources, sourceText, unknownSources, predicates, jinjaItems, jinjaCalls, sourceRanges, scopeOpen } = parsed + const { items, sources, sourceText, unknownSources, predicates, jinjaItems, jinjaCalls, sourceRanges, scopeOpen, scopeParent } = parsed + // The scopes a nested query sits in, nearest first. Nesting past any real + // model's depth is not followed. + const MAX_DEPTH = 64 + const ancestors = (scope: string) => { + const out: string[] = [] + for (let up = scopeParent.get(scope); up !== undefined && out.length <= MAX_DEPTH; up = scopeParent.get(up)) out.push(up) + return out + } + const tooDeep = [...scopeParent.keys()].some((scope) => ancestors(scope).length > MAX_DEPTH) const opaque = + tooDeep || parsed.unmodelled || parsed.misread || JINJA_GLUED_KEYWORD.test(sql) || @@ -1403,10 +1429,7 @@ export function rawReach(sql: string): RawReach { return at === undefined || !sourceRanges.some(([from, to]) => from <= at && at < to) }), ) - const inPredicate = (scope: string) => { - for (let at = scope.length; at > 0; at = scope.lastIndexOf(">", at - 1)) if (conditions.has(scope.slice(0, at))) return true - return false - } + const inPredicate = (scope: string) => conditions.has(scope) || ancestors(scope).some((up) => conditions.has(up)) const naming = (src: Source) => [src.alias, src.name, src.short].filter((x): x is string => !!x) const stars = new Map() const starOf = (item: SelectItem) => { @@ -1447,11 +1470,17 @@ export function rawReach(sql: string): RawReach { } const WORD = /["\x60]?([A-Za-z_][\w$]*)["\x60]?/g const BARE = /(? ({ key, scope: key.slice(0, key.lastIndexOf("#")) })) + const keyed = tooDeep ? [] : [...sources.keys()].map((key) => ({ key, scope: key.slice(0, key.lastIndexOf("#")) })) + const keysOfScope = new Map>() + for (const sel of keyed) { + const list = keysOfScope.get(sel.scope) + if (list) list.push(sel) + else keysOfScope.set(sel.scope, [sel]) + } const selects: Select[] = keyed .filter((sel) => !inPredicate(sel.scope)) .map((sel) => { - const enclosing = keyed.filter((o) => sel.scope.startsWith(`${o.scope}>`)) + const enclosing = ancestors(sel.scope).flatMap((up) => keysOfScope.get(up) ?? []) const text = sourceText.get(sel.key) ?? "" const out: Select = { ...sel, @@ -1681,7 +1710,8 @@ export function rawReach(sql: string): RawReach { const carries = (item: SelectItem, column: string) => { if (jinjaItems.has(item) || wordIn(jinjaCalls.get(item), column)) return true const expr = exprOf(item) - if (columnUses(expr, column).length > 0) return true + // As the PII rule reads a word: `$` ends one there (`ssn$raw`). + if (columnUses(expr, column).length > 0 || new RegExp(`\\b${column.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i").test(expr)) return true // Some other column, unmasked, under the PII name: an identifier that is // neither a call nor a keyword is left in the expression. return ( @@ -1697,8 +1727,10 @@ export function rawReach(sql: string): RawReach { if (parsed.misread) return true const star = starOf(item) if (!star) return carries(item, column) && reaches(item) - if (star.opaque) return opaque || reachMemo(item.scope, undefined) const sel = selectByKey.get(`${item.scope}#${item.branch}`) + // `ssn.*` expands a struct column's fields under names of their own. + if (star.opaque || (star.qualifier === column && !sel?.own.some((src) => naming(src).includes(column)))) + return opaque || reachMemo(item.scope, undefined) return star.carries(column).some((name) => opaque || reachMemo(item.scope, sel ? starName(sel, item, column, name) : name)) } const exposeMemo = new Map() diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 017a9936c7..88cd7d5173 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -488,6 +488,13 @@ describe("rawReach", () => { expect(star("sha2(\n ssn\n ) as h")).toBe(false) expect(star("coalesce(\n ssn,\n '') as tax_ref", "\nselect tax_ref from src")).toBe(true) expect(star("coalesce(\n ssn,\n '') as tax_ref", "\nselect customer_id from src")).toBe(false) + // Each modifier list applies to the star's own columns, not to the list before it. + const through = (modifiers: string, final: string) => reaches(src(`, mid as (\n select * ${modifiers} from src\n)\nselect ${final} from mid`)) + expect(through("rename (tax_ref as x, x as y)", "x")).toBe(true) + expect(through("rename (tax_ref as x, x as y)", "y")).toBe(false) + expect(through("replace (md5(tax_ref) as tax_ref, tax_ref as customer_id)", "customer_id")).toBe(true) + expect(through("replace (md5(tax_ref) as tax_ref, tax_ref as customer_id)", "tax_ref")).toBe(false) + expect(through("exclude (tax_ref) replace (tax_ref as customer_id)", "customer_id")).toBe(true) }) test("mayExpose: a column no select item names is exposed only through a table's `*`", () => { @@ -614,6 +621,34 @@ describe("rawReach", () => { ["an `unpivot` statement", "unpivot customers\non\n ssn\ninto name k value v"], ["a FROM-first CTE body", "with a as (\n select\n ssn as x\n from customers\n),\nb as (from a select x as tax_ref)\nselect tax_ref from b"], ["a union whose first branch is a table's `select *`", "with b as (\n select\n ssn,\n id\n from customers\n),\nu as (\n select * from {{ ref('stg_other') }}\n union all\n select * from b\n)\nselect id from u"], + ["jinja comment in sql comment", "select\n id,\n -- {#\n md5(\n -- #}\n ssn\n -- {#\n )\n -- #}\n as tax_ref\nfrom customers"], + ["backslash escape hides paren", "select\n id,\n md5(concat(trim(name, '\\''), '\\'')) as name_key,\n ssn,\n email\nfrom customers"], + ["snowflake slash comment", "select\n id, // TODO hash( later\n ssn,\n email\nfrom customers"], + ["nested block comment", "select\n id,\n /* note /* nested */ md5( -- */\n ssn,\n email\nfrom customers"], + ["predicate alias collision", "select\n id in (select customer_id from churned) as v,\n v.*\nfrom (\n select\n id,\n ssn\n from customers\n) v"], + ["rename swap", "with b as (\n select\n ssn as a,\n id as x\n from customers\n),\nc as (select * rename (a as x, x as y) from b)\nselect x from c"], + ["dollar string dashes", "select\n id,\n md5(name || $$--$$) as name_key,\n ssn,\n email\nfrom customers"], + ["multi item", "with h as (\n select\n id,\n email\n from customers\n)\nselect\n id,\n ssn,\n md5(email) as e\nfrom h"], + ["dollar in name", "select\n id,\n ssn$raw\nfrom customers"], + ["struct star cte", "with a as (\n select\n ssn.*\n from customers\n)\nselect number from a"], + ["nested comment balanced", "select\n id,\n /* a /* b */ md5( -- */\n ssn\n /* a /* b */ ) -- */\n as tax_ref\nfrom customers"], + ["backslash balanced", "select\n id,\n md5(name || '\\'') || '\\'' ||\n ssn\n || '\\'' || upper('\\'') as tax_ref\nfrom customers"], + ["jinja comment scalar subquery", "select\n -- {#\n id in\n -- #}\n (\n select\n ssn\n from customers\n limit 1\n ) as tax_ref\nfrom customers"], + ["jinja comment in literal", "select\n id,\n '{#' || md5('#}' ||\n ssn\n || '{#') || '#}' as tax_ref\nfrom customers"], + ["replace parallel", "with a as (\n select\n id,\n name,\n ssn\n from customers\n)\nselect * replace (md5(ssn) as ssn, ssn as name) from a"], + ["exclude then replace", "with a as (\n select\n id,\n name,\n ssn\n from customers\n)\nselect * exclude (ssn) replace (ssn as name) from a"], + ["quoted jinja alias", "{% set tax_col = 'tax_ref' %}\nwith a as (\n select\n ssn as \"{{ tax_col }}\"\n from customers\n)\nselect tax_ref from a"], + ["nested from", "with a as (\n select\n ssn as x\n from customers\n)\nselect x from (select x from (select x from a) s1) s2"], + ["correlated3", "with a as (\n select\n id,\n ssn as x\n from customers\n)\nselect (select (select max(a.x) from orders o2) from orders o1 limit 1) as y from a"], + ["if union", "with a as (\n select\n ssn as x\n from customers\n),\nu as (\n select md5(name) as x from customers\n {% if var('full', true) %}\n union all\n select x from a\n {% endif %}\n)\nselect x from u"], + ["union3", "with a as (\n select id, md5(name) as x from customers\n),\nb as (\n select\n id,\n ssn as x\n from customers\n),\nu as (\n select id, x from a\n union all\n select id, x from a\n union all\n select * from b\n)\nselect x from u"], + ["union in from", "with b as (\n select\n id,\n ssn as x\n from customers\n)\nselect t.x from (select id, md5(name) as x from customers union all select * from b) t"], + ["intersect mix", "with b as (\n select\n ssn as x\n from customers\n)\nselect x from b\nexcept\nselect md5(name) from customers"], + ["lateral alias eq src", "with a as (\n select\n ssn as tax,\n id\n from customers\n)\nselect md5(tax) as tax, tax as t2 from a"], + ["array agg order", "with a as (\n select\n id,\n ssn\n from customers\n)\nselect array_agg(id order by ssn) as f from a"], + ["named arg", "with a as (\n select\n ssn\n from customers\n)\nselect struct_pack(k := ssn) as rec from a"], + ["lambda", "with a as (\n select\n id,\n ssn\n from customers\n)\nselect list_transform([1], x -> ssn) as l from a"], + ["json path", "with a as (\n select\n ssn\n from customers\n)\nselect ssn['a'] as l, ssn->>'b' as m from a"], ] for (const [name, sql] of cases) { const lines = lineReaches(sql) From 7548ddf144d16329f12e07c3f7bf897d72d2537f Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Fri, 27 Nov 2026 23:20:10 +0530 Subject: [PATCH 78/81] docs(review): PII in SQL the review cannot follow blocks without a compiled base Co-Authored-By: Claude --- docs/docs/usage/dbt-pr-review.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 86e628b892..63567ba492 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -325,7 +325,9 @@ rubric: through CTEs and subqueries. A column that is hashed, masked or dropped on the way (`sha2(ssn)`, `right(ssn, 4)`, `* exclude (ssn)`) stays a warning; one that only passes through a value-preserving expression (`coalesce(ssn, '')`, - `max(ssn)`) still blocks. + `max(ssn)`) still blocks, and so does one in SQL the review cannot follow + (Jinja that builds the select list, lateral or scalar subqueries, unusual + syntax). ### Risk-tier path tokens From 72f9abcd30572f13604b66b2ff493de7da641d4b Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Sun, 29 Nov 2026 01:45:41 +0530 Subject: [PATCH 79/81] fix(review): block a proven-new PII column that reaches the output from anywhere in the model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The raw-base PII proof asked only about the twin's own line. A column dropped on that line and selected raw on a line the regex rules do not fire on (`select ssn from …` on one line, the table read again under a qualifier, a `*` over its table) lost its block. - `proveNewTwin` also asks `mayExpose(column)` for the whole head. - `mayExpose` follows a table's columns that leave a select unnamed under the item's own name (`to_json(c) as payload`, `object_construct(*)`, `$2`), reads the whole row of an outer table in a nested query and of a `ref` by its model name, and counts a table function or `unpivot` over the column. - `identifier(…)` in a select item names nothing, like `columns(…)` and `$n`. Such an item keeps the columns it does name and may read the selects around it. - `reach`: a reader naming the scope as a whole row reaches only when its own output does; a reader whose sources did not parse may name the scope itself. - Parser: `(select …)` before a set operator is a parenthesised branch only where a query can start, so a scalar, `where` or FROM subquery that ends a union branch no longer marks the file as unmodelled. White space of any length (a blanked comment) around a set operator is skipped. A source list cut at `with offset` counts as unread. - Fewer false blocks from the whole-model check: a count or a masking call over the row (`count(o.*)`, `hash(*)`), a test that answers true or false (`regexp_like`, `contains`, `startswith`), a cast's type under the column's name (`cast(null as varchar) as ssn`), and an alias spelled like a date part, a literal's prefix or a type are not read as the column or the row. - Tests: the parse-once test counts parser calls instead of timing them; the scaling tests assert results only. `reindentInfo` drops a fallback that could not run. - Docs: a model whose output also takes a `*` or a Jinja column list over a table blocks next to a proven-new column. Co-Authored-By: Claude --- docs/docs/usage/dbt-pr-review.md | 12 +- .../src/altimate/review/orchestrate.ts | 28 +-- .../src/altimate/review/rule-catalog.ts | 170 +++++++++++++----- .../test/altimate/review-rule-catalog.test.ts | 116 +++++++++++- .../opencode/test/altimate/review.test.ts | 91 +++++++--- 5 files changed, 322 insertions(+), 95 deletions(-) diff --git a/docs/docs/usage/dbt-pr-review.md b/docs/docs/usage/dbt-pr-review.md index 63567ba492..1c46f55762 100644 --- a/docs/docs/usage/dbt-pr-review.md +++ b/docs/docs/usage/dbt-pr-review.md @@ -322,12 +322,14 @@ rubric: 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 - through CTEs and subqueries. A column that is hashed, masked or dropped on the - way (`sha2(ssn)`, `right(ssn, 4)`, `* exclude (ssn)`) stays a warning; one that + 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 only passes through a value-preserving expression (`coalesce(ssn, '')`, - `max(ssn)`) still blocks, and so does one in SQL the review cannot follow - (Jinja that builds the select list, lateral or scalar subqueries, unusual - syntax). + `max(ssn)`) still blocks. So does one the review cannot rule out: in SQL it + cannot follow (Jinja that builds the select list, lateral or scalar + subqueries, unusual syntax), or in a model whose output also takes a `*` or a + Jinja column list over a table, whose columns the SQL does not show. ### Risk-tier path tokens diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 195a9b88a0..3cc493876d 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -1574,7 +1574,7 @@ export async function runReview(input: OrchestrateInput): Promise() const headReach = (file: string) => { @@ -1646,13 +1649,12 @@ export async function runReview(input: OrchestrateInput): Promise { const column = hit.column.toLowerCase() const lineNos = headLineNumbers(f.file, hit.line) - if (!reach || !lineNos.length) return true + if (!reach || !lineNos.length || reach.mayExpose(column)) return true // Any head line with this text counts: the diff does not say which one it is. return lineNos.some((n) => { // The analysis's own items: it knows them by identity. const items = reach.items.filter((i) => i.startLine <= n && n <= i.endLine) - if (items.length) return items.some((i) => reach.passes(i, column)) - return !reach.inClause(n) || reach.mayExpose(column) + return items.length ? items.some((i) => reach.passes(i, column)) : !reach.inClause(n) }) } return hits.every(mayReachOutput) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 7ec4b3c3db..d24b5545ab 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -580,6 +580,28 @@ function parseSelects(sql: string): ParsedSelects { } return false } + // The last 40 characters before `at`, each run of white space as one space. + const textBefore = (at: number) => { + let out = "" + for (let j = at - 1; j >= 0 && out.length < 40; j--) { + const blank = /\s/.test(s[j]) + if (!blank || !out.startsWith(" ")) out = (blank ? " " : s[j]) + out + } + return out + } + // A set operator is the next word at or after `at`. + const setOperatorAt = (at: number) => { + let j = at + while (j < s.length && /\s/.test(s[j])) j++ + return SET_OPERATOR.test(s.slice(j, j + 10)) + } + // The text before `at` ends where a query can start: nothing, only Jinja + // (masked to `_`), `(`, or the `)` that closes the CTE list. + const opensQuery = (at: number) => { + let j = at - 1 + while (j >= 0 && /\s/.test(s[j])) j-- + return j < 0 || s[j] === "(" || s[j] === ")" || (s[j] === "_" && /^[\s_]*$/.test(s.slice(0, j))) + } for (let i = 0; i < s.length; i++) { const c = s[i] if (c === "(") { @@ -600,7 +622,9 @@ function parseSelects(sql: string): ParsedSelects { parenScope.set(i, scopes[scopes.length - 1]) scopeOpen.set(scopes[scopes.length - 1], i) scopeParent.set(scopes[scopes.length - 1], parent) - const before = s.slice(Math.max(0, i - 40), i) + // The words before the parenthesis, with white space (a comment is + // blanked to spaces) collapsed, however long it runs. + const before = textBefore(i) const setOperand = /\b(?:union|intersect|except|minus)(?:\s+all|\s+distinct)?\s*$/i.test(before) if ( /(?:^|[^\w$."\x60])(?:in|exists|any|some)\s*$/i.test(before) || @@ -608,9 +632,13 @@ function parseSelects(sql: string): ParsedSelects { (/(?:^|[^\w$."\x60])all\s*$/i.test(before) && !setOperand && !/\bselect\s+all\s*$/i.test(before)) ) predicates.add(scopes[scopes.length - 1]) - // A parenthesised set-operation branch: its select is not a numbered branch. - else if (setOperand || /^\s*(?:union|intersect|except|minus)\b/i.test(s.slice(closingParen(s, i) + 1, closingParen(s, i) + 30))) - unmodelled = true + // A parenthesised set-operation branch: its select is not a numbered + // branch. One that opens the operation stands where a query starts: + // after `(`, the `)` of the CTE list, or nothing but Jinja. Anywhere + // else (`select (select …) union …`, `where x = (select …) union …`, + // `from (select …) union …`) the parenthesis ends a branch as a scalar + // or FROM subquery. + else if (setOperand || (opensQuery(i) && setOperatorAt(closingParen(s, i) + 1))) unmodelled = true } else scopes.push(parent) continue } @@ -806,6 +834,9 @@ function parseSelects(sql: string): ParsedSelects { segment = j + 1 unknownSources.add(key) } else if (boundary && FROM_LIST_END.test(s.slice(j, j + 10))) { + // `unnest(x) with offset` is part of a source, not the end of the + // list: what follows it is not read as a source. + if (inFrom && /^offset\b/i.test(s.slice(j, j + 7)) && /\bwith\s+$/i.test(s.slice(Math.max(0, j - 200), j))) unknownSources.add(key) closeSegment(j) inCondition = inFrom || inCondition ? /^(?:on|using)\b/i.test(s.slice(j, j + 6)) : false inFrom = false @@ -1171,12 +1202,13 @@ export const SILENT_JINJA_TAG = /^\{%[-+]?\s*(?:if|elif|else|endif|for|endfor|se // Calls whose result does not reveal their argument: hashes, encryption and // masking (by name, so a project's own `mask_ssn(…)` counts), a part of a -// string, a count or a length, and a date reduced to a part or a difference. +// string, a count or a length, a date reduced to a part or a difference, and a +// test that answers true or false (`regexp_like`, `contains`, `startswith`). // Any other call (`coalesce`, `trim`, `max`, `replace`, a cast) keeps the value. const MASKING_NAME = /hash|md5|hmac|fingerprint|surrogate_key|encrypt|cipher|mask|redact|anonymi[sz]e|pseudonymi[sz]e|tokeni[sz]e|obfuscate|scramble|(?:^|_)(?:sha|crc)(?:\d|_|$)/i const MASKING_EXACT = new Set( - "left right substr substring regexp_replace translate length len char_length character_length count count_if countif approx_count_distinct datediff date_diff timestampdiff timestamp_diff months_between age date_trunc datetrunc extract date_part datepart year".split( + "left right substr substring regexp_replace translate length len char_length character_length count count_if countif approx_count_distinct datediff date_diff timestampdiff timestamp_diff months_between age date_trunc datetrunc extract date_part datepart year regexp_like regexp_contains rlike contains startswith starts_with endswith ends_with".split( " ", ), ) @@ -1216,16 +1248,27 @@ function unmaskedExpr(text: string): string { /** Where `name` stands as a column in an unmasked expression: its qualifier * (`c` in `c.ssn`), and whether a field or method follows (`ssn.number`, * `ssn.lower()`). A call of that name (`ssn(…)`) is not the column. */ -function columnUses(expr: string, name: string): Array<{ qualifier?: string; path: boolean }> { +function columnUses(expr: string, name: string): Array<{ qualifier?: string; path: boolean; at: number }> { const re = new RegExp( String.raw`(? = [] - for (const m of expr.matchAll(re)) if (!m[3]) out.push({ qualifier: m[1] ? unquote(m[1]) : undefined, path: !!m[2] }) + const out: Array<{ qualifier?: string; path: boolean; at: number }> = [] + for (const m of expr.matchAll(re)) if (!m[3]) out.push({ qualifier: m[1] ? unquote(m[1]) : undefined, path: !!m[2], at: m.index! }) return out } +/** `name` (a source's alias) stands in the expression as a whole row (`select + * s`, `to_json(s)`): alone, and not as the date part of `dateadd(s, …)`, the + * prefix of a literal (`r'…'`, `e'…'`), or a type or field name after `as` + * (`cast(x as date)`, `struct(o.id as o)`). */ +const NOT_A_ROW_BEFORE = /(?:(? !use.qualifier && !use.path && !NOT_A_ROW_BEFORE.test(expr.slice(0, use.at)) && !/^["\x60]?[\w$]+["\x60]?'/.test(expr.slice(use.at)), + ) +} + /** 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 @@ -1239,18 +1282,23 @@ interface StarItem { carries: (column: string) => string[] } +const STAR_ONLY_CALL = new RegExp(String.raw`(? [c] } + // A positional column (`$2`), a column pattern (`columns('ss.')`) or a name + // resolved at run time (`identifier('ssn')`, `identifier($col)`) names nothing. + if (/(? [c] } // A `*` inside the item that is not a multiplication (an operand on both // sides): `object_construct(*)`, `struct(t.*)`, `as struct *`. `count(*)` - // reads no column. - const t = text.replace(/\bcount\s*\(\s*\*\s*\)/gi, " ") + // reads no column, and neither does a count or a masking call over the + // row (`count(o.*)`, `hash(*)`, `hash_agg(c.*)`): each stands as a plain + // operand. + const t = text.replace(STAR_ONLY_CALL, (call, name: string) => (isMaskingCall(name) ? " 0 " : call)) for (let i = t.indexOf("*"); i >= 0; i = t.indexOf("*", i + 1)) { const prev = /(\S)\s*$/.exec(t.slice(0, i))?.[1] const next = /^\s*(\S)/.exec(t.slice(i + 1))?.[1] @@ -1336,9 +1384,12 @@ export interface RawReach { * mask it and whose name for it reaches the output. Always, when the SQL's * quoting or select prefix may have been misread. */ passes: (item: SelectItem, column: string) => boolean - /** The final output may expose a column named `column` raw: through an item - * that carries it and reaches the output, or through a `*` (or a Jinja - * column list) over a table whose columns the SQL does not list. */ + /** The final output may expose a column named `column` raw, from anywhere in + * the SQL: some item carries it and reaches the output (as `passes` judges + * an item on a changed line), or a table's columns leave a select unnamed + * (a `*`, the table as a whole row, a table function or `unpivot` over the + * column) and that reaches the output. Always, for SQL the parser does not + * model. */ mayExpose: (column: string) => boolean /** The 1-based `line` sits in a clause that selects nothing: it is outside * every FROM/JOIN source, and the nearest clause word before it, outside @@ -1436,12 +1487,19 @@ export function rawReach(sql: string): RawReach { if (!stars.has(item)) stars.set(item, starItem(item.text)) return stars.get(item) } + // A `*` over the select's sources (`*`, `t.*`, with or without modifiers), + // as opposed to an item that reads columns it does not name + // (`object_construct(*)`, `coalesce(a.ssn, identifier($col))`). + const spanning = (item: SelectItem) => { + const star = starOf(item) + return !!star && STAR_HEAD.test(item.text) + } // An item's expression without its masked parts (`unmaskedExpr`): a column it - // still names keeps its value. A `*` item names no column it reads. + // still names keeps its value. A spanning `*` names no column it reads. const exprs = new Map() const exprOf = (item: SelectItem) => { let expr = exprs.get(item) - if (expr === undefined) exprs.set(item, (expr = starOf(item) ? "" : unmaskedExpr(item.text))) + if (expr === undefined) exprs.set(item, (expr = spanning(item) ? "" : unmaskedExpr(item.text))) return expr } // `ssn collate "C"` reads as an implicit alias: the output name is not known. @@ -1498,10 +1556,8 @@ export function rawReach(sql: string): RawReach { for (const item of out.items) { if (jinjaItems.has(item)) out.jinja.push(item) if (jinjaCalls.has(item)) out.calls.push(item) - if (starOf(item)) { - out.stars.push(item) - continue - } + if (starOf(item)) out.stars.push(item) + if (spanning(item)) continue for (const word of new Set([...exprOf(item).matchAll(WORD)].map((m) => m[1].toLowerCase()))) { const list = out.byWord.get(word) if (list) list.push(item) @@ -1513,7 +1569,7 @@ export function rawReach(sql: string): RawReach { // The items of a select that may name `name`. A quoted name that is not one // word (`"Tax Ref"`, `"a.b"`) is in no word index: every item is looked at. const itemsNaming = (sel: Select | undefined, name: string) => - !sel ? [] : /^[A-Za-z_][\w$]*$/.test(name) ? (sel.byWord.get(name) ?? []) : sel.items.filter((i) => !starOf(i)) + !sel ? [] : /^[A-Za-z_][\w$]*$/.test(name) ? (sel.byWord.get(name) ?? []) : sel.items.filter((i) => !spanning(i)) const selectsOfScope = new Map() const selectByKey = new Map() for (const sel of selects) { @@ -1676,8 +1732,9 @@ export function rawReach(sql: string): RawReach { for (const item of sel.calls) if (wordIn(jinjaCalls.get(item), name) && carriedOn(item)) return true for (const item of sel.stars) { const star = starOf(item)! - // An unqualified `*` spans the select's own sources only. - if (star.qualifier ? !fromScope(star.qualifier) : !own.length && !blind) continue + // An unqualified `*` spans the select's own sources only; an item that + // cannot be named (`identifier($col)`) may read the selects around it. + if (star.qualifier ? !fromScope(star.qualifier) : !own.length && !blind && (spanning(item) || !outer.length)) continue // `x.*` over a struct column named like the output expands its fields. if (star.qualifier === name && !scopeNames.has(name)) return true if (star.opaque) return true @@ -1690,10 +1747,11 @@ export function rawReach(sql: string): RawReach { for (const item of itemsNaming(sel, name)) if (columnUses(exprOf(item), name).some((use) => (use.path ? !isSource : fromScope(use.qualifier))) && carriedOn(item)) return true - // The scope as a whole row: `select s from src s`, `to_json(s)`. - for (const alias of scopeNames) + // The scope as a whole row: `select s from src s`, `to_json(s)`. A reader + // whose sources did not parse may read it under its own name. + for (const alias of blind ? new Set([...scopeNames, scope]) : scopeNames) for (const item of itemsNaming(sel, alias)) - if (columnUses(exprOf(item), alias).some((use) => !use.qualifier && !use.path)) return true + if (namesRow(exprOf(item), alias) && carriedOn(item)) return true } return false } @@ -1714,9 +1772,12 @@ export function rawReach(sql: string): RawReach { if (columnUses(expr, column).length > 0 || new RegExp(`\\b${column.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i").test(expr)) return true // Some other column, unmasked, under the PII name: an identifier that is // neither a call nor a keyword is left in the expression. + // The type of a cast is not one (`cast(null as varchar) as ssn`, + // `md5(x)::varchar as ssn`). + const values = expr.replace(/::\s*["\x60]?[\w$]+["\x60]?(?:\s*\([\d\s,]*\))?/g, " ").replace(/(? !m[2] && !EXPR_KEYWORDS.has(m[1].toLowerCase()), ) ) @@ -1739,31 +1800,44 @@ export function rawReach(sql: string): RawReach { let out = exposeMemo.get(column) if (out !== undefined) return out out = - items.some((i) => !starOf(i) && carries(i, column) && reaches(i)) || + // Any item of the model, judged as `passes` judges one on the changed line. + items.some((i) => !spanning(i) && carries(i, column) && reaches(i)) || + // A table's columns that leave a select without being named: the SQL + // does not list them, so the table may hold the column. selects.some((sel) => { - // A select reading a table whose columns are not listed in the SQL. A - // CTE that reads its own name reads the table of that name. + // A CTE that reads its own name reads the table of that name. const isTable = (src: Source) => !scopes.has(src.name) || src.name === sel.scope const tables = sel.own.filter(isTable) + // A nested query also reads the tables of the selects around it. + const around = ancestors(sel.scope) + const outerTables = sel.outer.filter((src) => !scopes.has(src.name) || around.includes(src.name)) + // A table as a whole row (`to_json(c) as payload`): the column leaves + // under the item's name. A `ref` or `source` read without an alias is + // also named by its model. + const rows = [...tables, ...outerTables].flatMap((src) => { + const jinja = src.short ?? src.name + const model = !src.alias && jinja.startsWith("{{") && /["']([^"']+)["'][^"']*$/.exec(jinja)?.[1] + return model ? [...naming(src), model] : naming(src) + }) + if (rows.some((t) => itemsNaming(sel, t).some((item) => namesRow(exprOf(item), t) && reaches(item)))) return true + // An item that cannot be named may read a table of the selects around it. + if (outerTables.length && sel.stars.some((item) => !spanning(item)) && reachMemo(sel.scope, undefined)) return true if (!tables.length && !unknownSources.has(sel.key)) return false + // A table function, `unpivot` or array join over the column in the + // source list moves its values under a name of its own. + if (sel.words.has(column) && reachMemo(sel.scope, undefined)) return true + // A Jinja column list, alone or glued to a `*` (`a.* {{ extra() }}`). + if (sel.jinja.length && reachMemo(sel.scope, column)) return true const tableNames = new Set(tables.flatMap(naming)) const derivedNames = new Set(sel.own.filter((src) => !isTable(src)).flatMap(naming)) - if (sel.jinja.length) return reachMemo(sel.scope, column) - if ( - sel.stars.some((item) => { - const star = starOf(item)! - // A `*` qualified by a CTE or subquery passes that scope's columns only. - if (star.qualifier && derivedNames.has(star.qualifier) && !tableNames.has(star.qualifier)) return false - return star.opaque ? reachMemo(sel.scope, column) : star.carries(column).some((c) => reachMemo(sel.scope, c)) - }) - ) - return true - // A table as a whole row. - return [...tableNames].some((t) => - itemsNaming(sel, t).some( - (item) => columnUses(exprOf(item), t).some((use) => !use.qualifier && !use.path) && reachMemo(sel.scope, column), - ), - ) + return sel.stars.some((item) => { + const star = starOf(item)! + // A `*` qualified by a CTE or subquery passes that scope's columns only. + if (star.qualifier && derivedNames.has(star.qualifier) && !tableNames.has(star.qualifier)) return false + // An item that reads columns it does not name (`object_construct(*) as + // payload`, `$2 as v`) carries the column under the item's own name. + return star.opaque && !spanning(item) ? reaches(item) : star.carries(column).some((c) => reachMemo(sel.scope, c)) + }) }) exposeMemo.set(column, out) return out diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index 88cd7d5173..c85f0360f9 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -220,13 +220,12 @@ describe("finalOutputs().raw", () => { ssn: ["customers|spouses.ssn"], }) }) - test("`starRaw` stays fast over a chain of `*` CTEs that each join the previous one twice", () => { + // Walking every path would take 2^30 steps: a regression does not finish inside the test timeout. + test("`starRaw` resolves a chain of `*` CTEs that each join the previous one twice", () => { const ctes = ["c0 as (select * from customers)"] for (let i = 1; i <= 30; i++) ctes.push(`c${i} as (select * from c${i - 1} a join c${i - 1} b using (customer_id))`) const sql = `with ${ctes.join(",\n")}\nselect * from c30` - const t0 = performance.now() expect([...finalOutputs(sql).starRaw("ssn")]).toEqual(["customers.ssn"]) - expect(performance.now() - t0).toBeLessThan(1000) }) test("`refCovered` matches an unqualified column over a join to its single-table ref", () => { expect(refCovered("customers|orders.email", new Set(["customers.email"]))).toBe(true) @@ -427,6 +426,15 @@ describe("rawReach", () => { ["nested in a condition", src(`\nselect * from ${OTHER} o\nwhere o.customer_id in (select x.tax_ref from (select tax_ref from src) x)`), false], ["scalar subquery in the select list", src(`\nselect o.customer_id, (select s.tax_ref from src s where s.customer_id = o.customer_id) as t\nfrom ${OTHER} o`), true], ["parenthesised union branch", src(`\n(select customer_id, region from ${OTHER})\nunion all\n(select customer_id, tax_ref from src)`), true], + ["parenthesised first branch only", src(`\n(select customer_id from ${OTHER})\nunion all\nselect customer_id from src`), true], + ["parenthesised first branch, a long comment before the operator", src(`, u as (\n (select region as label from ${OTHER})\n -- the two sources never overlap, by construction of the loader (see its README)\n union all\n select tax_ref from src\n)\nselect label from u`), true], + ["parenthesised later branch, a long comment inside the operator", src(`\nselect region from ${OTHER}\nunion /* keep duplicates: the two sources never overlap, checked by hand */ all (select tax_ref from src)`), true], + ["parenthesised branches inside a CTE", src(`, u as (\n (select customer_id from ${OTHER})\n union all\n (select customer_id from src)\n)\nselect customer_id from u`), true], + ["a scalar subquery ends a union branch, column dropped", src("\nselect (select max(customer_id) from analytics.spouses)\nunion all\nselect customer_id from src"), false], + ["a scalar subquery ends a union branch, column carried", src("\nselect (select max(customer_id) from analytics.spouses)\nunion all\nselect tax_ref from src"), true], + ["a `where` subquery ends a union branch, column dropped", src(`\nselect customer_id from src\nwhere customer_id > (select max(customer_id) from ${OTHER})\nunion all\nselect customer_id from ${OTHER}`), false], + ["an unaliased FROM subquery ends a union branch, column dropped", src(`\nselect customer_id from (select customer_id from src)\nunion all\nselect customer_id from ${OTHER}`), false], + ["an unaliased FROM subquery ends a union branch, column carried", src(`\nselect tax_ref from (select tax_ref from src)\nunion all\nselect customer_id from ${OTHER}`), true], ["lateral subquery", src(`\nselect o.customer_id, l.x\nfrom ${OTHER} o, src s, lateral (select s.tax_ref as x) l`), true], ]) }) @@ -438,6 +446,12 @@ describe("rawReach", () => { ["a table function over another column", src("\nselect s.customer_id, f.value as tag from src s, lateral flatten(input => s.tags) f"), false], ["whole row", src("\nselect s from src s"), true], ["whole row in a call", src("\nselect to_json(s) as j from src s"), true], + ["whole row, carried on by its reader", src(", b as (\n select s as row_s, customer_id from src s\n)\nselect row_s from b"), true], + ["whole row, dropped by its reader", src(", b as (\n select s as row_s, customer_id from src s\n)\nselect customer_id from b"), false], + ["whole row by the CTE's own name, in a reader with a source that did not parse", src(`\nselect o.customer_id, row_to_json(src) as payload from ${OTHER} o join ${OTHER} p on true, src`), true], + ["whole row after `unnest(…) with offset`", src(`\nselect o.customer_id, to_json_string(src) as payload from ${OTHER} o, unnest(o.tags) with offset, src`), true], + ["a name resolved at run time", src("\nselect identifier('tax_ref') as t from src"), true], + ["a name resolved at run time, from a variable and behind a comment", src("\nselect IDENTIFIER /* by name */ ($col) as t from src"), true], ["struct expansion of the column", src("\nselect tax_ref.* from src"), true], ["an alias the parser did not read", src("\nselect p.* from src pivot (max(v) for k in ('a')) p"), true], ["parenthesised join", src(`\nselect tax_ref from (src s join ${OTHER} o on o.customer_id = s.customer_id)`), true], @@ -473,6 +487,26 @@ describe("rawReach", () => { expect(item("regexp_replace(ssn, '[0-9]', '*') as s")).toBe(false) expect(item("row_number() over (partition by\n ssn\n order by id) as rn")).toBe(false) expect(item("email")).toBe(false) + // A test that answers true or false. + expect(item("regexp_like(ssn, '^[0-9]+$') as ok")).toBe(false) + expect(item("contains(ssn, '-') as dashed")).toBe(false) + // A `case` keeps what it may return, whatever identifiers sit around it. + expect(item("case when customer_id > 0 then ssn end as t")).toBe(true) + expect(item('concat(e."when", ssn, case when customer_id > 1 then \'x\' else \'y\' end) as t')).toBe(true) + // Another column under the name counts; a cast's type is not a column. + const named = (text: string) => { + const r = rawReach(`select ${text} from t`) + return r.carries(r.items[0], "ssn") + } + expect(named("tax_id as ssn")).toBe(true) + expect(named("cast(tax_id as varchar) as ssn")).toBe(true) + expect(named("cast(null as varchar) as ssn")).toBe(false) + expect(named("md5(tax_id)::varchar(32) as ssn")).toBe(false) + // A method call on the column: masked by a hash, kept by anything else. + expect(item("ssn.md5() as s")).toBe(false) + expect(item("c.ssn.sha256() as s")).toBe(false) + expect(item("ssn.trim() as s")).toBe(true) + expect(item("ssn.replace('-', '').md5() as s")).toBe(true) }) test("passes: a `*` item on the changed line passes the column unless it excludes or masks it", () => { @@ -508,6 +542,70 @@ describe("rawReach", () => { expect(rawReach(src("\nselect * from src")).mayExpose("ssn")).toBe(true) }) + test("mayExpose: an item anywhere in the model that keeps the column and reaches the output", () => { + const exposes = (sql: string) => rawReach(sql).mayExpose("ssn") + // `dead` reads the column and nothing reads `dead`. + const dead = (rest: string) => `with dead as (\n select customer_id,\n ssn\n from ${REF}\n)${rest}` + expect(exposes(dead(`\nselect customer_id from ${OTHER}`))).toBe(false) + expect(exposes(dead(`\nselect customer_id, ssn from ${REF}`))).toBe(true) + expect(exposes(dead(`\nselect d.customer_id, c.ssn as tax_ref from dead d join ${REF} c on c.customer_id = d.customer_id`))).toBe(true) + expect(exposes(dead(`\nselect customer_id, coalesce(ssn, '') as tax_ref from ${REF}`))).toBe(true) + expect(exposes(dead(`\nselect customer_id, sha2(ssn) as tax_ref from ${REF}`))).toBe(false) + expect(exposes(dead(`, b as (\n select customer_id, ssn as tax_ref from ${REF}\n)\nselect tax_ref from b`))).toBe(true) + expect(exposes(dead(`, b as (\n select customer_id, ssn as tax_ref from ${REF}\n)\nselect customer_id from b`))).toBe(false) + expect(exposes(dead(`\nselect o.customer_id, (select max(c.ssn) from ${REF} c where c.customer_id = o.customer_id) as t from ${OTHER} o`))).toBe(true) + expect(exposes(dead(`\nselect o.customer_id, l.t from ${REF} o, lateral (select o.ssn as t) l`))).toBe(true) + // Another value under the column's name, a field of that name, a hierarchy root. + expect(exposes(dead(`, b as (\n select customer_id, tax_id as ssn from ${REF}\n)\nselect * from b`))).toBe(true) + expect(exposes(dead(`, b as (\n select customer_id, payload from ${REF}\n)\nselect payload.ssn as tax_ref from b`))).toBe(true) + expect(exposes(dead(`\nselect customer_id, connect_by_root ssn from ${REF} start with customer_id = 1 connect by prior customer_id = manager_id`))).toBe(true) + // A macro call naming the column, unless the SQL around it masks what it emits. + expect(exposes(dead(`\nselect customer_id, {{ dbt.safe_cast("ssn", "varchar") }} as t from ${REF}`))).toBe(true) + // The table's column next to a CTE's hashed column of the same name. + const hashed = (final: string) => `with h as (\n select customer_id,\n sha2(\n ssn\n ) as ssn\n from ${REF}\n)\n${final}` + expect(exposes(hashed("select * from h"))).toBe(false) + expect(exposes(hashed("select customer_id from h"))).toBe(false) + expect(exposes(hashed(`select ssn, c.customer_id from h right join ${REF} c using (ssn)`))).toBe(true) + // Names are all it reads: the hashed column selected by its name counts. + expect(exposes(hashed("select customer_id, ssn from h"))).toBe(true) + // A CTE named like the table an earlier CTE reads. + expect(exposes(`with raw_rows as (\n select customer_id, ssn from customers\n), customers as (\n select customer_id from raw_rows\n)\nselect r.customer_id, r.ssn from raw_rows r join customers c on c.customer_id = r.customer_id`)).toBe(true) + }) + + test("mayExpose: a table's columns that leave a select unnamed", () => { + const exposes = (sql: string) => rawReach(sql).mayExpose("ssn") + expect(exposes(`with a as (\n select object_construct(*) as payload from ${REF}\n)\nselect payload from a`)).toBe(true) + expect(exposes(`with a as (\n select object_construct(*) as payload from ${REF}\n)\nselect customer_id from ${OTHER}`)).toBe(false) + expect(exposes(`with a as (\n select to_json(c) as payload from ${REF} c\n)\nselect payload from a`)).toBe(true) + expect(exposes(`with a as (\n select to_json(c) as payload, c.customer_id from ${REF} c\n)\nselect customer_id from a`)).toBe(false) + // A `ref` read without an alias is also named by its model; with one, only by the alias. + expect(exposes(`with a as (\n select to_json(customers) as payload from ${REF}\n)\nselect payload from a`)).toBe(true) + expect(exposes(`select d.day, cast(d.day as date) as day_date from {{ ref('date') }} d`)).toBe(false) + // A date part spelled like the alias is not the row. + expect(exposes(`select s.customer_id, dateadd(s, s.duration_s, s.started_at) as ended_at from ${REF} s`)).toBe(false) + expect(exposes(`select s.customer_id, coalesce(s, null) as payload from ${REF} s`)).toBe(true) + // The whole row of an outer table, inside a scalar subquery. + expect(exposes(`select c.customer_id, (select to_json(c)) as payload from ${REF} c`)).toBe(true) + expect(exposes(`with a as (\n select * from ${REF} unpivot (v for k in (ssn, region))\n)\nselect v from a`)).toBe(true) + expect(exposes(`with a as (\n select c.customer_id, t from ${REF} c cross join unnest([c.ssn]) as u(t)\n)\nselect t from a`)).toBe(true) + expect(exposes(`with a as (\n select identifier('ssn') as t from ${REF}\n)\nselect t from a`)).toBe(true) + // A masking call over the row reads no column; a product with a masked operand is a product. + expect(exposes(`select customer_id, hash(*) as row_hash from ${REF}`)).toBe(false) + expect(exposes(`select c.customer_id, count(o.*) as orders from ${REF} c left join ${OTHER} o on o.customer_id = c.customer_id group by 1`)).toBe(false) + expect(exposes(`select c.customer_id, to_json(o.*) as payload from ${REF} c left join ${OTHER} o on o.customer_id = c.customer_id`)).toBe(true) + expect(exposes(`select customer_id, datediff(day, created_at, updated_at) * 24 as hours from ${REF}`)).toBe(false) + expect(exposes(`select customer_id, concat(to_json(c), case when customer_id > 1 then 'x' end) as payload from ${REF} c`)).toBe(true) + // A Jinja call glued to a `*` may add the column. + expect(exposes(`with a as (select customer_id from ${OTHER})\nselect a.* {{ extra('c.ssn') }} from a join ${REF} c on c.customer_id = a.customer_id`)).toBe(true) + // A literal's prefix and a cast's type are not the row. + expect(exposes(`select r.customer_id, regexp_extract(r.region, r'^[a-z]+') as zone from ${REF} r`)).toBe(false) + expect(exposes(`select d.day, cast(d.day as date) as day_date from {{ ref('date') }} as date`)).toBe(false) + // A Jinja column list may hold the column under any name. + expect(exposes(`with a as (\n select {{ dbt_utils.star(from=ref('customers')) }} from ${REF}\n)\nselect customer_id from a`)).toBe(true) + // SQL the parser does not model may expose anything. + expect(exposes(`select t.customer_id\nfrom (\n with a as (select customer_id, sha2(ssn) as h from ${REF})\n select * from a\n) t`)).toBe(true) + }) + test("inClause: a line outside every select list is told apart only by the clause word before it", () => { const at = (sql: string, text: string) => rawReach(sql).inClause(sql.split("\n").findIndex((l) => l.trim() === text) + 1) expect(at(`select customer_id\nfrom ${REF}\norder by\n ssn`, "ssn")).toBe(true) @@ -533,7 +631,8 @@ describe("rawReach", () => { }) test("shapes the parser does not model block: every `ssn` line counts as reaching", () => { - // As the orchestrator asks it: the items on the line, else the clause it sits in. + // The line's own evidence, as the orchestrator asks it after `mayExpose`: + // the items on the line, else the clause it sits in. const lineReaches = (sql: string) => { const r = rawReach(sql) return sql.split("\n").flatMap((text, at) => { @@ -656,12 +755,13 @@ describe("rawReach", () => { } }) - test("deeply nested subqueries stay fast", () => { + // No time is asserted in the next two: a walk that stalls fails on the test timeout. + test("subqueries nested past any real model's depth count as reaching", () => { const depth = 800 const sql = "select x from " + "(select x from ".repeat(depth) + `(select\n ssn as x\n from ${REF}) t` + ") t".repeat(depth) - const t0 = performance.now() expect(reaches(sql)).toBe(true) - expect(performance.now() - t0).toBeLessThan(3000) + // Nothing shows the column dropped either: the nesting is not followed. + expect(reaches(sql.replace("select x from (", "select 1 as one from ("))).toBe(true) }) test("malformed SQL and deep chains do not throw or stall", () => { @@ -675,9 +775,7 @@ describe("rawReach", () => { `with c0 as (\n select customer_id,\n ssn as x0\n from ${REF}\n)` + Array.from({ length: n }, (_, i) => `, c${i + 1} as (\n select customer_id, x${i} as x${i + 1}, ${Array.from({ length: 30 }, (_, k) => `f${k}`).join(", ")} from c${i}\n)`).join("") + `\nselect x${n} from c${n}` - const t0 = performance.now() expect(reaches(chain)).toBe(true) expect(reaches(chain.replace(`select x${n} from`, "select customer_id from"))).toBe(false) - expect(performance.now() - t0).toBeLessThan(2000) }) }) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index b6698f6f5c..e4e2bd86cc 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -1,4 +1,5 @@ -import { describe, test, expect } from "bun:test" +import { describe, test, expect, spyOn } from "bun:test" +import * as RuleCatalog from "../../src/altimate/review/rule-catalog" import { makeFinding, fingerprint, @@ -3300,6 +3301,29 @@ describe("orchestrate", () => { { name: "multi-line coalesce keeps the value", base: plainBase, head: `select customer_id,\n coalesce(\n ssn,\n ''\n ) as tax_ref\nfrom ${REF}`, critical: true }, { name: "kept by `max` in the final select", base: cteBase, head: src("ssn as tax_ref", "\nselect\n customer_id,\n max(tax_ref) as tax_ref\nfrom src\ngroup by 1"), critical: true }, { name: "a Jinja column list in the final select", base: cteBase, head: src("ssn", "\nselect\n {{ dbt_utils.star(from=ref('customers'), except=['region']) }}\nfrom src"), critical: true }, + { name: "read by a name resolved at run time", base: cteBase, head: src("ssn", "\nselect\n customer_id,\n identifier('ssn') as tax_ref\nfrom src"), critical: true }, + // Dropped or masked on the changed line, and selected raw on a line the regex rules do not fire on. + { name: "dropped by its CTE, selected on one line by the final select", base: cteBase, head: src("ssn as tax_ref", `\nselect customer_id, ssn from ${REF}`), critical: true }, + { + name: "dropped by its CTE, read from the table again under a qualifier", + base: cteBase, + head: src("ssn", `\nselect s.customer_id, c.ssn as tax_ref\nfrom src s\njoin ${REF} c on c.customer_id = s.customer_id`), + critical: true, + }, + { name: "dropped by its CTE, `select *` over its table", base: cteBase, head: src("ssn as tax_ref", `\nselect * from ${REF}`), critical: true }, + // A limit of reading names: a hash kept under the column's own name, then selected by that name, reads as the column. + { + name: "hashed under the same name, then selected by that name", + base: cteBase, + head: src("ssn", ", final as (\n select customer_id, sha2(ssn) as ssn\n from src\n)\nselect customer_id, ssn\nfrom final"), + critical: true, + }, + { + name: "hashed on its line, kept by another item on one line", + base: plainBase, + head: `select customer_id, coalesce(ssn, '') as raw_ref,\n sha2(\n ssn\n ) as tax_ref\nfrom ${REF}`, + critical: true, + }, // Masked, dropped, or only tested: undecided. { name: "multi-line sha2 in a CTE", @@ -3322,16 +3346,29 @@ describe("orchestrate", () => { critical: false, }, { - name: "hashed under the same name", + name: "hashed under the same name, then `select *`", base: cteBase, - head: src("ssn", ", final as (\n select customer_id, sha2(ssn) as ssn\n from src\n)\nselect customer_id, ssn\nfrom final"), + head: src("ssn", ", final as (\n select customer_id, sha2(ssn) as ssn\n from src\n)\nselect * from final"), critical: false, }, { name: "`* exclude` of the column", base: cteBase, head: src("ssn", "\nselect * exclude (ssn)\nfrom src"), critical: false }, { name: "read only by an `exists` condition", base: cteBase, - head: src("ssn", `\nselect o.*\nfrom ${OTHER} o\nwhere exists (select * from src s where s.customer_id = o.customer_id)`), + head: src("ssn", `\nselect o.customer_id\nfrom ${OTHER} o\nwhere exists (select * from src s where s.customer_id = o.customer_id)`), + critical: false, + }, + { name: "a method-style hash", base: plainBase, head: `select customer_id,\n ssn.md5() as tax_ref\nfrom ${REF}`, critical: false }, + { + name: "kept in a whole row that its reader drops", + base: cteBase, + head: src("ssn", ", b as (\n select s as row_s, s.customer_id\n from src s\n)\nselect\n customer_id\nfrom b"), + critical: false, + }, + { + name: "dropped, in a union whose first branch ends in a scalar subquery", + base: cteBase, + head: src("ssn", "\nselect (select max(customer_id) from analytics.spouses)\nunion all\nselect customer_id from src"), critical: false, }, { name: "`order by` line, not selected", base: plainBase, head: `select customer_id\nfrom ${REF}\norder by\n ssn`, critical: false }, @@ -3384,22 +3421,36 @@ describe("orchestrate", () => { }) test("the raw-base proof parses each file once however many PII lines it adds", async () => { - // 300 added PII lines in a 3,000-column CTE: the proof is asked twice per line. - const cols = Array.from({ length: 3000 }, (_, i) => ` c${i},`).join("\n") - const pii = Array.from({ length: 300 }, (_, i) => ` ssn as t${i},`).join("\n") - const base = `with src as (\n select\n${cols}\n customer_id\n from {{ ref('customers') }}\n)\nselect * from src` - const head = `with src as (\n select\n${cols}\n${pii}\n customer_id\n from {{ ref('customers') }}\n)\nselect customer_id from src` - const t0 = performance.now() - const env = await runReview({ - changedFiles: [{ path: "models/marts/m1.sql", status: "modified" as const, diff: `${pii.split("\n").map((l) => `+${l}`).join("\n")}\n` }], - config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, - rubric: DEFAULT_RUBRIC, - mode: "gate", - runner: piiRunner(["ssn"]), - getContent: content(head, base), - }) - expect(env.findings.filter(isTwin).length).toBeGreaterThan(0) - expect(performance.now() - t0).toBeLessThan(1500) + // Added PII lines in a wide CTE: the proof is asked twice per line. + const cols = Array.from({ length: 200 }, (_, i) => ` c${i},`).join("\n") + const base = `with src as (\n select\n${cols}\n customer_id\n from {{ ref('customers') }}\n)\nselect customer_id from src` + const parses = async (lines: number) => { + const pii = Array.from({ length: lines }, (_, i) => ` ssn as t${i},`).join("\n") + const head = `with src as (\n select\n${cols}\n${pii}\n customer_id\n from {{ ref('customers') }}\n)\nselect customer_id from src` + // Counts the orchestrator's own calls into the parser. + const reach = spyOn(RuleCatalog, "rawReach") + const items = spyOn(RuleCatalog, "selectItems") + try { + const env = await runReview({ + changedFiles: [{ path: "models/marts/m1.sql", status: "modified" as const, diff: `${pii.split("\n").map((l) => `+${l}`).join("\n")}\n` }], + config: { ...DEFAULT_REVIEW_CONFIG, reviewers: ["dbt_patterns"] }, + rubric: DEFAULT_RUBRIC, + mode: "gate", + runner: piiRunner(["ssn"]), + getContent: content(head, base), + }) + return { twins: env.findings.filter(isTwin).length, head: reach.mock.calls.length, base: items.mock.calls.length } + } finally { + reach.mockRestore() + items.mockRestore() + } + } + const one = await parses(1) + const many = await parses(300) + expect(one.twins).toBeGreaterThan(0) + expect(many.twins).toBeGreaterThan(0) + expect(one.head).toBe(1) + expect({ head: many.head, base: many.base }).toEqual({ head: one.head, base: one.base }) }) test("without a compiled base, an added `c.ssn` over a raw base with no `ssn` still blocks", async () => { From d8895dc5adae75900da3154404df2750dab76a6f Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Mon, 30 Nov 2026 01:37:05 +0530 Subject: [PATCH 80/81] fix(review): read `with offset` across any comment, and a typed literal as a constant in the PII reach analysis MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `unnest(…) with offset`: the word before `offset` is read across any amount of white space. A comment longer than the old 200-character window hid the `with`, so a source after it was dropped and a whole-row exposure lost its block. - `namesRow`: the type word of a typed literal (`date '2024-01-01'`) is not a whole-row reference to a source or model named `date`. - `carries`: a typed literal under the column's name (`date '1900-01-01' as ssn`) is a constant, not a value. - `mayExpose`: drop two `reachMemo(scope, undefined)` conjuncts that were always true. - Test: the parse-once fixture is 3,000 columns wide again. Co-Authored-By: Claude Fable 5.2 --- .../src/altimate/review/rule-catalog.ts | 31 +++++++++++++------ .../test/altimate/review-rule-catalog.test.ts | 17 ++++++++++ .../opencode/test/altimate/review.test.ts | 2 +- 3 files changed, 39 insertions(+), 11 deletions(-) diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index d24b5545ab..2bd49a1c71 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -580,6 +580,14 @@ function parseSelects(sql: string): ParsedSelects { } return false } + // The word that ends before `at`, across any white space (a masked comment is white space). + const wordBefore = (at: number) => { + let stop = at + while (stop > 0 && /\s/.test(s[stop - 1])) stop-- + let from = stop + while (from > 0 && /[\w$]/.test(s[from - 1])) from-- + return s.slice(from, stop).toLowerCase() + } // The last 40 characters before `at`, each run of white space as one space. const textBefore = (at: number) => { let out = "" @@ -836,7 +844,7 @@ function parseSelects(sql: string): ParsedSelects { } else if (boundary && FROM_LIST_END.test(s.slice(j, j + 10))) { // `unnest(x) with offset` is part of a source, not the end of the // list: what follows it is not read as a source. - if (inFrom && /^offset\b/i.test(s.slice(j, j + 7)) && /\bwith\s+$/i.test(s.slice(Math.max(0, j - 200), j))) unknownSources.add(key) + if (inFrom && /^offset\b/i.test(s.slice(j, j + 7)) && wordBefore(j) === "with") unknownSources.add(key) closeSegment(j) inCondition = inFrom || inCondition ? /^(?:on|using)\b/i.test(s.slice(j, j + 6)) : false inFrom = false @@ -1260,12 +1268,15 @@ function columnUses(expr: string, name: string): Array<{ qualifier?: string; pat /** `name` (a source's alias) stands in the expression as a whole row (`select * s`, `to_json(s)`): alone, and not as the date part of `dateadd(s, …)`, the - * prefix of a literal (`r'…'`, `e'…'`), or a type or field name after `as` - * (`cast(x as date)`, `struct(o.id as o)`). */ + * prefix of a literal (`r'…'`, `e'…'`), the type of a typed literal (`date + * '2024-01-01'`), or a type or field name after `as` (`cast(x as date)`, + * `struct(o.id as o)`). */ const NOT_A_ROW_BEFORE = /(?:(? !use.qualifier && !use.path && !NOT_A_ROW_BEFORE.test(expr.slice(0, use.at)) && !/^["\x60]?[\w$]+["\x60]?'/.test(expr.slice(use.at)), + // Blanked in place, so the offsets still hold. + const e = expr.replace(TYPED_LITERAL, (literal) => " ".repeat(literal.length)) + return columnUses(e, name).some( + (use) => !use.qualifier && !use.path && !NOT_A_ROW_BEFORE.test(e.slice(0, use.at)) && !/^["\x60]?[\w$]+["\x60]?'/.test(e.slice(use.at)), ) } @@ -1772,9 +1783,9 @@ export function rawReach(sql: string): RawReach { if (columnUses(expr, column).length > 0 || new RegExp(`\\b${column.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i").test(expr)) return true // Some other column, unmasked, under the PII name: an identifier that is // neither a call nor a keyword is left in the expression. - // The type of a cast is not one (`cast(null as varchar) as ssn`, - // `md5(x)::varchar as ssn`). - const values = expr.replace(/::\s*["\x60]?[\w$]+["\x60]?(?:\s*\([\d\s,]*\))?/g, " ").replace(/(? itemsNaming(sel, t).some((item) => namesRow(exprOf(item), t) && reaches(item)))) return true // An item that cannot be named may read a table of the selects around it. - if (outerTables.length && sel.stars.some((item) => !spanning(item)) && reachMemo(sel.scope, undefined)) return true + if (outerTables.length && sel.stars.some((item) => !spanning(item))) return true if (!tables.length && !unknownSources.has(sel.key)) return false // A table function, `unpivot` or array join over the column in the // source list moves its values under a name of its own. - if (sel.words.has(column) && reachMemo(sel.scope, undefined)) return true + if (sel.words.has(column)) return true // A Jinja column list, alone or glued to a `*` (`a.* {{ extra() }}`). if (sel.jinja.length && reachMemo(sel.scope, column)) return true const tableNames = new Set(tables.flatMap(naming)) diff --git a/packages/opencode/test/altimate/review-rule-catalog.test.ts b/packages/opencode/test/altimate/review-rule-catalog.test.ts index c85f0360f9..07bbbb7e92 100644 --- a/packages/opencode/test/altimate/review-rule-catalog.test.ts +++ b/packages/opencode/test/altimate/review-rule-catalog.test.ts @@ -450,6 +450,7 @@ describe("rawReach", () => { ["whole row, dropped by its reader", src(", b as (\n select s as row_s, customer_id from src s\n)\nselect customer_id from b"), false], ["whole row by the CTE's own name, in a reader with a source that did not parse", src(`\nselect o.customer_id, row_to_json(src) as payload from ${OTHER} o join ${OTHER} p on true, src`), true], ["whole row after `unnest(…) with offset`", src(`\nselect o.customer_id, to_json_string(src) as payload from ${OTHER} o, unnest(o.tags) with offset, src`), true], + ["whole row after `unnest(…) with offset`, a long comment inside it", src(`\nselect o.customer_id, to_json_string(src) as payload from ${OTHER} o, unnest(o.tags) with /* the position is kept so that the tags can be put back in their original order downstream; the loader does not guarantee any order of its own, and two consumers rely on the first tag being the primary one */ offset, src`), true], ["a name resolved at run time", src("\nselect identifier('tax_ref') as t from src"), true], ["a name resolved at run time, from a variable and behind a comment", src("\nselect IDENTIFIER /* by name */ ($col) as t from src"), true], ["struct expansion of the column", src("\nselect tax_ref.* from src"), true], @@ -572,6 +573,22 @@ describe("rawReach", () => { expect(exposes(`with raw_rows as (\n select customer_id, ssn from customers\n), customers as (\n select customer_id from raw_rows\n)\nselect r.customer_id, r.ssn from raw_rows r join customers c on c.customer_id = r.customer_id`)).toBe(true) }) + test("mayExpose: the type word of a typed literal is neither a row nor a value", () => { + const exposes = (sql: string) => rawReach(sql).mayExpose("ssn") + // A model or an alias named like a type. + expect(exposes("select customer_id, md5(ssn) as h, date '2024-01-01' as d from {{ ref('date') }}")).toBe(false) + expect(exposes("select customer_id, md5(ssn) as h, date '2024-01-01' as d from analytics.dim_date date")).toBe(false) + expect(exposes("select customer_id, md5(ssn) as h, to_json(date) as d from {{ ref('date') }}")).toBe(true) + expect(exposes("select customer_id, date '2024-01-01' as d, to_json(date) as p from {{ ref('date') }}")).toBe(true) + // A constant under the column's name. + expect(exposes(`select customer_id, date '1900-01-01' as ssn from ${REF}`)).toBe(false) + expect(exposes(`select customer_id, interval 1 day as ssn from ${REF}`)).toBe(false) + expect(exposes(`select customer_id, coalesce(tax_date, date '1900-01-01') as ssn from ${REF}`)).toBe(true) + expect(exposes(`select customer_id, date as ssn from ${REF}`)).toBe(true) + // A string that ends in a type word hides nothing after it. + expect(exposes(`select customer_id, concat('due date ', tax_id, ' ok') as ssn from ${REF}`)).toBe(true) + }) + test("mayExpose: a table's columns that leave a select unnamed", () => { const exposes = (sql: string) => rawReach(sql).mayExpose("ssn") expect(exposes(`with a as (\n select object_construct(*) as payload from ${REF}\n)\nselect payload from a`)).toBe(true) diff --git a/packages/opencode/test/altimate/review.test.ts b/packages/opencode/test/altimate/review.test.ts index e4e2bd86cc..44a60b3d18 100644 --- a/packages/opencode/test/altimate/review.test.ts +++ b/packages/opencode/test/altimate/review.test.ts @@ -3422,7 +3422,7 @@ describe("orchestrate", () => { test("the raw-base proof parses each file once however many PII lines it adds", async () => { // Added PII lines in a wide CTE: the proof is asked twice per line. - const cols = Array.from({ length: 200 }, (_, i) => ` c${i},`).join("\n") + const cols = Array.from({ length: 3000 }, (_, i) => ` c${i},`).join("\n") const base = `with src as (\n select\n${cols}\n customer_id\n from {{ ref('customers') }}\n)\nselect customer_id from src` const parses = async (lines: number) => { const pii = Array.from({ length: lines }, (_, i) => ` ssn as t${i},`).join("\n") From 2cf3250e0121356c4cd00b663df53341209484ee Mon Sep 17 00:00:00 2001 From: RaghwendraSingh Date: Tue, 1 Dec 2026 18:15:48 +0530 Subject: [PATCH 81/81] fix(review): a reindent does not hide a changed source, and a `USING` column needs every joined side covered MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A PII finding on a re-indented select item was dropped when the base had the same item text, even if the pull request also changed the table it reads from. The pairing now includes the select's FROM/JOIN sources, followed through the CTEs and subqueries it reads; a source the parser cannot name counts as changed. - An unqualified column merged by `using (…)` or a `natural` join takes values from every joined side. It resolved to one combined ref that a single base table could cover, so a newly joined table's column read as already exposed. It now resolves to one ref per side. Co-Authored-By: Claude Fable 5.2 --- .../src/altimate/review/orchestrate.ts | 31 ++- .../src/altimate/review/rule-catalog.ts | 73 ++++++- .../altimate/review-pii-source-change.test.ts | 193 ++++++++++++++++++ 3 files changed, 289 insertions(+), 8 deletions(-) create mode 100644 packages/opencode/test/altimate/review-pii-source-change.test.ts diff --git a/packages/opencode/src/altimate/review/orchestrate.ts b/packages/opencode/src/altimate/review/orchestrate.ts index 3cc493876d..4f4a015791 100644 --- a/packages/opencode/src/altimate/review/orchestrate.ts +++ b/packages/opencode/src/altimate/review/orchestrate.ts @@ -27,6 +27,7 @@ import { SILENT_JINJA_TAG, normalizeSelectLine, selectItems, + selectSources, } from "./rule-catalog" import { type AiLaneStatus, type AiReviewInput, type AiReviewResult, safeReason } from "./ai-review" @@ -1563,9 +1564,18 @@ export async function runReview(input: OrchestrateInput): Promise; head: SelectItem[]; headLines: string[]; base: Set }>() - const itemKey = (i: SelectItem) => `${i.scope}#${i.branch}\u0000${i.text.toLowerCase()}` + // is unwrapped, exposes something new. The item's FROM/JOIN sources must be + // unchanged too: `ssn` reindented while `from customers` became `from + // spouses` reads another table's column. Sources the parser cannot name never + // match. + const reindentByFile = new Map< + string, + { removed: Set; head: SelectItem[]; headLines: string[]; base: Set; headSources: ReturnType } + >() + const itemKey = (i: SelectItem, sourcesOf: ReturnType) => { + const src = sourcesOf(i.scope, i.branch) + return src === undefined ? undefined : `${i.scope}#${i.branch}\u0000${i.text.toLowerCase()}\u0000${src}` + } const reindentInfo = (file: string) => { const ctx = ctxByPath.get(file) if (!ctx?.newSql) return undefined @@ -1576,7 +1586,15 @@ export async function runReview(input: OrchestrateInput): Promise(), + headSources: selectSources(ctx.newSql), + } + if (ctx.oldSql) { + const baseSources = selectSources(ctx.oldSql) + for (const i of selectItems(ctx.oldSql)) { + const key = itemKey(i, baseSources) + if (key !== undefined) r.base.add(key) + } } reindentByFile.set(file, r) } @@ -1598,7 +1616,10 @@ export async function runReview(input: OrchestrateInput): Promise 0 && items.every((i) => r.base.has(itemKey(i))) + return items.length > 0 && items.every((i) => { + const key = itemKey(i, r.headSources) + return key !== undefined && r.base.has(key) + }) } // Without a compiled base every other PII lane is undecided (an unknown- // confidence warning). A regex twin whose source columns the raw base cannot diff --git a/packages/opencode/src/altimate/review/rule-catalog.ts b/packages/opencode/src/altimate/review/rule-catalog.ts index 2bd49a1c71..94274f12dd 100644 --- a/packages/opencode/src/altimate/review/rule-catalog.ts +++ b/packages/opencode/src/altimate/review/rule-catalog.ts @@ -422,6 +422,13 @@ interface ParsedSelects { * names, aliases and table-function or `pivot`/`unpivot` arguments, without * the bodies of FROM subqueries and without join conditions. */ sourceText: Map + /** As `sourceText`, with Jinja expressions, literals and quoted identifiers as + * written (`ref('a')` and `ref('b')` differ) and words lowercased, for telling + * whether a select's sources changed between base and head. */ + sourceExact: Map + /** Per `scope#branch`, the columns its `using (…)` joins merge, or `"all"` + * for a `natural` join: such a column takes values from every joined source. */ + merged: Map | "all"> /** `scope#branch` selects with a source the parser could not name: a * parenthesised join, a Jinja expression other than `ref`/`source`/`this`, a * comma-joined source after a join condition, or no source at all in a @@ -495,6 +502,10 @@ function parseSelects(sql: string): ParsedSelects { const items: SelectItem[] = [] const sources = new Map() const sourceText = new Map() + const sourceExact = new Map() + const merged = new Map | "all">() + // Comments and Jinja statements blanked, everything else as written (offsets kept). + const exactView = sql.replace(MASKED_TOKEN, (m) => (/^(?:\{\{|'|")/.test(m) ? m : m.replace(/[^\n]/g, " "))) const unknownSources = new Set() const predicates = new Set() const jinjaItems = new Set() @@ -768,11 +779,13 @@ function parseSelects(sql: string): ParsedSelects { // The source list's own text, one segment per source: from after `from`, // `join` or `,` to the next of them or the word that ends the list. let text = "" + let exact = "" let segment = -1 const closeSegment = (stop: number) => { if (segment >= 0) { const part = s.slice(segment, stop) text += ` ${part}` + exact += ` ${exactView.slice(segment, stop)}` // Without the white space around it, so the range holds no line it only touches. if (part.trim()) sourceRanges.push([segment + part.length - part.trimStart().length, segment + part.trimEnd().length]) } @@ -845,6 +858,13 @@ function parseSelects(sql: string): ParsedSelects { // `unnest(x) with offset` is part of a source, not the end of the // list: what follows it is not read as a source. if (inFrom && /^offset\b/i.test(s.slice(j, j + 7)) && wordBefore(j) === "with") unknownSources.add(key) + const using = (inFrom || inCondition) && /^using\s*\(/i.exec(s.slice(j, j + 40)) + if (using) { + const open = j + using[0].length - 1 + const cols = merged.get(key) ?? new Set() + if (cols !== "all") for (const c of s.slice(open + 1, closingParen(s, open)).split(",")) if (c.trim()) cols.add(unquote(c.trim())) + merged.set(key, cols) + } closeSegment(j) inCondition = inFrom || inCondition ? /^(?:on|using)\b/i.test(s.slice(j, j + 6)) : false inFrom = false @@ -855,10 +875,18 @@ function parseSelects(sql: string): ParsedSelects { if (!read.length && /(? (/^['"]/.test(m) ? m : m.toLowerCase().replace(/\s+/g, " "))) + .trim(), + ) + // `natural join` merges every same-named column of its sources. + if (/(? !selectScopes.has(name))) unmodelled = true - return { items, sources, sourceText, unknownSources, predicates, unmodelled, misread, jinjaItems, jinjaCalls, sourceRanges, scopeOpen, scopeParent } + return { items, sources, sourceText, sourceExact, merged, unknownSources, predicates, unmodelled, misread, jinjaItems, jinjaCalls, sourceRanges, scopeOpen, scopeParent } } /** @@ -871,6 +899,34 @@ export function selectItems(sql: string): SelectItem[] { return parseSelects(sql).items } +/** + * Per select (`scope`, `branch`), the text of every FROM/JOIN source it reads + * (`ParsedSelects.sourceExact`), followed through the CTEs and FROM subqueries + * it reads, so a table swapped upstream changes it too. `undefined` when any + * select on the way has a source the parser could not name: such sources can + * never be shown unchanged. + */ +export function selectSources(sql: string): (scope: string, branch: number) => string | undefined { + const { sourceExact, sources, unknownSources } = parseSelects(sql) + const branchesOf = new Map() + for (const key of sourceExact.keys()) { + const scope = key.slice(0, key.lastIndexOf("#")) + branchesOf.set(scope, [...(branchesOf.get(scope) ?? []), key]) + } + return (scope, branch) => { + const parts: string[] = [] + const seen = new Set() + const walk = (key: string): boolean => { + if (seen.has(key)) return true + seen.add(key) + if (unknownSources.has(key) || !sourceExact.has(key)) return false + parts.push(`${key}\u0000${sourceExact.get(key)}`) + return (sources.get(key) ?? []).every((src) => (branchesOf.get(src.name) ?? []).every(walk)) + } + return walk(`${scope}#${branch}`) ? parts.join("\u0001") : undefined + } +} + const STAR = new RegExp(String.raw`^(?:${SEGMENT}\.)*\*$`) /** The model's final output, as `finalOutputs` resolves it. */ @@ -966,7 +1022,8 @@ function sameTable(h: string, b: string, env?: RelationPrefixes): boolean { /** * `ref` is one of the `exposed` source columns. An unqualified column read over * several tables (`customers|orders.email`, see `FinalOutputs.raw`) comes from - * exactly one of them (the query would be ambiguous otherwise), so it is + * exactly one of them (the query would be ambiguous otherwise; a column merged + * by `using`/`natural` resolves to one ref per source instead), so it is * covered by a single-table ref to one of its members. The reverse is not: a * base combined ref does not say which table the column came from, so a head * read pinned to one of them (`s.ssn`) may be new. Two combined refs match only @@ -998,7 +1055,7 @@ const lowerOutsideLiterals = (sql: string) => /** The model's final output: every name it resolves, the source columns each * exposes raw (`raw`), and how each is computed. */ export function finalOutputs(sql: string): FinalOutputs { - const { items, sources } = parseSelects(sql) + const { items, sources, merged } = parseSelects(sql) const byScope = new Map() for (const item of items) { const list = byScope.get(item.scope) @@ -1065,6 +1122,16 @@ export function finalOutputs(sql: string): FinalOutputs { srcs.find((x) => x.alias === qualifier) ?? srcs.find((x) => !x.alias && named(x)) ?? srcs.find(named) return src ? fromSource(src) : same(unresolved(col)) } + // A column merged by `using (…)` / `natural join` takes values from every + // joined source (`full outer`, `right`), so it resolves to one ref per + // source that may hold it, as a `*` does, never to a combined ref. + const mergedCols = merged.get(`${scope}#${branch}`) + if (mergedCols === "all" || mergedCols?.has(col)) { + const holders = srcs.filter((x) => + isDerived(x, scope, seen) ? resolve(x.name, inner).names.has(col) || resolve(x.name, inner).stars.length > 0 : !byScope.has(x.name), + ) + return holders.length ? unionRefs(holders.map(fromSource)) : same(unresolved(col)) + } const named = srcs.filter((x) => isDerived(x, scope, seen) && resolve(x.name, inner).names.has(col)) if (named.length) return unionRefs(named.map(fromSource)) const open = srcs.filter((x) => diff --git a/packages/opencode/test/altimate/review-pii-source-change.test.ts b/packages/opencode/test/altimate/review-pii-source-change.test.ts new file mode 100644 index 0000000000..b82734f1f7 --- /dev/null +++ b/packages/opencode/test/altimate/review-pii-source-change.test.ts @@ -0,0 +1,193 @@ +import { describe, test, expect } from "bun:test" +import * as RC from "../../src/altimate/review/rule-catalog" +import { runReview, DEFAULT_RUBRIC, DEFAULT_REVIEW_CONFIG, type ReviewRunner, type ChangedFile } from "../../src/altimate/review" + +// A PII check must not lose a report because a changed FROM/JOIN source hides +// behind a reindent (fix 1), or because a column merged by `using` / `natural` +// joins is credited to a single side (fix 2). + +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 +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[]): ReviewRunner => ({ + ...base, + async detectPii(sql: string) { + return { columns: 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: async () => [], +}) +const P = "models/marts/m.sql" +const run = async (o: { head: string; base: string; diff: string; reviewers: string[] }) => { + 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: piiRunner(["ssn"]), + getContent: async (_f: string, side: "old" | "new") => (side === "new" ? o.head : o.base), + }) + const pii = env.findings.filter((f) => f.category === "pii_exposure") + return { verdict: env.verdict, pii, critical: pii.some((f) => f.severity === "critical") } +} +const lines = (sign: "-" | "+", sql: string) => sql.split("\n").map((l) => `${sign}${l}`).join("\n") + "\n" + +describe("fix 1: a reindent does not hide a changed FROM/JOIN source", () => { + const twins = (base: string, head: string, diff: string) => run({ base, head, diff, reviewers: ["dbt_patterns"] }) + + test("reindent + table swap is reported", async () => { + const r = await twins( + "select customer_id,\n ssn\nfrom customers", + "select customer_id,\n ssn\nfrom spouses", + "- ssn\n-from customers\n+ ssn\n+from spouses\n", + ) + expect(r.verdict).toBe("REQUEST_CHANGES") + expect(r.critical).toBe(true) + }) + + // With an `on` join the unqualified `ssn` resolves to `customers|spouses.ssn`, + // which the base's `customers.ssn` covers even without a reindent, so the + // added join here merges `ssn` by `using` to make it reach `spouses`. + test("reindent + a join added is reported", async () => { + const r = await twins( + "select customer_id,\n ssn\nfrom customers c", + "select customer_id,\n ssn\nfrom customers c\njoin spouses s using (ssn)", + "- ssn\n+ ssn\n+join spouses s using (ssn)\n", + ) + expect(r.critical).toBe(true) + }) + + test("reindent + a joined table swapped is reported", async () => { + const r = await twins( + "select customer_id,\n ssn\nfrom customers c\njoin orders o on o.id = c.id", + "select customer_id,\n ssn\nfrom customers c\njoin spouses o on o.id = c.id", + "- ssn\n-join orders o on o.id = c.id\n+ ssn\n+join spouses o on o.id = c.id\n", + ) + expect(r.critical).toBe(true) + }) + + // Without a compiled base the twins are unknown-confidence warnings: the + // reindented item must report exactly what the same change without a reindent does. + test("reindent + a ref swapped to a same-length name is reported (Jinja is compared as written)", async () => { + const shape = (r: Awaited>) => r.pii.map((f) => `${f.severity}/${f.confidence}/${(f.evidence?.result as any)?.rule}`) + const r = await twins( + "select customer_id,\n ssn\nfrom {{ ref('aaaa') }}", + "select customer_id,\n ssn\nfrom {{ ref('bbbb') }}", + "- ssn\n-from {{ ref('aaaa') }}\n+ ssn\n+from {{ ref('bbbb') }}\n", + ) + const plain = await twins( + "select customer_id,\n ssn\nfrom {{ ref('aaaa') }}", + "select customer_id,\n ssn\nfrom {{ ref('bbbb') }}", + "-from {{ ref('aaaa') }}\n+ ssn\n+from {{ ref('bbbb') }}\n", + ) + expect(shape(r).length).toBeGreaterThan(0) + expect(shape(r)).toEqual(shape(plain)) + }) + + test("reindent + a source swapped inside the CTE the item reads from is reported", async () => { + const r = await twins( + "with a as (\n select customer_id, ssn\n from customers\n)\nselect customer_id,\n ssn\nfrom a", + "with a as (\n select customer_id, ssn\n from spouses\n)\nselect customer_id,\n ssn\nfrom a", + "- from customers\n+ from spouses\n- ssn\n+ ssn\n", + ) + expect(r.critical).toBe(true) + }) + + test("control: a pure reindent over identical sources stays suppressed", async () => { + for (const from of ["from customers", "from customers c\njoin orders o on o.id = c.id", "from {{ ref('customers') }}"]) { + const r = await twins(`select customer_id,\n ssn\n${from}`, `select customer_id,\n ssn\n${from}`, "- ssn\n+ ssn\n") + expect(r.pii).toEqual([]) + expect(r.verdict).toBe("APPROVE") + } + }) + + test("control: keyword case and spacing in the FROM list are not a source change", async () => { + const r = await twins( + "select customer_id,\n ssn\nfrom customers c", + "select customer_id,\n ssn\nFROM Customers c", + "- ssn\n-from customers c\n+ ssn\n+FROM Customers c\n", + ) + expect(r.pii).toEqual([]) + }) + + test("control: the same CTE chain, reindented only, stays suppressed", async () => { + const sql = (pad: string) => `with a as (\n select customer_id, ssn\n from customers\n)\nselect customer_id,\n${pad}ssn\nfrom a` + const r = await twins(sql(" "), sql(" "), "- ssn\n+ ssn\n") + expect(r.pii).toEqual([]) + }) +}) + +describe("fix 2: a column merged by USING / NATURAL comes from every joined source", () => { + const headSql = (join: string) => `select\n ssn\nfrom customers c\n${join}` + const baseSql = "select c.ssn from customers c" + const both = (base: string, head: string) => + run({ base, head, diff: lines("-", base) + lines("+", head), reviewers: ["dbt_patterns", "pii_exposure"] }) + + for (const kind of ["full outer join", "right join", "left join", "inner join", "join"]) { + test(`${kind} ... using (ssn): one ref per source, and reported`, async () => { + const head = headSql(`${kind} contacts d using (ssn)`) + expect([...(RC.finalOutputs(head).raw.get("ssn") ?? [])].sort()).toEqual(["contacts.ssn", "customers.ssn"]) + const r = await both(baseSql, head) + expect(r.verdict).toBe("REQUEST_CHANGES") + expect(r.critical).toBe(true) + }) + } + + test("multi-column using (id, ssn)", async () => { + const head = headSql("full outer join contacts d using (id, ssn)") + expect([...(RC.finalOutputs(head).raw.get("ssn") ?? [])].sort()).toEqual(["contacts.ssn", "customers.ssn"]) + expect((await both(baseSql, head)).critical).toBe(true) + }) + + test("a column not in the using list keeps the existing resolution", () => { + const out = RC.finalOutputs("select\n email\nfrom customers c\nfull outer join contacts d using (ssn)") + expect([...(out.raw.get("email") ?? [])]).toEqual(["contacts|customers.email"]) + }) + + test("a qualified c.ssn beside a using join still resolves to customers only", async () => { + const head = "select\n c.ssn\nfrom customers c\nfull outer join contacts d using (ssn)" + expect([...(RC.finalOutputs(head).raw.get("ssn") ?? [])]).toEqual(["customers.ssn"]) + const r = await both(baseSql, head) + expect(r.critical).toBe(false) + }) + + test("natural join: every unqualified column comes from every source", async () => { + const head = headSql("natural full outer join contacts d") + expect([...(RC.finalOutputs(head).raw.get("ssn") ?? [])].sort()).toEqual(["contacts.ssn", "customers.ssn"]) + expect((await both(baseSql, head)).critical).toBe(true) + }) + + test("a base that already merged the same sources covers the head", () => { + const sql = headSql("full outer join contacts d using (ssn)") + const exposed = RC.finalOutputs(sql).raw.get("ssn")! + const head = RC.finalOutputs(sql.replace("\n ssn", "\n ssn")).raw.get("ssn")! + expect([...head].every((ref) => RC.refCovered(ref, exposed))).toBe(true) + }) + + test("control: d.ssn with an on join is reported", async () => { + const r = await both(baseSql, "select\n d.ssn\nfrom customers c\nfull outer join contacts d on c.id = d.id") + expect(r.verdict).toBe("REQUEST_CHANGES") + expect(r.critical).toBe(true) + }) +})