Skip to content

Commit 14aa1a1

Browse files
sahrizviclaude
andcommitted
fix(finops): re-validate the snapshot, say "unknown" like check() does, runnable recipes
Codex review of #1346 (gpt-5.6-sol). - The note trusted the cached precedence snapshot; a project re-linked while the call ran could be pointed at the workspace it had left. The helper is async now and re-validates with `snapshotState` before naming a workspace, as `check()` does before a redirect; relinked/unreadable are said and marked `undetermined` - No snapshot at all (a caller that never resolved tools, an evicted entry) was a silent local failure; it is the unknown `check()` reports - BigQuery recipes named bare `INFORMATION_SCHEMA` views, which are only reachable region-qualified (`bq-utils.ts`): they read `region-<location>.INFORMATION_SCHEMA.…` now. The Snowflake unused-resource recipe adds `QUERY_HISTORY`; warehouse advice adds `SHOW WAREHOUSES` - Tests: every one of the eight wrappers through the real handler (unwrapping any one fails it — checked by mutation); an unbound snapshot stays plain; no snapshot is undetermined; a re-linked project gets no recommendation; every BigQuery recipe is region-qualified Not changed: a FinOps call that SUCCEEDS against an unrelated local connection while the project is bound elsewhere says nothing about it (pre-existing auto-pick behaviour), and the other registry-backed tools (`schema_index`, live PII, data_diff, warehouse_test/list) still fail bare — both are follow-ups, not this issue. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012Q51zFUmPg1WwtS5CrGJE6
1 parent 3264426 commit 14aa1a1

8 files changed

Lines changed: 136 additions & 57 deletions

‎packages/opencode/src/altimate/tools/finops-analyze-credits.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ export const FinopsAnalyzeCreditsTool = Tool.define("finops_analyze_credits", {
9595

9696
if (!result.success) {
9797
const error = result.error ?? "Unknown error"
98-
return withWorkspaceFallback(ctx.sessionID, "analyze_credits", DEFAULT_FINOPS_TYPES, {
98+
return await withWorkspaceFallback(ctx.sessionID, "analyze_credits", DEFAULT_FINOPS_TYPES, {
9999
title: "Credit Analysis: FAILED",
100100
metadata: { success: false, total_credits: 0, error },
101101
output: `Failed to analyze credits: ${error}`,
@@ -116,7 +116,7 @@ export const FinopsAnalyzeCreditsTool = Tool.define("finops_analyze_credits", {
116116
}
117117
} catch (e) {
118118
const msg = e instanceof Error ? e.message : String(e)
119-
return withWorkspaceFallback(ctx.sessionID, "analyze_credits", DEFAULT_FINOPS_TYPES, {
119+
return await withWorkspaceFallback(ctx.sessionID, "analyze_credits", DEFAULT_FINOPS_TYPES, {
120120
title: "Credit Analysis: ERROR",
121121
metadata: { success: false, total_credits: 0, error: msg },
122122
output: `Failed to analyze credits: ${msg}`,

‎packages/opencode/src/altimate/tools/finops-expensive-queries.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ export const FinopsExpensiveQueriesTool = Tool.define("finops_expensive_queries"
6060

6161
if (!result.success) {
6262
const error = result.error ?? "Unknown error"
63-
return withWorkspaceFallback(ctx.sessionID, "expensive_queries", DEFAULT_FINOPS_TYPES, {
63+
return await withWorkspaceFallback(ctx.sessionID, "expensive_queries", DEFAULT_FINOPS_TYPES, {
6464
title: "Expensive Queries: FAILED",
6565
metadata: { success: false, query_count: 0, error },
6666
output: `Failed to find expensive queries: ${error}`,
@@ -74,7 +74,7 @@ export const FinopsExpensiveQueriesTool = Tool.define("finops_expensive_queries"
7474
}
7575
} catch (e) {
7676
const msg = e instanceof Error ? e.message : String(e)
77-
return withWorkspaceFallback(ctx.sessionID, "expensive_queries", DEFAULT_FINOPS_TYPES, {
77+
return await withWorkspaceFallback(ctx.sessionID, "expensive_queries", DEFAULT_FINOPS_TYPES, {
7878
title: "Expensive Queries: ERROR",
7979
metadata: { success: false, query_count: 0, error: msg },
8080
output: `Failed to find expensive queries: ${msg}`,

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ export const FinopsQueryHistoryTool = Tool.define("finops_query_history", {
8484

8585
if (!result.success) {
8686
const error = result.error ?? "Unknown error"
87-
return withWorkspaceFallback(ctx.sessionID, "query_history", QUERY_HISTORY_SUPPORTED_TYPES, {
87+
return await withWorkspaceFallback(ctx.sessionID, "query_history", QUERY_HISTORY_SUPPORTED_TYPES, {
8888
title: "Query History: FAILED",
8989
metadata: { success: false, query_count: 0, error },
9090
output: `Failed to fetch query history: ${error}`,
@@ -99,7 +99,7 @@ export const FinopsQueryHistoryTool = Tool.define("finops_query_history", {
9999
}
100100
} catch (e) {
101101
const msg = e instanceof Error ? e.message : String(e)
102-
return withWorkspaceFallback(ctx.sessionID, "query_history", QUERY_HISTORY_SUPPORTED_TYPES, {
102+
return await withWorkspaceFallback(ctx.sessionID, "query_history", QUERY_HISTORY_SUPPORTED_TYPES, {
103103
title: "Query History: ERROR",
104104
metadata: { success: false, query_count: 0, error: msg },
105105
output: `Failed to fetch query history: ${msg}`,

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

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ export const FinopsRoleGrantsTool = Tool.define("finops_role_grants", {
124124
})
125125

126126
if (!result.success) {
127-
return withWorkspaceFallback(ctx.sessionID, "role_grants", DEFAULT_FINOPS_TYPES, {
127+
return await withWorkspaceFallback(ctx.sessionID, "role_grants", DEFAULT_FINOPS_TYPES, {
128128
title: "Role Grants: FAILED",
129129
metadata: { success: false, grant_count: 0 },
130130
output: `Failed to query grants: ${result.error ?? "Unknown error"}`,
@@ -138,7 +138,7 @@ export const FinopsRoleGrantsTool = Tool.define("finops_role_grants", {
138138
}
139139
} catch (e) {
140140
const msg = e instanceof Error ? e.message : String(e)
141-
return withWorkspaceFallback(ctx.sessionID, "role_grants", DEFAULT_FINOPS_TYPES, {
141+
return await withWorkspaceFallback(ctx.sessionID, "role_grants", DEFAULT_FINOPS_TYPES, {
142142
title: "Role Grants: ERROR",
143143
metadata: { success: false, grant_count: 0, error: msg },
144144
output: `Failed to query grants: ${msg}`,
@@ -162,7 +162,7 @@ export const FinopsRoleHierarchyTool = Tool.define("finops_role_hierarchy", {
162162
const result = await Dispatcher.call("finops.role_hierarchy", { warehouse: args.warehouse })
163163

164164
if (!result.success) {
165-
return withWorkspaceFallback(ctx.sessionID, "role_hierarchy", SNOWFLAKE_ONLY_TYPES, {
165+
return await withWorkspaceFallback(ctx.sessionID, "role_hierarchy", SNOWFLAKE_ONLY_TYPES, {
166166
title: "Role Hierarchy: FAILED",
167167
metadata: { success: false, role_count: 0 },
168168
output: `Failed to query role hierarchy: ${result.error ?? "Unknown error"}`,
@@ -176,7 +176,7 @@ export const FinopsRoleHierarchyTool = Tool.define("finops_role_hierarchy", {
176176
}
177177
} catch (e) {
178178
const msg = e instanceof Error ? e.message : String(e)
179-
return withWorkspaceFallback(ctx.sessionID, "role_hierarchy", SNOWFLAKE_ONLY_TYPES, {
179+
return await withWorkspaceFallback(ctx.sessionID, "role_hierarchy", SNOWFLAKE_ONLY_TYPES, {
180180
title: "Role Hierarchy: ERROR",
181181
metadata: { success: false, role_count: 0, error: msg },
182182
output: `Failed to query role hierarchy: ${msg}`,
@@ -206,7 +206,7 @@ export const FinopsUserRolesTool = Tool.define("finops_user_roles", {
206206
})
207207

208208
if (!result.success) {
209-
return withWorkspaceFallback(ctx.sessionID, "user_roles", SNOWFLAKE_ONLY_TYPES, {
209+
return await withWorkspaceFallback(ctx.sessionID, "user_roles", SNOWFLAKE_ONLY_TYPES, {
210210
title: "User Roles: FAILED",
211211
metadata: { success: false, assignment_count: 0 },
212212
output: `Failed to query user roles: ${result.error ?? "Unknown error"}`,
@@ -220,7 +220,7 @@ export const FinopsUserRolesTool = Tool.define("finops_user_roles", {
220220
}
221221
} catch (e) {
222222
const msg = e instanceof Error ? e.message : String(e)
223-
return withWorkspaceFallback(ctx.sessionID, "user_roles", SNOWFLAKE_ONLY_TYPES, {
223+
return await withWorkspaceFallback(ctx.sessionID, "user_roles", SNOWFLAKE_ONLY_TYPES, {
224224
title: "User Roles: ERROR",
225225
metadata: { success: false, assignment_count: 0, error: msg },
226226
output: `Failed to query user roles: ${msg}`,

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ export const FinopsUnusedResourcesTool = Tool.define("finops_unused_resources",
8383

8484
if (!result.success) {
8585
const error = result.error ?? "Unknown error"
86-
return withWorkspaceFallback(ctx.sessionID, "unused_resources", DEFAULT_FINOPS_TYPES, {
86+
return await withWorkspaceFallback(ctx.sessionID, "unused_resources", DEFAULT_FINOPS_TYPES, {
8787
title: "Unused Resources: FAILED",
8888
metadata: { success: false, unused_count: 0, error },
8989
output: `Failed to find unused resources: ${error}`,
@@ -100,7 +100,7 @@ export const FinopsUnusedResourcesTool = Tool.define("finops_unused_resources",
100100
}
101101
} catch (e) {
102102
const msg = e instanceof Error ? e.message : String(e)
103-
return withWorkspaceFallback(ctx.sessionID, "unused_resources", DEFAULT_FINOPS_TYPES, {
103+
return await withWorkspaceFallback(ctx.sessionID, "unused_resources", DEFAULT_FINOPS_TYPES, {
104104
title: "Unused Resources: ERROR",
105105
metadata: { success: false, unused_count: 0, error: msg },
106106
output: `Failed to find unused resources: ${msg}`,

‎packages/opencode/src/altimate/tools/finops-warehouse-advice.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ export const FinopsWarehouseAdviceTool = Tool.define("finops_warehouse_advice",
104104

105105
if (!result.success) {
106106
const error = result.error ?? "Unknown error"
107-
return withWorkspaceFallback(ctx.sessionID, "warehouse_advice", DEFAULT_FINOPS_TYPES, {
107+
return await withWorkspaceFallback(ctx.sessionID, "warehouse_advice", DEFAULT_FINOPS_TYPES, {
108108
title: "Warehouse Advice: FAILED",
109109
metadata: { success: false, recommendation_count: 0, error },
110110
output: `Failed to analyze warehouses: ${error}`,
@@ -127,7 +127,7 @@ export const FinopsWarehouseAdviceTool = Tool.define("finops_warehouse_advice",
127127
}
128128
} catch (e) {
129129
const msg = e instanceof Error ? e.message : String(e)
130-
return withWorkspaceFallback(ctx.sessionID, "warehouse_advice", DEFAULT_FINOPS_TYPES, {
130+
return await withWorkspaceFallback(ctx.sessionID, "warehouse_advice", DEFAULT_FINOPS_TYPES, {
131131
title: "Warehouse Advice: ERROR",
132132
metadata: { success: false, recommendation_count: 0, error: msg },
133133
output: `Failed to analyze warehouses: ${msg}`,

‎packages/opencode/src/altimate/tools/finops-workspace.ts‎

Lines changed: 48 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -31,37 +31,40 @@ export type FinopsOperation =
3131
* handler itself reads (`native/finops/*.ts`), so the model writes the query the
3232
* tool would have run. Keyed by canonical local driver type, the key
3333
* `servedInventory` reports; an operation/type pair with no entry gets the tool
34-
* name alone rather than a table that holds something else. */
34+
* name alone rather than a table that holds something else. BigQuery's
35+
* INFORMATION_SCHEMA views are only reachable region-qualified (`bq-utils.ts`), and
36+
* the snapshot does not carry the integration's region, so the placeholder is
37+
* spelled out rather than a bare name that would fail again. */
3538
const SOURCE: Readonly<Record<FinopsOperation, Readonly<Record<string, string>>>> = {
3639
query_history: {
3740
snowflake: "`SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY`",
38-
bigquery: "`INFORMATION_SCHEMA.JOBS`",
41+
bigquery: "`region-<location>.INFORMATION_SCHEMA.JOBS`",
3942
databricks: "`system.query.history`",
4043
postgres: "`pg_stat_statements`",
4144
},
4245
analyze_credits: {
4346
snowflake: "`SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY` and `QUERY_HISTORY`",
44-
bigquery: "`INFORMATION_SCHEMA.JOBS`",
47+
bigquery: "`region-<location>.INFORMATION_SCHEMA.JOBS`",
4548
databricks: "`system.billing.usage` and `system.query.history`",
4649
},
4750
expensive_queries: {
4851
snowflake: "`SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY`",
49-
bigquery: "`INFORMATION_SCHEMA.JOBS`",
52+
bigquery: "`region-<location>.INFORMATION_SCHEMA.JOBS`",
5053
databricks: "`system.query.history`",
5154
},
5255
warehouse_advice: {
53-
snowflake: "`SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_LOAD_HISTORY` and `QUERY_HISTORY`",
54-
bigquery: "`INFORMATION_SCHEMA.JOBS` and `JOBS_TIMELINE`",
56+
snowflake: "`SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_LOAD_HISTORY` and `QUERY_HISTORY`, plus `SHOW WAREHOUSES`",
57+
bigquery: "`region-<location>.INFORMATION_SCHEMA.JOBS` and `JOBS_TIMELINE`",
5558
databricks: "`system.compute.warehouse_events` and `system.query.history`",
5659
},
5760
unused_resources: {
58-
snowflake: "`SNOWFLAKE.ACCOUNT_USAGE.TABLE_STORAGE_METRICS`, `ACCESS_HISTORY` and `WAREHOUSES`",
59-
bigquery: "`INFORMATION_SCHEMA.TABLE_STORAGE`",
61+
snowflake: "`SNOWFLAKE.ACCOUNT_USAGE.TABLE_STORAGE_METRICS`, `ACCESS_HISTORY`, `WAREHOUSES` and `QUERY_HISTORY`",
62+
bigquery: "`region-<location>.INFORMATION_SCHEMA.TABLE_STORAGE`",
6063
databricks: "`system.information_schema.tables`",
6164
},
6265
role_grants: {
6366
snowflake: "`SNOWFLAKE.ACCOUNT_USAGE.GRANTS_TO_ROLES`",
64-
bigquery: "`INFORMATION_SCHEMA.OBJECT_PRIVILEGES`",
67+
bigquery: "`region-<location>.INFORMATION_SCHEMA.OBJECT_PRIVILEGES`",
6568
databricks: "`system.information_schema.table_privileges`",
6669
},
6770
role_hierarchy: { snowflake: "`SNOWFLAKE.ACCOUNT_USAGE.GRANTS_TO_ROLES` (granted_on = 'ROLE')" },
@@ -85,16 +88,20 @@ export interface WorkspaceFallback {
8588
* snapshot only — the same reachability-filtered projection the awareness section
8689
* uses, so this never names a tool the caller's agent cannot call.
8790
*/
88-
export function workspaceFallbacks(sessionID: string, supportedTypes: readonly string[]): WorkspaceFallback[] {
91+
export async function workspaceFallbacks(sessionID: string, supportedTypes: readonly string[]): Promise<WorkspaceFallback[]> {
8992
const precedence = Precedence.forSession(sessionID)
9093
if (!precedence?.enabled) return []
91-
return Precedence.servedInventory(precedence).flatMap(({ type, served }) => {
94+
const served = Precedence.servedInventory(precedence).flatMap(({ type, served }) => {
9295
if (!supportedTypes.includes(type)) return []
9396
const execute = served.find((row) => row.capability === "sql_execute")
9497
return execute
9598
? [{ workspaceName: precedence.workspaceName, workspaceId: precedence.workspaceId, type, modelKey: execute.modelKey }]
9699
: []
97100
})
101+
if (served.length === 0) return []
102+
// Same re-validation `check()` does before a redirect: a note naming a workspace the
103+
// project has since left would send the model to that workspace's engine.
104+
return (await Precedence.snapshotState(precedence)) === "current" ? served : []
98105
}
99106

100107
/** The sentence appended to a FinOps failure, or nothing when the workspace serves
@@ -117,18 +124,32 @@ export function workspaceFallbackNote(operation: FinopsOperation, fallbacks: Wor
117124
)
118125
}
119126

120-
/** Why the fallback could not be decided, when routing is disabled for a reason that
121-
* is uncertainty rather than a choice. Deliberate disablement (unbound, pilot off,
122-
* `--integrations=local`, nothing materialised) says nothing: that is the plain local
123-
* failure. Uncertainty must say so (the precedence module's first claim), so the
124-
* failure is marked `undetermined` and says the workspace could not be consulted. */
125-
function undeterminedNote(sessionID: string): string | undefined {
126-
const reason = Precedence.forSession(sessionID)?.disabledReason
127-
if (reason !== "unattributed" && reason !== "binding-unreadable" && reason !== "derive-failed") return undefined
128-
return (
129-
"Whether the linked workspace serves this connection type could not be determined this turn " +
130-
"(no routing decision was available), so no workspace alternative is offered here."
131-
)
127+
/** Why the fallback could not be decided, when that is uncertainty rather than a
128+
* choice. Deliberate disablement (unbound, pilot off, `--integrations=local`, nothing
129+
* materialised) says nothing: that is the plain local failure. Uncertainty must say so
130+
* (the precedence module's first claim), so the failure is marked `undetermined` and
131+
* says the workspace could not be consulted — mirroring `check()`'s own cases. */
132+
async function undeterminedNote(sessionID: string): Promise<string | undefined> {
133+
const precedence = Precedence.forSession(sessionID)
134+
// No snapshot at all is the same unknown `check()` reports: a caller that never
135+
// resolved tools, or an entry evicted between resolution and this call.
136+
if (!precedence) {
137+
return "No routing decision was available for this call, so whether the linked workspace serves this connection type is unknown."
138+
}
139+
const reason = precedence.disabledReason
140+
if (reason === "unattributed" || reason === "binding-unreadable" || reason === "derive-failed") {
141+
return (
142+
"Whether the linked workspace serves this connection type could not be determined this turn " +
143+
"(no routing decision was available), so no workspace alternative is offered here."
144+
)
145+
}
146+
if (!precedence.enabled) return undefined
147+
// Enabled, but the link changed or could not be read while this call ran.
148+
const state = await Precedence.snapshotState(precedence)
149+
if (state === "current") return undefined
150+
return state === "unreadable"
151+
? "The workspace link could not be read while this call ran, so whether the workspace serves this connection type is unknown."
152+
: "The project was re-linked while this call ran, so the previous routing decision no longer applies."
132153
}
133154

134155
/**
@@ -137,13 +158,13 @@ function undeterminedNote(sessionID: string): string | undefined {
137158
* metadata so telemetry can tell a failure the model could route around from a dead
138159
* end.
139160
*/
140-
export function withWorkspaceFallback<T extends { metadata: Record<string, unknown>; output: string }>(
161+
export async function withWorkspaceFallback<T extends { metadata: Record<string, unknown>; output: string }>(
141162
sessionID: string,
142163
operation: FinopsOperation,
143164
supportedTypes: readonly string[],
144165
result: T,
145-
): T {
146-
const fallbacks = workspaceFallbacks(sessionID, supportedTypes)
166+
): Promise<T> {
167+
const fallbacks = await workspaceFallbacks(sessionID, supportedTypes)
147168
const note = workspaceFallbackNote(operation, fallbacks)
148169
if (note) {
149170
return {
@@ -152,7 +173,7 @@ export function withWorkspaceFallback<T extends { metadata: Record<string, unkno
152173
output: `${result.output}\n\n${note}`,
153174
}
154175
}
155-
const undetermined = undeterminedNote(sessionID)
176+
const undetermined = await undeterminedNote(sessionID)
156177
if (!undetermined) return result
157178
return {
158179
...result,

0 commit comments

Comments
 (0)