Skip to content

Commit 00738e9

Browse files
anandgupta42claude
andauthored
fix: [#827] finops_* 100% failure — add warehouse-resolver fallback (#828)
* fix: [#827] resolve finops_* 100% failure with warehouse-resolver fallback Telemetry (memory/telemetry-analysis-2026-05-21.md, 2,503 machines, 14 days) flagged `finops_analyze_credits` (8/8) and `finops_query_history` (1/1) as 100% broken. Every user who tried them hit a dead-end "Credit analysis is not available for unknown warehouses." error with no path forward. Unlike `sql.explain` (which auto-falls-back to `warehouses[0]`), the finops handlers had no resolution logic and returned an unhelpful error whenever the caller omitted the warehouse name, supplied an unknown one, or supplied one whose type wasn't supported. Changes - New shared helper `finops/warehouse-resolver.ts` with a 4-branch resolution contract (ok / not configured / unknown name / unsupported type) and actionable errors that name the available warehouses and suggest `warehouse_add` when nothing is configured. - `credit-analyzer.ts` (analyzeCredits, getExpensiveQueries) and `query-history.ts` (getQueryHistory) wired to the resolver. The dead `getWhType` helpers removed. - `warehouse` parameter made optional on the `finops_analyze_credits` and `finops_query_history` tool schemas; descriptions updated to document the auto-pick behaviour and the full supported-warehouse list. - `CreditAnalysisParams`, `ExpensiveQueriesParams`, `QueryHistoryParams` marked `warehouse?` to match the new optionality contract. - 12 new unit tests in `test/altimate/finops-warehouse-resolver.test.ts` pinning every resolution branch including empty-string and whitespace-only requested values. Expected impact - Error rate on `finops_analyze_credits` and `finops_query_history` drops from 100% to whatever the real operational failure rate is (warehouse unreachable, ACCOUNT_USAGE permission missing, etc.). The resolver no longer masks those as "unknown warehouse" — driver errors pass through with their original message. - Cost-audit wedge demo now works on any tenant with a Snowflake / BigQuery / Databricks warehouse configured, without the LLM needing to guess the exact warehouse name. Validation - `tsgo --noEmit`: pass, zero errors. - `bun test test/altimate/finops-*`: 37 pass / 0 fail (12 new + 25 existing). - `bun test test/altimate/finops-*-e2e.test.ts test/altimate/schema-finops-dbt.test.ts test/altimate/finops-role-access.test.ts`: 85 pass / 67 skip (credentials-gated) / 0 fail. - Marker check: pass — no upstream-shared files touched. Closes #827 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * 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]> * fix: [#827] address consensus review — test determinism + error consistency + formatter completeness Third-pass on PR #828 after follow-up code review. Three follow-ups in scope. 1. Test determinism (MINOR per reviewer) `test/altimate/schema-finops-dbt.test.ts` was reading the warehouse resolver's error message verbatim ("not configured") to assert the unknown-warehouse path. That message only appears when the registry has at least one warehouse configured — if the test ran in a fresh sandbox or hermetic CI, the resolver would return "...none are set up..." and the assertion would silently fail. Added a beforeAll / afterAll block that captures the prior registry state, pins a known two-warehouse config for the test, and restores afterwards. 2. Error stringification consistency (MINOR) The first PR commit upgraded most `catch (e) { error: String(e) }` to `e instanceof Error ? e.message : String(e)`, but role-access.ts was missed (three handlers). Normalized all three to match the credit-analyzer / query-history pattern — driver errors now surface as `"...message..."` rather than `"Error: ...message..."`. 3. Formatter completeness (NIT) `finops-query-history.ts` formatter surfaced only avg_execution_time even though the underlying handler emits total_execution_time_sec and error_count too. Added both: total exec time always shown; error count shown only when > 0 to avoid cluttering the typical 0-error case. Validation - `tsgo --noEmit`: pass. - `bun test test/altimate/schema-finops-dbt.test.ts test/altimate/finops-warehouse-resolver.test.ts test/altimate/finops-recommendations.test.ts`: 95 pass / 0 fail. - Marker check: pass (no upstream-shared files in these paths). Reviewer note - GPT-5.4 second-opinion was unavailable (OpenRouter credit exhaustion). Single-reviewer Claude analysis. Deferred to follow-up - Surface auto-picked warehouse name in handler success metadata (reviewer NIT — separate ROADMAP item already tracked). - Restore role-access BigQuery-IAM / Databricks-Unity hints lost in the resolver rewrite (reviewer NIT — would require per-operation `hint` field on `ResolveOptions`, separate enhancement). - Tool-level integration test for the auto-pick path (reviewer suggestion — requires Dispatcher mock scaffolding). Closes review feedback for PR #828 (third pass). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix: [#827] address re-review — finops_warehouse_advice formatter + last 2 String(e) Fourth pass on PR #828. Re-review found one MAJOR formatter bug missed by the previous formatter audit, plus the last two String(e) instances that the third pass left behind. 1. MAJOR — formatter field-name mismatch in finops-warehouse-advice Same class of bug as the one commit ed6f247 fixed for finops-query-history.ts and finops-expensive-queries.ts — the formatter read keys the handler never emits: - Performance summary: read `avg_execution_time`, `avg_queue_time`, `status`, `health`; handler emits `query_count`, `avg_time_sec`, `p95_time_sec`, `avg_bytes_scanned`, `total_credits`. - Load metrics: read `warehouse_size`, `avg_load`, `peak_load`, `utilization`; handler emits `avg_concurrency`, `avg_queue_load`, `peak_queue_load`, `sample_count`. Every value rendered as "-" regardless of input. Auto-pick from the prior commits expanded the user population hitting this formatter. Fix: rewrote both table headers and row loops to read the actual handler keys. Added inline comments pointing back at the previous instance of this bug pattern so the next reviewer doesn't have to discover it independently. 2. MINOR — null-guard on result.recommendations `result.recommendations.length` was read directly. If a future handler variance or partial success ever dropped the field, the tool throws a TypeError instead of returning a structured error. Coalesced to `[]`. Also defensive-defaulted warehouse_load and warehouse_performance for the same reason. 3. MINOR — last two String(e) call sites The third pass normalized role-access.ts but missed: - unused-resources.ts:234 - warehouse-advisor.ts:301 Both fixed in this commit. All five finops handlers now use the same `e instanceof Error ? e.message : String(e)` pattern, so driver errors no longer carry "Error:" prefixes inconsistently. Validation - `tsgo --noEmit`: pass. - `bun test test/altimate/finops-*.test.ts test/altimate/schema-finops-dbt.test.ts`: 95 pass / 0 fail / 67 skip (credential-gated). - Marker check: pass. Reviewer note - GPT-5.4 and Kimi K2.5 second-opinions did not produce output this round either — kilo CLI was preempted by other concurrent jobs on the same OpenRouter quota. Single-reviewer Claude analysis. Deferred to follow-up - Tool-level integration test for each formatter (would have caught all three formatter bugs at once — tracked as a separate quality bar enhancement). - warehouse_filter param silently ignored for BigQuery/Databricks (description already documents Snowflake-only; tracking as NIT). Closes review feedback for PR #828 (fourth pass). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix: [#827] address cubic P2 — trim requested warehouse name before matching Cubic flagged that valid warehouse names with leading/trailing whitespace were incorrectly reported as unknown. LLMs occasionally surface names with stray whitespace from prompt copy-paste or YAML/JSON serialization edge cases — without the trim, " prod_wh" reports as unknown even though "prod_wh" is configured. The trim is on the lookup key only; configured names are stored as-is. Added a 4-variant test that pins the contract (leading-only, trailing-only, both-sides, tabs+newlines) so a refactor can't silently drop the trim. 15/15 resolver tests pass; marker check clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 476d234 commit 00738e9

15 files changed

Lines changed: 779 additions & 126 deletions

‎packages/opencode/src/altimate/native/finops/credit-analyzer.ts‎

Lines changed: 50 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@
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
CreditAnalysisParams,
1112
CreditAnalysisResult,
1213
ExpensiveQueriesParams,
1314
ExpensiveQueriesResult,
1415
} from "../types"
1516

17+
const CREDIT_SUPPORTED_TYPES = ["snowflake", "bigquery", "databricks"] as const
18+
1619
// ---------------------------------------------------------------------------
1720
// Snowflake SQL templates
1821
// ---------------------------------------------------------------------------
@@ -185,12 +188,6 @@ LIMIT ?
185188
// Helpers
186189
// ---------------------------------------------------------------------------
187190

188-
function getWhType(warehouse: string): string {
189-
const warehouses = Registry.list().warehouses
190-
const wh = warehouses.find((w) => w.name === warehouse)
191-
return wh?.type || "unknown"
192-
}
193-
194191
function buildCreditUsageSql(
195192
whType: string, days: number, limit: number, warehouseFilter?: string, bqRegion?: unknown,
196193
): { sql: string; binds: any[] } | null {
@@ -302,14 +299,35 @@ function generateRecommendations(
302299
// ---------------------------------------------------------------------------
303300

304301
export async function analyzeCredits(params: CreditAnalysisParams): Promise<CreditAnalysisResult> {
305-
const whType = getWhType(params.warehouse)
306302
const days = params.days ?? 30
307303
const limit = params.limit ?? 50
308-
const bqRegion = whType === "bigquery" ? bqRegionFor(params.warehouse) : undefined
304+
305+
const resolved = resolveFinopsWarehouse({
306+
requested: params.warehouse,
307+
supportedTypes: CREDIT_SUPPORTED_TYPES,
308+
operationName: "Credit analysis",
309+
})
310+
if (resolved.kind === "error") {
311+
return {
312+
success: false,
313+
daily_usage: [],
314+
warehouse_summary: [],
315+
total_credits: 0,
316+
days_analyzed: days,
317+
recommendations: [],
318+
error: resolved.error,
319+
}
320+
}
321+
322+
const { warehouse: whName, type: whType } = resolved
323+
const bqRegion = whType === "bigquery" ? bqRegionFor(whName) : undefined
309324

310325
const dailyBuilt = buildCreditUsageSql(whType, days, limit, params.warehouse_filter, bqRegion)
311326
const summaryBuilt = buildCreditSummarySql(whType, days, bqRegion)
312327

328+
// CREDIT_SUPPORTED_TYPES is the contract with the resolver — if we got past
329+
// resolution, both builders are guaranteed to return non-null. Defensive null
330+
// check here only to satisfy the type system; not a real runtime path.
313331
if (!dailyBuilt || !summaryBuilt) {
314332
return {
315333
success: false,
@@ -318,12 +336,12 @@ export async function analyzeCredits(params: CreditAnalysisParams): Promise<Cred
318336
total_credits: 0,
319337
days_analyzed: days,
320338
recommendations: [],
321-
error: `Credit analysis is not available for ${whType} warehouses.`,
339+
error: `Internal error: credit SQL templates missing for ${whType}.`,
322340
}
323341
}
324342

325343
try {
326-
const connector = await Registry.get(params.warehouse)
344+
const connector = await Registry.get(whName)
327345
const dailyResult = await connector.execute(dailyBuilt.sql, limit, dailyBuilt.binds)
328346
const summaryResult = await connector.execute(summaryBuilt.sql, 1000, summaryBuilt.binds)
329347

@@ -348,16 +366,32 @@ export async function analyzeCredits(params: CreditAnalysisParams): Promise<Cred
348366
total_credits: 0,
349367
days_analyzed: days,
350368
recommendations: [],
351-
error: String(e),
369+
error: e instanceof Error ? e.message : String(e),
352370
}
353371
}
354372
}
355373

356374
export async function getExpensiveQueries(params: ExpensiveQueriesParams): Promise<ExpensiveQueriesResult> {
357-
const whType = getWhType(params.warehouse)
358375
const days = params.days ?? 7
359376
const limit = params.limit ?? 20
360-
const bqRegion = whType === "bigquery" ? bqRegionFor(params.warehouse) : undefined
377+
378+
const resolved = resolveFinopsWarehouse({
379+
requested: params.warehouse,
380+
supportedTypes: CREDIT_SUPPORTED_TYPES,
381+
operationName: "Expensive query analysis",
382+
})
383+
if (resolved.kind === "error") {
384+
return {
385+
success: false,
386+
queries: [],
387+
query_count: 0,
388+
days_analyzed: days,
389+
error: resolved.error,
390+
}
391+
}
392+
393+
const { warehouse: whName, type: whType } = resolved
394+
const bqRegion = whType === "bigquery" ? bqRegionFor(whName) : undefined
361395

362396
const built = buildExpensiveSql(whType, days, limit, bqRegion)
363397
if (!built) {
@@ -366,12 +400,12 @@ export async function getExpensiveQueries(params: ExpensiveQueriesParams): Promi
366400
queries: [],
367401
query_count: 0,
368402
days_analyzed: days,
369-
error: `Expensive query analysis is not available for ${whType} warehouses.`,
403+
error: `Internal error: expensive-query SQL template missing for ${whType}.`,
370404
}
371405
}
372406

373407
try {
374-
const connector = await Registry.get(params.warehouse)
408+
const connector = await Registry.get(whName)
375409
const result = await connector.execute(built.sql, limit, built.binds)
376410
const queries = rowsToRecords(result)
377411

@@ -387,7 +421,7 @@ export async function getExpensiveQueries(params: ExpensiveQueriesParams): Promi
387421
queries: [],
388422
query_count: 0,
389423
days_analyzed: days,
390-
error: String(e),
424+
error: e instanceof Error ? e.message : String(e),
391425
}
392426
}
393427
}

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

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,19 @@
55
*/
66

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

12+
const QUERY_HISTORY_SUPPORTED_TYPES = [
13+
"snowflake",
14+
"postgres",
15+
"postgresql",
16+
"bigquery",
17+
"databricks",
18+
"clickhouse",
19+
] as const
20+
1121
// ---------------------------------------------------------------------------
1222
// SQL templates
1323
// ---------------------------------------------------------------------------
@@ -141,12 +151,6 @@ LIMIT __LIMIT__
141151
// Helpers
142152
// ---------------------------------------------------------------------------
143153

144-
function getWhType(warehouse: string): string {
145-
const warehouses = Registry.list().warehouses
146-
const wh = warehouses.find((w) => w.name === warehouse)
147-
return wh?.type || "unknown"
148-
}
149-
150154
function buildHistoryQuery(
151155
whType: string,
152156
days: number,
@@ -210,23 +214,38 @@ function rowsToRecords(result: { columns: string[]; rows: any[][] }): Record<str
210214
// ---------------------------------------------------------------------------
211215

212216
export async function getQueryHistory(params: QueryHistoryParams): Promise<QueryHistoryResult> {
213-
const whType = getWhType(params.warehouse)
214217
const days = params.days ?? 7
215218
const limit = params.limit ?? 100
216-
const bqRegion = whType === "bigquery" ? bqRegionFor(params.warehouse) : undefined
219+
220+
const resolved = resolveFinopsWarehouse({
221+
requested: params.warehouse,
222+
supportedTypes: QUERY_HISTORY_SUPPORTED_TYPES,
223+
operationName: "Query history",
224+
})
225+
if (resolved.kind === "error") {
226+
return {
227+
success: false,
228+
queries: [],
229+
summary: {},
230+
error: resolved.error,
231+
}
232+
}
233+
234+
const { warehouse: whName, type: whType } = resolved
235+
const bqRegion = whType === "bigquery" ? bqRegionFor(whName) : undefined
217236

218237
const built = buildHistoryQuery(whType, days, limit, params.user, params.warehouse_filter, bqRegion)
219238
if (!built) {
220239
return {
221240
success: false,
222241
queries: [],
223242
summary: {},
224-
error: `Query history is not available for ${whType} warehouses.`,
243+
error: `Internal error: query history SQL template missing for ${whType}.`,
225244
}
226245
}
227246

228247
try {
229-
const connector = await Registry.get(params.warehouse)
248+
const connector = await Registry.get(whName)
230249
const result = await connector.execute(built.sql, limit, built.binds)
231250
const queries = rowsToRecords(result)
232251

@@ -261,7 +280,7 @@ export async function getQueryHistory(params: QueryHistoryParams): Promise<Query
261280
success: false,
262281
queries: [],
263282
summary: {},
264-
error: String(e),
283+
error: e instanceof Error ? e.message : String(e),
265284
}
266285
}
267286
}

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

Lines changed: 42 additions & 24 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

@@ -202,26 +216,28 @@ export async function queryGrants(params: RoleGrantsParams): Promise<RoleGrantsR
202216
grants: [],
203217
grant_count: 0,
204218
privilege_summary: {},
205-
error: String(e),
219+
error: e instanceof Error ? e.message : String(e),
206220
}
207221
}
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

@@ -241,26 +257,28 @@ export async function queryRoleHierarchy(params: RoleHierarchyParams): Promise<R
241257
success: false,
242258
hierarchy: [],
243259
role_count: 0,
244-
error: String(e),
260+
error: e instanceof Error ? e.message : String(e),
245261
}
246262
}
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 = ?") : ""
@@ -280,7 +298,7 @@ export async function queryUserRoles(params: UserRolesParams): Promise<UserRoles
280298
success: false,
281299
assignments: [],
282300
assignment_count: 0,
283-
error: String(e),
301+
error: e instanceof Error ? e.message : String(e),
284302
}
285303
}
286304
}

0 commit comments

Comments
 (0)