Skip to content

Commit ed6f247

Browse files
anandgupta42claude
andcommitted
fix: [#827] address consensus review — apply resolver to all 5 finops handlers + formatter fix + case-insensitivity
Multi-model consensus review of the original commit identified four in-scope issues this commit addresses: 1. finops_expensive_queries tool schema not updated (5/6 reviewer consensus) The handler in credit-analyzer.ts was already wired to the resolver, but the tool schema still required `warehouse` and the description claimed "Snowflake only" — leaving the auto-pick fallback unreachable for that tool. Schema and description updated to match the other two tools. 2. Formatter field-name mismatch in finops-query-history.ts and finops-expensive-queries.ts (2/6 independent catches, both MAJOR) The formatters read `summary.avg_execution_time` / `q.execution_time`, but the native handler returns `_sec`-suffixed keys (`avg_execution_time_sec` and per-row `execution_time_sec`). Pre-existing silent data loss: average time line never rendered, per-query exec time always "-". Auto-pick from the prior commit routes more users through these formatters, expanding the impact. Both formatters updated to read the correct keys. 3. Other finops handlers had the same dead-end pattern (Gemini CRITICAL, Kimi MAJOR). warehouse-advisor.ts (adviseWarehouse), unused-resources.ts (findUnusedResources), role-access.ts (queryGrants, queryRoleHierarchy, queryUserRoles) all rewired to use resolveFinopsWarehouse. Their tool schemas (finops-warehouse-advice, finops-unused-resources, three tools in finops-role-access) made warehouse optional. Type signatures in native/types.ts updated to match. role-access uses a SNOWFLAKE_ONLY_TYPES const for queryRoleHierarchy and queryUserRoles. 4. Case-sensitivity bug (DeepSeek unique catch). The driver lookup in registry.ts uses toLowerCase() via DRIVER_MAP, so configs with `type: "Snowflake"` (capitalized) get a working driver — but the resolver's case-sensitive supportedTypes.includes(match.type) failed them with a spurious "not available for Snowflake" error. Resolver now normalizes type via toLowerCase() at every comparison, and the returned `type` field is the lowercased form so downstream SQL-template selectors continue to compare against "snowflake" / "bigquery" / "databricks". Plus two cleanup items from the review: - Removed unused `sanitizeBqRegion` import from query-history.ts (Claude NIT) - Added a code comment in the resolver documenting the intentional warehouse-name disclosure in error messages (resolves the disputed security concern with the synthesis's rationale) Test changes - Added 3 new test cases pinning case-insensitive type matching, including mixed-case (`type: "Snowflake"`), uppercase (`type: "SNOWFLAKE"`), and auto-pick filtering with mixed-case types. - Updated two assertions in schema-finops-dbt.test.ts to match the new "not configured" error message (replacing the less-accurate old "not available for X" — the warehouse never existed, regardless of type). Validation - `tsgo --noEmit`: pass, zero errors. - `bun test test/altimate/finops-*`: 124 pass / 0 fail / 67 skip (credential-gated). - `bun test test/altimate/tool-error-propagation.test.ts test/altimate/simulation-suite.test.ts`: 854 pass / 0 fail. - Marker check: pass — no upstream-shared files touched. Expected telemetry impact unchanged from prior commit: error rate on finops_* tools should drop to operational baseline. With this commit, all five finops handlers benefit, not just the two from the original PR. The formatter fix recovers two display values that have been silently broken for all users since these tools shipped. Closes review feedback from PR #828 multi-model consensus. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent c4ab025 commit ed6f247

13 files changed

Lines changed: 222 additions & 71 deletions

‎packages/opencode/src/altimate/native/finops/query-history.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
*/
66

77
import * as Registry from "../connections/registry"
8-
import { bqRegionFor, interpolateBqRegion, sanitizeBqRegion } from "./bq-utils"
8+
import { bqRegionFor, interpolateBqRegion } from "./bq-utils"
99
import { resolveFinopsWarehouse } from "./warehouse-resolver"
1010
import type { QueryHistoryParams, QueryHistoryResult } from "../types"
1111

‎packages/opencode/src/altimate/native/finops/role-access.ts‎

Lines changed: 39 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import * as Registry from "../connections/registry"
88
import { bqRegionFor, interpolateBqRegion } from "./bq-utils"
9+
import { resolveFinopsWarehouse } from "./warehouse-resolver"
910
import type {
1011
RoleGrantsParams,
1112
RoleGrantsResult,
@@ -107,11 +108,8 @@ LIMIT ?
107108
// Helpers
108109
// ---------------------------------------------------------------------------
109110

110-
function getWhType(warehouse: string): string {
111-
const warehouses = Registry.list().warehouses
112-
const wh = warehouses.find((w) => w.name === warehouse)
113-
return wh?.type || "unknown"
114-
}
111+
const GRANTS_SUPPORTED_TYPES = ["snowflake", "bigquery", "databricks"] as const
112+
const SNOWFLAKE_ONLY_TYPES = ["snowflake"] as const
115113

116114
function rowsToRecords(result: { columns: string[]; rows: any[][] }): Record<string, unknown>[] {
117115
return result.rows.map((row) => {
@@ -164,9 +162,25 @@ function buildGrantsSql(
164162
// ---------------------------------------------------------------------------
165163

166164
export async function queryGrants(params: RoleGrantsParams): Promise<RoleGrantsResult> {
167-
const whType = getWhType(params.warehouse)
168165
const limit = params.limit ?? 100
169-
const bqRegion = whType === "bigquery" ? bqRegionFor(params.warehouse) : undefined
166+
167+
const resolved = resolveFinopsWarehouse({
168+
requested: params.warehouse,
169+
supportedTypes: GRANTS_SUPPORTED_TYPES,
170+
operationName: "Role/access queries",
171+
})
172+
if (resolved.kind === "error") {
173+
return {
174+
success: false,
175+
grants: [],
176+
grant_count: 0,
177+
privilege_summary: {},
178+
error: resolved.error,
179+
}
180+
}
181+
182+
const { warehouse: whName, type: whType } = resolved
183+
const bqRegion = whType === "bigquery" ? bqRegionFor(whName) : undefined
170184

171185
const built = buildGrantsSql(whType, params.role, params.object_name, limit, bqRegion)
172186
if (!built) {
@@ -175,12 +189,12 @@ export async function queryGrants(params: RoleGrantsParams): Promise<RoleGrantsR
175189
grants: [],
176190
grant_count: 0,
177191
privilege_summary: {},
178-
error: `Role/access queries are not available for ${whType} warehouses.`,
192+
error: `Internal error: grants SQL template missing for ${whType}.`,
179193
}
180194
}
181195

182196
try {
183-
const connector = await Registry.get(params.warehouse)
197+
const connector = await Registry.get(whName)
184198
const result = await connector.execute(built.sql, limit, built.binds)
185199
const grants = rowsToRecords(result)
186200

@@ -208,20 +222,22 @@ export async function queryGrants(params: RoleGrantsParams): Promise<RoleGrantsR
208222
}
209223

210224
export async function queryRoleHierarchy(params: RoleHierarchyParams): Promise<RoleHierarchyResult> {
211-
const whType = getWhType(params.warehouse)
212-
if (whType !== "snowflake") {
225+
const resolved = resolveFinopsWarehouse({
226+
requested: params.warehouse,
227+
supportedTypes: SNOWFLAKE_ONLY_TYPES,
228+
operationName: "Role hierarchy",
229+
})
230+
if (resolved.kind === "error") {
213231
return {
214232
success: false,
215233
hierarchy: [],
216234
role_count: 0,
217-
error: `Role hierarchy is not available for ${whType}. ` +
218-
`Use ${whType === "bigquery" ? "BigQuery IAM" : whType === "databricks" ? "Databricks Unity Catalog" : whType} ` +
219-
`for access management.`,
235+
error: resolved.error,
220236
}
221237
}
222238

223239
try {
224-
const connector = await Registry.get(params.warehouse)
240+
const connector = await Registry.get(resolved.warehouse)
225241
const result = await connector.execute(SNOWFLAKE_ROLE_HIERARCHY_SQL, 10000)
226242
const hierarchy = rowsToRecords(result)
227243

@@ -247,20 +263,22 @@ export async function queryRoleHierarchy(params: RoleHierarchyParams): Promise<R
247263
}
248264

249265
export async function queryUserRoles(params: UserRolesParams): Promise<UserRolesResult> {
250-
const whType = getWhType(params.warehouse)
251-
if (whType !== "snowflake") {
266+
const resolved = resolveFinopsWarehouse({
267+
requested: params.warehouse,
268+
supportedTypes: SNOWFLAKE_ONLY_TYPES,
269+
operationName: "User role queries",
270+
})
271+
if (resolved.kind === "error") {
252272
return {
253273
success: false,
254274
assignments: [],
255275
assignment_count: 0,
256-
error: `User role queries are not available for ${whType}. ` +
257-
`Use ${whType === "bigquery" ? "BigQuery IAM" : whType === "databricks" ? "Databricks Unity Catalog" : whType} ` +
258-
`for access management.`,
276+
error: resolved.error,
259277
}
260278
}
261279

262280
try {
263-
const connector = await Registry.get(params.warehouse)
281+
const connector = await Registry.get(resolved.warehouse)
264282
const limit = params.limit ?? 100
265283
const binds: any[] = []
266284
const userF = params.user ? (binds.push(params.user), "AND grantee_name = ?") : ""

‎packages/opencode/src/altimate/native/finops/unused-resources.ts‎

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,14 @@
66

77
import * as Registry from "../connections/registry"
88
import { bqRegionFor, interpolateBqRegion } from "./bq-utils"
9+
import { resolveFinopsWarehouse } from "./warehouse-resolver"
910
import type {
1011
UnusedResourcesParams,
1112
UnusedResourcesResult,
1213
} from "../types"
1314

15+
const UNUSED_RESOURCES_SUPPORTED_TYPES = ["snowflake", "bigquery", "databricks"] as const
16+
1417
// ---------------------------------------------------------------------------
1518
// Snowflake SQL templates
1619
// ---------------------------------------------------------------------------
@@ -121,12 +124,6 @@ LIMIT ?
121124
// Helpers
122125
// ---------------------------------------------------------------------------
123126

124-
function getWhType(warehouse: string): string {
125-
const warehouses = Registry.list().warehouses
126-
const wh = warehouses.find((w) => w.name === warehouse)
127-
return wh?.type || "unknown"
128-
}
129-
130127
function rowsToRecords(result: { columns: string[]; rows: any[][] }): Record<string, unknown>[] {
131128
return result.rows.map((row) => {
132129
const obj: Record<string, unknown> = {}
@@ -142,23 +139,29 @@ function rowsToRecords(result: { columns: string[]; rows: any[][] }): Record<str
142139
// ---------------------------------------------------------------------------
143140

144141
export async function findUnusedResources(params: UnusedResourcesParams): Promise<UnusedResourcesResult> {
145-
const whType = getWhType(params.warehouse)
146142
const days = params.days ?? 30
147143
const limit = params.limit ?? 50
148144

149-
if (!["snowflake", "bigquery", "databricks"].includes(whType)) {
145+
const resolved = resolveFinopsWarehouse({
146+
requested: params.warehouse,
147+
supportedTypes: UNUSED_RESOURCES_SUPPORTED_TYPES,
148+
operationName: "Unused resource detection",
149+
})
150+
if (resolved.kind === "error") {
150151
return {
151152
success: false,
152153
unused_tables: [],
153154
idle_warehouses: [],
154155
summary: {},
155156
days_analyzed: days,
156-
error: `Unused resource detection is not available for ${whType} warehouses.`,
157+
error: resolved.error,
157158
}
158159
}
159160

161+
const { warehouse: whName, type: whType } = resolved
162+
160163
try {
161-
const connector = await Registry.get(params.warehouse)
164+
const connector = await Registry.get(whName)
162165
let unusedTables: Record<string, unknown>[] = []
163166
let idleWarehouses: Record<string, unknown>[] = []
164167
const errors: string[] = []
@@ -187,7 +190,7 @@ export async function findUnusedResources(params: UnusedResourcesParams): Promis
187190
}
188191
} else if (whType === "bigquery") {
189192
try {
190-
const sql = interpolateBqRegion(BIGQUERY_UNUSED_TABLES_SQL, bqRegionFor(params.warehouse))
193+
const sql = interpolateBqRegion(BIGQUERY_UNUSED_TABLES_SQL, bqRegionFor(whName))
191194
const result = await connector.execute(sql, limit, [days, limit])
192195
unusedTables = rowsToRecords(result)
193196
} catch (e) {

‎packages/opencode/src/altimate/native/finops/warehouse-advisor.ts‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import * as Registry from "../connections/registry"
88
import { bqRegionFor, interpolateBqRegion } from "./bq-utils"
9+
import { resolveFinopsWarehouse } from "./warehouse-resolver"
910
import type {
1011
WarehouseAdvisorParams,
1112
WarehouseAdvisorResult,
@@ -122,11 +123,7 @@ const SIZE_ORDER = ["X-Small", "Small", "Medium", "Large", "X-Large", "2X-Large"
122123
// Helpers
123124
// ---------------------------------------------------------------------------
124125

125-
function getWhType(warehouse: string): string {
126-
const warehouses = Registry.list().warehouses
127-
const wh = warehouses.find((w) => w.name === warehouse)
128-
return wh?.type || "unknown"
129-
}
126+
const ADVISOR_SUPPORTED_TYPES = ["snowflake", "bigquery", "databricks"] as const
130127

131128
function buildLoadSql(whType: string, days: number, bqRegion?: unknown): string | null {
132129
if (whType === "snowflake") return SNOWFLAKE_LOAD_SQL.replace("{days}", String(days))
@@ -220,9 +217,26 @@ function generateSizingRecommendations(
220217
// ---------------------------------------------------------------------------
221218

222219
export async function adviseWarehouse(params: WarehouseAdvisorParams): Promise<WarehouseAdvisorResult> {
223-
const whType = getWhType(params.warehouse)
224220
const days = params.days ?? 14
225-
const bqRegion = whType === "bigquery" ? bqRegionFor(params.warehouse) : undefined
221+
222+
const resolved = resolveFinopsWarehouse({
223+
requested: params.warehouse,
224+
supportedTypes: ADVISOR_SUPPORTED_TYPES,
225+
operationName: "Warehouse sizing advice",
226+
})
227+
if (resolved.kind === "error") {
228+
return {
229+
success: false,
230+
warehouse_load: [],
231+
warehouse_performance: [],
232+
recommendations: [],
233+
days_analyzed: days,
234+
error: resolved.error,
235+
}
236+
}
237+
238+
const { warehouse: whName, type: whType } = resolved
239+
const bqRegion = whType === "bigquery" ? bqRegionFor(whName) : undefined
226240

227241
const loadSql = buildLoadSql(whType, days, bqRegion)
228242
const sizingSql = buildSizingSql(whType, days, bqRegion)
@@ -234,12 +248,12 @@ export async function adviseWarehouse(params: WarehouseAdvisorParams): Promise<W
234248
warehouse_performance: [],
235249
recommendations: [],
236250
days_analyzed: days,
237-
error: `Warehouse sizing advice is not available for ${whType} warehouses.`,
251+
error: `Internal error: advisor SQL templates missing for ${whType}.`,
238252
}
239253
}
240254

241255
try {
242-
const connector = await Registry.get(params.warehouse)
256+
const connector = await Registry.get(whName)
243257

244258
// Run load and sizing queries in parallel
245259
const [loadResult, sizingResult] = await Promise.all([

‎packages/opencode/src/altimate/native/finops/warehouse-resolver.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,10 @@ export function resolveFinopsWarehouse(opts: ResolveOptions): FinopsWarehouseRes
5959
if (requested && requested.trim() !== "") {
6060
const match = all.find((w) => w.name === requested)
6161
if (!match) {
62+
// Error messages enumerate configured warehouse names so the LLM can
63+
// self-correct. This is intentional — names are already accessible via
64+
// the warehouse_list tool, so this is not new information disclosure;
65+
// it just shortens the recovery path.
6266
const availableNames = all.map((w) => w.name).join(", ")
6367
return {
6468
kind: "error",
@@ -68,8 +72,14 @@ export function resolveFinopsWarehouse(opts: ResolveOptions): FinopsWarehouseRes
6872
`Pass one of those as the 'warehouse' parameter, or omit it to use the default.`,
6973
}
7074
}
71-
if (!supportedTypes.includes(match.type)) {
72-
const compatible = all.filter((w) => supportedTypes.includes(w.type)).map((w) => w.name)
75+
// Driver types are case-insensitive (DRIVER_MAP in registry.ts uses
76+
// toLowerCase()). Normalize here so a config with `type: "Snowflake"`
77+
// resolves the same as `type: "snowflake"`.
78+
const matchTypeLower = match.type.toLowerCase()
79+
if (!supportedTypes.includes(matchTypeLower)) {
80+
const compatible = all
81+
.filter((w) => supportedTypes.includes(w.type.toLowerCase()))
82+
.map((w) => w.name)
7383
const hint =
7484
compatible.length > 0
7585
? `Try one of: ${compatible.join(", ")}.`
@@ -79,11 +89,16 @@ export function resolveFinopsWarehouse(opts: ResolveOptions): FinopsWarehouseRes
7989
error: `${operationName} is not available for ${match.type} warehouses. ${hint}`,
8090
}
8191
}
82-
return { kind: "ok", warehouse: match.name, type: match.type, autoPicked: false }
92+
return { kind: "ok", warehouse: match.name, type: matchTypeLower, autoPicked: false }
8393
}
8494

8595
// No requested warehouse — auto-pick first compatible.
86-
const compatible = all.find((w) => supportedTypes.includes(w.type))
96+
//
97+
// Order is whatever Registry.list() returns, which follows config-load order
98+
// (global file → local file → env vars). Deterministic per machine but may
99+
// vary across machines for the same user. Matches the existing sql.explain
100+
// fallback pattern in connections/register.ts.
101+
const compatible = all.find((w) => supportedTypes.includes(w.type.toLowerCase()))
87102
if (!compatible) {
88103
const availableTypes = Array.from(new Set(all.map((w) => w.type))).join(", ") || "(none)"
89104
return {
@@ -94,5 +109,5 @@ export function resolveFinopsWarehouse(opts: ResolveOptions): FinopsWarehouseRes
94109
`Add a compatible warehouse with the warehouse_add tool.`,
95110
}
96111
}
97-
return { kind: "ok", warehouse: compatible.name, type: compatible.type, autoPicked: true }
112+
return { kind: "ok", warehouse: compatible.name, type: compatible.type.toLowerCase(), autoPicked: true }
98113
}

‎packages/opencode/src/altimate/native/types.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -578,7 +578,8 @@ export interface ExpensiveQueriesResult {
578578
// --- FinOps: Warehouse Advisor ---
579579

580580
export interface WarehouseAdvisorParams {
581-
warehouse: string
581+
/** Warehouse connection name. If omitted, the first compatible warehouse is auto-picked. */
582+
warehouse?: string
582583
days?: number
583584
}
584585

@@ -594,7 +595,8 @@ export interface WarehouseAdvisorResult {
594595
// --- FinOps: Unused Resources ---
595596

596597
export interface UnusedResourcesParams {
597-
warehouse: string
598+
/** Warehouse connection name. If omitted, the first compatible warehouse is auto-picked. */
599+
warehouse?: string
598600
days?: number
599601
limit?: number
600602
}
@@ -611,7 +613,8 @@ export interface UnusedResourcesResult {
611613
// --- FinOps: Role & Access ---
612614

613615
export interface RoleGrantsParams {
614-
warehouse: string
616+
/** Warehouse connection name. If omitted, the first compatible warehouse is auto-picked. */
617+
warehouse?: string
615618
role?: string
616619
object_name?: string
617620
limit?: number
@@ -626,7 +629,8 @@ export interface RoleGrantsResult {
626629
}
627630

628631
export interface RoleHierarchyParams {
629-
warehouse: string
632+
/** Warehouse connection name. If omitted, the first compatible (Snowflake) warehouse is auto-picked. */
633+
warehouse?: string
630634
}
631635

632636
export interface RoleHierarchyResult {
@@ -637,7 +641,8 @@ export interface RoleHierarchyResult {
637641
}
638642

639643
export interface UserRolesParams {
640-
warehouse: string
644+
/** Warehouse connection name. If omitted, the first compatible (Snowflake) warehouse is auto-picked. */
645+
warehouse?: string
641646
user?: string
642647
limit?: number
643648
}

0 commit comments

Comments
 (0)