Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
b93527a
feat(review): let the AI lane see whole PRs and the dbt parents of wh…
RaghwendraSingh Nov 16, 2026
9344429
fix(review): honour `macro-paths` that point outside the dbt project …
RaghwendraSingh Nov 16, 2026
930dc28
feat(review): give every finding a stable `rule` id
RaghwendraSingh Nov 16, 2026
bf35d1c
feat(review): per-rule posting tiers (inline, summary, off)
RaghwendraSingh Nov 16, 2026
23d6b8b
feat(review): mark findings on lines the PR did not add as pre-existing
RaghwendraSingh Nov 16, 2026
70cbd33
feat(review): cap inline comments and lay the summary out by where fi…
RaghwendraSingh Nov 16, 2026
60dd942
feat(review): list every changed file the review did not look at, wit…
RaghwendraSingh Nov 16, 2026
a21fa58
fix(review): keep the folder-config hint for moved files in the ledger
RaghwendraSingh Nov 16, 2026
3db3aae
feat(review): cap rendered bodies, quote the matched line, post sugge…
RaghwendraSingh Nov 16, 2026
17a261a
feat(review): record tokens, cost and calls for the AI review lane
RaghwendraSingh Nov 16, 2026
82d1274
feat(review): anchor rule findings to the diff line they matched
RaghwendraSingh Nov 16, 2026
7026b53
fix(review): keep `self-join` and `join-case-folded-one-side` at summ…
RaghwendraSingh Nov 16, 2026
41e0a36
feat(review): record undecidable equivalence in the coverage ledger
RaghwendraSingh Nov 16, 2026
b97c982
fix(review): apply held-out per-rule judging to two rule tiers
RaghwendraSingh Nov 16, 2026
a7cdc94
fix(review): anchor `incremental-filter-created-only` to its filter line
RaghwendraSingh Nov 16, 2026
867e69b
fix(review): fold spacing and keyword case in `case-duplicate-when`
RaghwendraSingh Nov 16, 2026
0aa6183
fix(review): see `IGNORE NULLS ORDER BY` in calls, and accept DuckDB'…
RaghwendraSingh Nov 16, 2026
f21544c
fix(review): recognise more temporary-code phrasing in `temporary-cod…
RaghwendraSingh Nov 16, 2026
d18d654
fix(review): gate `microbatch-granularity-mismatch` on the adapter
RaghwendraSingh Nov 16, 2026
6087084
fix(review): read output columns through `select * from <cte>`
RaghwendraSingh Nov 16, 2026
eb08584
fix(review): anchor core check issues on Jinja models by compiled lin…
RaghwendraSingh Nov 16, 2026
39ecc53
fix(review): anchor removed-column findings where the column was removed
RaghwendraSingh Nov 16, 2026
26aaaba
fix(review): anchor `macro-param-shifted` on the changed signature line
RaghwendraSingh Nov 16, 2026
18b0654
fix(review): anchor `non-deterministic-dedup` on the line that orders…
RaghwendraSingh Nov 16, 2026
decddd7
fix(review): raise `removed-final-layer-columns` to warning
RaghwendraSingh Nov 17, 2026
b07fb67
fix(review): keep rules whose tier depends on the judging sample at s…
RaghwendraSingh Nov 17, 2026
fa667b7
fix(review): address review comments: UNION output names, package par…
RaghwendraSingh Nov 20, 2026
4038522
fix(review): address review feedback: full summary on inline fallback…
RaghwendraSingh Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion packages/opencode/src/altimate/review/adapter-capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ export interface AdapterCapability {
* leaves no table during the build. Undefined = not established.
*/
contractTableReplaceAtomic?: boolean
/**
* A microbatch model's `batch_size` must equal its `partition_by`
* granularity, or the run fails. Undefined = the adapter has no such rule.
*/
microbatchBatchSizeMatchesPartition?: boolean
/** Documentation backing the entries above. */
sources: string[]
}
Expand Down Expand Up @@ -61,7 +66,12 @@ export const ADAPTER_CAPABILITIES: Record<string, AdapterCapability> = {
},
bigquery: {
integerDivisionTruncates: false,
sources: ["https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#arithmetic_operators"],
microbatchBatchSizeMatchesPartition: true,
sources: [
"https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#arithmetic_operators",
"https://docs.getdbt.com/docs/build/incremental-microbatch",
"https://github.com/dbt-labs/dbt-adapters/blob/main/dbt-bigquery/src/dbt/include/bigquery/macros/materializations/incremental_strategy/microbatch.sql",
],
},
databricks: {
integerDivisionTruncates: false,
Expand Down
262 changes: 229 additions & 33 deletions packages/opencode/src/altimate/review/ai-review.ts

Large diffs are not rendered by default.

23 changes: 22 additions & 1 deletion packages/opencode/src/altimate/review/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { promises as fs } from "node:fs"
import YAML from "yaml"
import { createHash } from "node:crypto"
import { Rubric, DEFAULT_RUBRIC } from "./rubric"
import { ReviewMode } from "./verdict"
import { ReviewMode, DEFAULT_POSTING_POLICY } from "./verdict"
import { Severity } from "./finding"

/**
Expand Down Expand Up @@ -77,6 +77,27 @@ export const ReviewConfig = z.object({
.default({ enabled: false, warehouse: "" }),
/** Rubric overrides, deep-merged onto DEFAULT_RUBRIC. */
rubric: Rubric.partial().default({}),
/**
* Per-rule posting policy, keyed by finding `rule` id (`tool:rule`) or a
* `tool:*` glob: `inline` posts on the diff, `summary` keeps it to the
* summary comment, `off` drops it. Overrides the shipped defaults in
* rule-tiers.ts. Read from the base branch, so a PR cannot relax it.
* Engine rules that decide the verdict can be turned off only by exact id.
*/
rules: z.record(z.string(), z.enum(["inline", "summary", "off"])).default({}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Rule keys are not validated, so a typo in rules: is accepted and silently has no effect. Constrain keys to the tool:rule or tool:* shape so a malformed key fails at config load.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/review/config.ts, line 87:

<comment>Rule keys are not validated, so a typo in `rules:` is accepted and silently has no effect. Constrain keys to the `tool:rule` or `tool:*` shape so a malformed key fails at config load.</comment>

<file context>
@@ -77,6 +77,27 @@ export const ReviewConfig = z.object({
+   * rule-tiers.ts. Read from the base branch, so a PR cannot relax it.
+   * Engine rules that decide the verdict can be turned off only by exact id.
+   */
+  rules: z.record(z.string(), z.enum(["inline", "summary", "off"])).default({}),
+  /**
+   * How findings reach the PR: `inlineBudget` caps new inline comments per run
</file context>
Suggested change
rules: z.record(z.string(), z.enum(["inline", "summary", "off"])).default({}),
rules: z.record(z.string().regex(/^[\w.-]+:(\*|[\w-]+)$/), z.enum(["inline", "summary", "off"])).default({}),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: nit. Unknown keys are harmless no-ops, so we left validation out of this PR.

/**
* How findings reach the PR: `inlineBudget` caps new inline comments per run
* (the rest stay in the summary), `inlineSeverityFloor` keeps lower
* severities out of inline comments, and `silentWhenClean` posts nothing on
* a run with no findings and nothing to report about coverage.
*/
posting: z
.object({
inlineBudget: z.number().int().min(0).default(DEFAULT_POSTING_POLICY.inlineBudget),
inlineSeverityFloor: Severity.default(DEFAULT_POSTING_POLICY.inlineSeverityFloor),
silentWhenClean: z.boolean().default(DEFAULT_POSTING_POLICY.silentWhenClean),
})
.default(() => ({ ...DEFAULT_POSTING_POLICY })),
/** Extra path suffixes to exclude from review. */
exclude: z.array(z.string()).default([]),
/**
Expand Down
53 changes: 36 additions & 17 deletions packages/opencode/src/altimate/review/dbt-patterns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ const detectClock: Detector = (c) => {
file: c.file.path,
model: c.model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "clock_in_transform", lines: hits.slice(0, 3) } },
evidence: { tool: "dbt-patterns", result: { rule: "clock_in_transform", line: hits[0], lines: hits.slice(0, 3) } },
ruleKey: "idempotency:clock",
})
}
Expand Down Expand Up @@ -240,7 +240,7 @@ const detectFanout: Detector = (c) => {
confidence: "high",
evidence: {
tool: "dbt-patterns",
result: { rule: "fanout_join", joins: newJoins.map((j) => j.trim()).slice(0, 2) },
result: { rule: "fanout_join", line: newJoins[0], joins: newJoins.map((j) => j.trim()).slice(0, 2) },
},
ruleKey: "fanout:join-before-agg",
})
Expand Down Expand Up @@ -293,18 +293,19 @@ function addedLineNumbers(diff: string | undefined): Set<number> | undefined {
* only when the diff carries no hunk headers, and then only for added lines
* that themselves hold window syntax).
*/
function dedupWindows(c: Ctx): Array<{ spec: string; text: string }> {
function dedupWindows(c: Ctx): Array<{ spec: string; text: string; line: string }> {
// Comments blanked with newlines kept, so offsets map to head line numbers.
const sql = c.newSql.replace(/\/\*[\s\S]*?\*\/|--[^\n]*|\{#[\s\S]*?#\}/g, (m) => m.replace(/[^\n]/g, " "))
const lineAt = (offset: number) => sql.slice(0, offset).split("\n").length
const headLines = c.newSql.split("\n")
const addedLines = addedLineNumbers(c.file.diff)
// Text fallback (diff without hunk headers): only added lines that are part
// of a window spec can touch one; a bare identifier elsewhere never does.
const squash = (t: string) => t.replace(/\s+/g, " ").trim()
const added = c.added
.map((l) => squash(stripComments(l)))
.filter((l) => l.length >= 3 && /\b(row_number|over|partition\s+by|order\s+by)\b/i.test(l))
const out: Array<{ spec: string; text: string }> = []
.map((raw) => ({ raw, l: squash(stripComments(raw)) }))
.filter(({ l }) => l.length >= 3 && /\b(row_number|over|partition\s+by|order\s+by)\b/i.test(l))
const out: Array<{ spec: string; text: string; line: string }> = []
for (const m of sql.matchAll(/row_number\s*\(\s*\)\s*over\s*\(/gi)) {
const open = m.index! + m[0].length - 1
let depth = 0
Expand All @@ -318,11 +319,22 @@ function dedupWindows(c: Ctx): Array<{ spec: string; text: string }> {
}
if (close < 0) continue
const text = sql.slice(m.index!, close + 1)
const touched = addedLines
? [...addedLines].some((n) => n >= lineAt(m.index!) && n <= lineAt(close))
: added.some((l) => squash(text).includes(l) || l.includes(squash(text)))
if (!touched) continue
out.push({ spec: sql.slice(open + 1, close).replace(/\s+/g, " ").trim(), text: text.replace(/\s+/g, " ") })
let line: string | undefined
if (addedLines) {
// The added line that opens the window, else the first added line inside it.
const first = lineAt(m.index!)
const last = lineAt(close)
const touched = [...addedLines].filter((n) => n >= first && n <= last).sort((a, b) => a - b)
if (!touched.length) continue
line = headLines[(touched.includes(first) ? first : touched[0]) - 1] ?? ""
} else {
const inside = added.filter(({ l }) => squash(text).includes(l) || l.includes(squash(text)))
if (!inside.length) continue
const end = sql.indexOf("\n", m.index!)
const opener = sql.slice(sql.lastIndexOf("\n", m.index!) + 1, end < 0 ? undefined : end).trim()
line = (added.find(({ l }) => l === squash(opener)) ?? inside[0]).raw
}
out.push({ spec: sql.slice(open + 1, close).replace(/\s+/g, " ").trim(), text: text.replace(/\s+/g, " "), line })
}
return out
}
Expand All @@ -345,7 +357,7 @@ const detectDedupTie: Detector = (c) => {
file: c.file.path,
model: c.model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "dedup_no_tiebreaker", line: hit.text } },
evidence: { tool: "dbt-patterns", result: { rule: "dedup_no_tiebreaker", line: hit.line, window: hit.text } },
ruleKey: "dedup:no-tiebreaker",
})
}
Expand Down Expand Up @@ -375,7 +387,7 @@ const detectDedupLoadTimestamp: Detector = (c) => {
file: c.file.path,
model: c.model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "dedup_load_timestamp_only", line: w.text } },
evidence: { tool: "dbt-patterns", result: { rule: "dedup_load_timestamp_only", line: w.line, window: w.text } },
ruleKey: "dedup:load-timestamp-only",
})
}
Expand Down Expand Up @@ -443,6 +455,7 @@ const detectCountDistinct: Detector = (c) => {
const addedDistinct = c.added.some(hasCountDistinct)
const removedPlain = c.removed.some(hasPlainCount)
if (!((removedDistinct && addedPlain) || (addedDistinct && removedPlain))) return null
const line = c.added.find(removedDistinct && addedPlain ? hasPlainCount : hasCountDistinct)
return makeFinding({
severity: "warning",
category: "sql_correctness",
Expand All @@ -453,7 +466,7 @@ const detectCountDistinct: Detector = (c) => {
file: c.file.path,
model: c.model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "count_distinct_change" } },
evidence: { tool: "dbt-patterns", result: { rule: "count_distinct_change", line } },
ruleKey: "sql_correctness:count-distinct",
})
}
Expand Down Expand Up @@ -722,13 +735,15 @@ const detectCaseNoElse: Detector = (c) => {
(m) => !/\belse\b/i.test(m[0]) && !NULL_CONSUMING_CALL.test(joined.slice(0, m.index)),
)
if (!bare) return null
const head = bare[0].split("\n")[0].trim()
return pattern(
c,
"sql_correctness",
"suggestion",
"case-no-else",
"CASE without ELSE returns NULL for unmatched rows",
"A `CASE` expression with no `ELSE` silently yields NULL for any unmatched row, which can skew downstream metrics. Add an explicit `ELSE`.",
c.added.find((l) => stripComments(l).includes(head)),
)
}

Expand Down Expand Up @@ -764,7 +779,8 @@ const detectNaturalJoin: Detector = (c) => {

// 38. Self-join: same ref()/source() appears 2+ times.
const detectSelfJoin: Detector = (c) => {
if (!addedHit(c, /\bjoin\b/i)) return null
const hit = addedHit(c, /\bjoin\b/i)
if (!hit) return null
// A self-join reads one relation twice in the same FROM … JOIN chain. The same ref in two
// CTEs, or in two UNION branches, is two separate reads, not a self-join.
const sql = stripComments(c.newSql).replace(/\{\{\s*(ref|source)\s*\(([^)]*)\)\s*\}\}/gi, (_, kind, args) =>
Expand All @@ -778,6 +794,7 @@ const detectSelfJoin: Detector = (c) => {
"self-join",
"self-join detected — verify it can't fan out",
"The same relation is joined to itself. Self-joins are easy to get wrong (missing grain predicate → fan-out). Confirm the join keys keep it one-to-one.",
hit,
)
}

Expand All @@ -802,7 +819,7 @@ const detectWindowNoPartition: Detector = (c) => {
const head = sql.slice(lineStart, open + 1).trim()
return changed.some((l) => l.includes(head)) && !/partition\s+by/i.test(sql.slice(open, end))
})
const hit = unpartitioned ? changed[0] : undefined
const hit = unpartitioned ? c.added.find((l) => stripComments(l).trim() === changed[0]) : undefined

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SUGGESTION]: Anchors to the first OVER ( line, not the unpartitioned one

changed[0] is the first added line that contains any over (, while unpartitioned may be true for a later clause. When a diff adds a partitioned window before an unpartitioned one, the finding anchors to the correctly partitioned line with a window function has no PARTITION BY message, and once dbt-patterns:window-no-partition is promoted to inline the comment is posted there. Have the matchAll predicate record the offending head (use find rather than some) and anchor that line.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up: low priority, tracked. The rule is off by default, so this is dormant. We'll anchor it to the offending OVER when we enable it.

if (!hit) return null
return pattern(
c,
Expand Down Expand Up @@ -903,13 +920,15 @@ const detectOffsetNoOrder: Detector = (c) => {
const detectMultiCountDistinct: Detector = (c) => {
const count = (stripComments(c.added.join("\n")).match(/count\s*\(\s*distinct/gi) || []).length
if (count < 2) return null
const hit = addedHit(c, /count\s*\(\s*distinct/i)
return pattern(
c,
"warehouse_cost",
"suggestion",
"multi-count-distinct",
`${count} COUNT(DISTINCT …) in one query is expensive`,
"Multiple `COUNT(DISTINCT …)` each need their own sort/hash; on large tables this is a major cost. Consider APPROX_COUNT_DISTINCT or pre-aggregation where exactness isn't required.",
hit,
)
}

Expand Down Expand Up @@ -998,7 +1017,7 @@ export function detectMacroPatterns(
file: file.path,
model,
confidence: "high",
evidence: { tool: "dbt-patterns", result: { rule: "macro-var-no-default", var: name } },
evidence: { tool: "dbt-patterns", result: { rule: "macro-var-no-default", var: name, line } },
ruleKey: `materialization:macro-var-no-default`,
}),
)
Expand Down
Loading
Loading