Skip to content

Commit 8d5266c

Browse files
sahrizviclaude
andcommitted
fix(finops): name the workspace engine tool when a FinOps tool has no local connection
The `finops_*` tools resolve warehouses from the local connection registry only. In a project bound to a workspace whose Snowflake credentials live in the workspace, every one of them failed with a bare `FAILED`, and the workspace's own cost skills steer the model to exactly these tools first — so a cost question began with four failures before the model fell back to raw `ACCOUNT_USAGE` SQL through `datamate_snowflake_execute_database_query`. - New `tools/finops-workspace.ts`: when the session's precedence snapshot serves `sql_execute` for a type the operation supports (reachability-filtered, the same projection the awareness section uses), append the reason and the engine tool to the failure, with the usage tables to query, and stamp `metadata.workspace_fallback` for telemetry - Every `finops_*` failure branch (dispatcher error and thrown error) goes through `withWorkspaceFallback`; the local reason is kept - Export `QUERY_HISTORY_SUPPORTED_TYPES` / `SNOWFLAKE_ONLY_TYPES` so the wrappers name the types their handler really supports - Tests: served/unserved/disabled/analyst shapes, and the three tool paths through the real handlers with an empty registry Closes #1336 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012Q51zFUmPg1WwtS5CrGJE6
1 parent 13cab51 commit 8d5266c

10 files changed

Lines changed: 305 additions & 34 deletions

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { bqRegionFor, interpolateBqRegion } from "./bq-utils"
99
import { resolveFinopsWarehouse } from "./warehouse-resolver"
1010
import type { QueryHistoryParams, QueryHistoryResult } from "../types"
1111

12-
const QUERY_HISTORY_SUPPORTED_TYPES = [
12+
export const QUERY_HISTORY_SUPPORTED_TYPES = [
1313
"snowflake",
1414
"postgres",
1515
"postgresql",

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ LIMIT ?
109109
// ---------------------------------------------------------------------------
110110

111111
const GRANTS_SUPPORTED_TYPES = DEFAULT_FINOPS_TYPES
112-
const SNOWFLAKE_ONLY_TYPES = ["snowflake"] as const
112+
export const SNOWFLAKE_ONLY_TYPES = ["snowflake"] as const
113113

114114
function rowsToRecords(result: { columns: string[]; rows: any[][] }): Record<string, unknown>[] {
115115
return result.rows.map((row) => {

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import z from "zod"
22
import { Tool } from "../../tool/tool"
33
import { Dispatcher } from "../native"
4+
import { DEFAULT_FINOPS_TYPES } from "../native/finops/warehouse-resolver"
5+
import { withWorkspaceFallback } from "./finops-workspace"
46

57
function formatCreditsAnalysis(
68
totalCredits: number,
@@ -93,11 +95,11 @@ export const FinopsAnalyzeCreditsTool = Tool.define("finops_analyze_credits", {
9395

9496
if (!result.success) {
9597
const error = result.error ?? "Unknown error"
96-
return {
98+
return withWorkspaceFallback(ctx.sessionID, DEFAULT_FINOPS_TYPES, {
9799
title: "Credit Analysis: FAILED",
98100
metadata: { success: false, total_credits: 0, error },
99101
output: `Failed to analyze credits: ${error}`,
100-
}
102+
})
101103
}
102104

103105
const totalCredits = Number(result.total_credits ?? 0)
@@ -114,11 +116,11 @@ export const FinopsAnalyzeCreditsTool = Tool.define("finops_analyze_credits", {
114116
}
115117
} catch (e) {
116118
const msg = e instanceof Error ? e.message : String(e)
117-
return {
119+
return withWorkspaceFallback(ctx.sessionID, DEFAULT_FINOPS_TYPES, {
118120
title: "Credit Analysis: ERROR",
119121
metadata: { success: false, total_credits: 0, error: msg },
120122
output: `Failed to analyze credits: ${msg}`,
121-
}
123+
})
122124
}
123125
},
124126
})

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import z from "zod"
22
import { Tool } from "../../tool/tool"
33
import { Dispatcher } from "../native"
4+
import { DEFAULT_FINOPS_TYPES } from "../native/finops/warehouse-resolver"
5+
import { withWorkspaceFallback } from "./finops-workspace"
46
import { formatBytes, truncateQuery } from "./finops-formatting"
57

68
function formatExpensiveQueries(queries: unknown[]): string {
@@ -58,11 +60,11 @@ export const FinopsExpensiveQueriesTool = Tool.define("finops_expensive_queries"
5860

5961
if (!result.success) {
6062
const error = result.error ?? "Unknown error"
61-
return {
63+
return withWorkspaceFallback(ctx.sessionID, DEFAULT_FINOPS_TYPES, {
6264
title: "Expensive Queries: FAILED",
6365
metadata: { success: false, query_count: 0, error },
6466
output: `Failed to find expensive queries: ${error}`,
65-
}
67+
})
6668
}
6769

6870
return {
@@ -72,11 +74,11 @@ export const FinopsExpensiveQueriesTool = Tool.define("finops_expensive_queries"
7274
}
7375
} catch (e) {
7476
const msg = e instanceof Error ? e.message : String(e)
75-
return {
77+
return withWorkspaceFallback(ctx.sessionID, DEFAULT_FINOPS_TYPES, {
7678
title: "Expensive Queries: ERROR",
7779
metadata: { success: false, query_count: 0, error: msg },
7880
output: `Failed to find expensive queries: ${msg}`,
79-
}
81+
})
8082
}
8183
},
8284
})

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import z from "zod"
22
import { Tool } from "../../tool/tool"
33
import { Dispatcher } from "../native"
4+
import { QUERY_HISTORY_SUPPORTED_TYPES } from "../native/finops/query-history"
5+
import { withWorkspaceFallback } from "./finops-workspace"
46
import { formatBytes, truncateQuery } from "./finops-formatting"
57

68
function formatQueryHistory(summary: Record<string, unknown>, queries: unknown[]): string {
@@ -82,11 +84,11 @@ export const FinopsQueryHistoryTool = Tool.define("finops_query_history", {
8284

8385
if (!result.success) {
8486
const error = result.error ?? "Unknown error"
85-
return {
87+
return withWorkspaceFallback(ctx.sessionID, QUERY_HISTORY_SUPPORTED_TYPES, {
8688
title: "Query History: FAILED",
8789
metadata: { success: false, query_count: 0, error },
8890
output: `Failed to fetch query history: ${error}`,
89-
}
91+
})
9092
}
9193

9294
const summary = result.summary as Record<string, unknown>
@@ -97,11 +99,11 @@ export const FinopsQueryHistoryTool = Tool.define("finops_query_history", {
9799
}
98100
} catch (e) {
99101
const msg = e instanceof Error ? e.message : String(e)
100-
return {
102+
return withWorkspaceFallback(ctx.sessionID, QUERY_HISTORY_SUPPORTED_TYPES, {
101103
title: "Query History: ERROR",
102104
metadata: { success: false, query_count: 0, error: msg },
103105
output: `Failed to fetch query history: ${msg}`,
104-
}
106+
})
105107
}
106108
},
107109
})

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

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import z from "zod"
22
import { Tool } from "../../tool/tool"
33
import { Dispatcher } from "../native"
4+
import { DEFAULT_FINOPS_TYPES } from "../native/finops/warehouse-resolver"
5+
import { SNOWFLAKE_ONLY_TYPES } from "../native/finops/role-access"
6+
import { withWorkspaceFallback } from "./finops-workspace"
47

58
function formatGrants(privilegeSummary: unknown, grants: unknown[]): string {
69
const lines: string[] = []
@@ -121,11 +124,11 @@ export const FinopsRoleGrantsTool = Tool.define("finops_role_grants", {
121124
})
122125

123126
if (!result.success) {
124-
return {
127+
return withWorkspaceFallback(ctx.sessionID, DEFAULT_FINOPS_TYPES, {
125128
title: "Role Grants: FAILED",
126129
metadata: { success: false, grant_count: 0 },
127130
output: `Failed to query grants: ${result.error ?? "Unknown error"}`,
128-
}
131+
})
129132
}
130133

131134
return {
@@ -135,11 +138,11 @@ export const FinopsRoleGrantsTool = Tool.define("finops_role_grants", {
135138
}
136139
} catch (e) {
137140
const msg = e instanceof Error ? e.message : String(e)
138-
return {
141+
return withWorkspaceFallback(ctx.sessionID, DEFAULT_FINOPS_TYPES, {
139142
title: "Role Grants: ERROR",
140143
metadata: { success: false, grant_count: 0, error: msg },
141144
output: `Failed to query grants: ${msg}`,
142-
}
145+
})
143146
}
144147
},
145148
})
@@ -159,11 +162,11 @@ export const FinopsRoleHierarchyTool = Tool.define("finops_role_hierarchy", {
159162
const result = await Dispatcher.call("finops.role_hierarchy", { warehouse: args.warehouse })
160163

161164
if (!result.success) {
162-
return {
165+
return withWorkspaceFallback(ctx.sessionID, SNOWFLAKE_ONLY_TYPES, {
163166
title: "Role Hierarchy: FAILED",
164167
metadata: { success: false, role_count: 0 },
165168
output: `Failed to query role hierarchy: ${result.error ?? "Unknown error"}`,
166-
}
169+
})
167170
}
168171

169172
return {
@@ -173,11 +176,11 @@ export const FinopsRoleHierarchyTool = Tool.define("finops_role_hierarchy", {
173176
}
174177
} catch (e) {
175178
const msg = e instanceof Error ? e.message : String(e)
176-
return {
179+
return withWorkspaceFallback(ctx.sessionID, SNOWFLAKE_ONLY_TYPES, {
177180
title: "Role Hierarchy: ERROR",
178181
metadata: { success: false, role_count: 0, error: msg },
179182
output: `Failed to query role hierarchy: ${msg}`,
180-
}
183+
})
181184
}
182185
},
183186
})
@@ -203,11 +206,11 @@ export const FinopsUserRolesTool = Tool.define("finops_user_roles", {
203206
})
204207

205208
if (!result.success) {
206-
return {
209+
return withWorkspaceFallback(ctx.sessionID, SNOWFLAKE_ONLY_TYPES, {
207210
title: "User Roles: FAILED",
208211
metadata: { success: false, assignment_count: 0 },
209212
output: `Failed to query user roles: ${result.error ?? "Unknown error"}`,
210-
}
213+
})
211214
}
212215

213216
return {
@@ -217,11 +220,11 @@ export const FinopsUserRolesTool = Tool.define("finops_user_roles", {
217220
}
218221
} catch (e) {
219222
const msg = e instanceof Error ? e.message : String(e)
220-
return {
223+
return withWorkspaceFallback(ctx.sessionID, SNOWFLAKE_ONLY_TYPES, {
221224
title: "User Roles: ERROR",
222225
metadata: { success: false, assignment_count: 0, error: msg },
223226
output: `Failed to query user roles: ${msg}`,
224-
}
227+
})
225228
}
226229
},
227230
})

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import z from "zod"
22
import { Tool } from "../../tool/tool"
33
import { Dispatcher } from "../native"
4+
import { DEFAULT_FINOPS_TYPES } from "../native/finops/warehouse-resolver"
5+
import { withWorkspaceFallback } from "./finops-workspace"
46

57
function formatUnusedResources(
68
summary: Record<string, unknown>,
@@ -81,11 +83,11 @@ export const FinopsUnusedResourcesTool = Tool.define("finops_unused_resources",
8183

8284
if (!result.success) {
8385
const error = result.error ?? "Unknown error"
84-
return {
86+
return withWorkspaceFallback(ctx.sessionID, DEFAULT_FINOPS_TYPES, {
8587
title: "Unused Resources: FAILED",
8688
metadata: { success: false, unused_count: 0, error },
8789
output: `Failed to find unused resources: ${error}`,
88-
}
90+
})
8991
}
9092

9193
const summary = result.summary as Record<string, unknown>
@@ -98,11 +100,11 @@ export const FinopsUnusedResourcesTool = Tool.define("finops_unused_resources",
98100
}
99101
} catch (e) {
100102
const msg = e instanceof Error ? e.message : String(e)
101-
return {
103+
return withWorkspaceFallback(ctx.sessionID, DEFAULT_FINOPS_TYPES, {
102104
title: "Unused Resources: ERROR",
103105
metadata: { success: false, unused_count: 0, error: msg },
104106
output: `Failed to find unused resources: ${msg}`,
105-
}
107+
})
106108
}
107109
},
108110
})

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import z from "zod"
22
import { Tool } from "../../tool/tool"
33
import { Dispatcher } from "../native"
4+
import { DEFAULT_FINOPS_TYPES } from "../native/finops/warehouse-resolver"
5+
import { withWorkspaceFallback } from "./finops-workspace"
46

57
function formatWarehouseAdvice(
68
recommendations: unknown[],
@@ -102,11 +104,11 @@ export const FinopsWarehouseAdviceTool = Tool.define("finops_warehouse_advice",
102104

103105
if (!result.success) {
104106
const error = result.error ?? "Unknown error"
105-
return {
107+
return withWorkspaceFallback(ctx.sessionID, DEFAULT_FINOPS_TYPES, {
106108
title: "Warehouse Advice: FAILED",
107109
metadata: { success: false, recommendation_count: 0, error },
108110
output: `Failed to analyze warehouses: ${error}`,
109-
}
111+
})
110112
}
111113

112114
// Defensive null-coalesce in case the handler ever returns a partial
@@ -125,11 +127,11 @@ export const FinopsWarehouseAdviceTool = Tool.define("finops_warehouse_advice",
125127
}
126128
} catch (e) {
127129
const msg = e instanceof Error ? e.message : String(e)
128-
return {
130+
return withWorkspaceFallback(ctx.sessionID, DEFAULT_FINOPS_TYPES, {
129131
title: "Warehouse Advice: ERROR",
130132
metadata: { success: false, recommendation_count: 0, error: msg },
131133
output: `Failed to analyze warehouses: ${msg}`,
132-
}
134+
})
133135
}
134136
},
135137
})
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
// altimate_change - new file
2+
//
3+
// The FinOps tools run their SQL through connections configured on this machine —
4+
// `~/.altimate-code/connections.json`, the project's, `ALTIMATE_CODE_CONN_*` — and
5+
// nothing else. A project bound to a workspace whose warehouse credentials live in the
6+
// workspace has none of those, so every `finops_*` call fails, and the workspace's own
7+
// cost skills steer the model to exactly these tools first. A bare `FAILED` there sends
8+
// the model through four failures before it thinks of the engine tool that works.
9+
//
10+
// This is the reason and the way out, appended to every FinOps failure when the
11+
// session's bound workspace serves a type the tool supports. It is advice, not a
12+
// redirect: the FinOps SQL is not routed through the engine (that is the option the
13+
// issue prefers and a larger change — the engine's result shape is not a contract the
14+
// native handlers can parse), so the model is told which engine tool to run the same
15+
// usage-table query through instead.
16+
import * as Precedence from "../workspace/precedence"
17+
18+
/** Where each served type keeps the usage data the FinOps tools read, so the model
19+
* can write the query the tool would have run. Keyed by canonical local driver type,
20+
* the key `servedInventory` reports. */
21+
const USAGE_SOURCE: Readonly<Record<string, string>> = {
22+
snowflake:
23+
"the `SNOWFLAKE.ACCOUNT_USAGE` views (`QUERY_HISTORY`, `WAREHOUSE_METERING_HISTORY`, " +
24+
"`WAREHOUSE_LOAD_HISTORY`, `GRANTS_TO_ROLES`, `GRANTS_TO_USERS`)",
25+
bigquery: "`INFORMATION_SCHEMA.JOBS_BY_PROJECT`",
26+
databricks: "`system.query.history` and `system.billing.usage`",
27+
postgres: "`pg_stat_statements`",
28+
}
29+
30+
export interface WorkspaceFallback {
31+
workspaceName: string
32+
/** Canonical local driver type the workspace serves, e.g. `snowflake`. */
33+
type: string
34+
/** The engine execute tool the model should call, e.g.
35+
* `datamate_snowflake_execute_database_query`. */
36+
modelKey: string
37+
}
38+
39+
/**
40+
* The workspace-served execute tools for the types a FinOps operation supports, if
41+
* the session is bound to a workspace that serves any. Reads the session's precedence
42+
* snapshot only — the same reachability-filtered projection the awareness section
43+
* uses, so this never names a tool the caller's agent cannot call.
44+
*/
45+
export function workspaceFallbacks(sessionID: string, supportedTypes: readonly string[]): WorkspaceFallback[] {
46+
const precedence = Precedence.forSession(sessionID)
47+
if (!precedence?.enabled) return []
48+
return Precedence.servedInventory(precedence).flatMap(({ type, served }) => {
49+
if (!supportedTypes.includes(type)) return []
50+
const execute = served.find((row) => row.capability === "sql_execute")
51+
return execute ? [{ workspaceName: precedence.workspaceName, type, modelKey: execute.modelKey }] : []
52+
})
53+
}
54+
55+
/** The sentence appended to a FinOps failure, or nothing when the workspace serves
56+
* none of the operation's types — then the local error stands on its own. */
57+
export function workspaceFallbackNote(fallbacks: WorkspaceFallback[]): string | undefined {
58+
if (fallbacks.length === 0) return undefined
59+
const name = fallbacks[0].workspaceName
60+
const routes = fallbacks
61+
.map(({ type, modelKey }) => {
62+
const source = USAGE_SOURCE[type]
63+
return source ? `for ${type}, query ${source} with \`${modelKey}\`` : `for ${type}, use \`${modelKey}\``
64+
})
65+
.join("; ")
66+
return (
67+
`This tool only uses warehouse connections configured on this machine, and workspace "${name}" ` +
68+
`serves ${fallbacks.map((f) => f.type).join(", ")} through its integration engine instead. ` +
69+
`Run the same analysis through the workspace: ${routes}.`
70+
)
71+
}
72+
73+
/**
74+
* Attach the workspace note to a failed FinOps result. The failure text is kept — the
75+
* local reason may still be the one to fix — and the engine tool is stamped on the
76+
* metadata so telemetry can tell a failure the model could route around from a dead
77+
* end.
78+
*/
79+
export function withWorkspaceFallback<T extends { metadata: Record<string, unknown>; output: string }>(
80+
sessionID: string,
81+
supportedTypes: readonly string[],
82+
result: T,
83+
): T {
84+
const fallbacks = workspaceFallbacks(sessionID, supportedTypes)
85+
const note = workspaceFallbackNote(fallbacks)
86+
if (!note) return result
87+
return {
88+
...result,
89+
metadata: { ...result.metadata, workspace_fallback: fallbacks.map((f) => f.modelKey) },
90+
output: `${result.output}\n\n${note}`,
91+
}
92+
}

0 commit comments

Comments
 (0)