Skip to content

Commit 6ab901f

Browse files
fix(workspace): materialisation is owned by the engine's client; an unreadable link is unknown, not unbound
- Engine tools are recognised by the MCP client that served them, not by the `datamate_` prefix alone: `MCP.tools()` stamps every entry with its client, and another server named e.g. `datamate_snowflake` flattens to the same key shape. Such keys confer no precedence and are reported once per session. - The binding is read through the strict reader: a cache or credentials file that is present but unreadable settles `binding-unreadable`, which `check()` reports as undetermined with the reason, and which invalidates a routed snapshot for that reason rather than as a re-link. - A derivation that throws settles `derive-failed` — local execution with a stated reason — instead of failing the turn's tool resolution. - The re-link guard runs only when a redirect is about to be returned; a call that runs locally regardless does not pay for the binding read. - A superseded dbt-adapter attempt returns its result but no longer publishes it over the newer attempt's cache, and `tryExecuteViaDbt` executes on the adapter it was handed rather than re-reading the mutable global. - The drift warning covers every warehouse capability shape, not only execute. - `schema_inspect` validates its inputs before consulting precedence, as `sql_explain` does, through a shared `input-validation` module. - The guard-order test restores `ALTIMATE_INTEGRATIONS` it deletes.
1 parent ae3fd15 commit 6ab901f

10 files changed

Lines changed: 359 additions & 67 deletions

File tree

‎packages/opencode/src/altimate/native/connections/register.ts‎

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,11 @@ export const dbtAdapterInternals: {
5757
readConfig?: () => Promise<unknown>
5858
/** Adapter creation attempts since the last reset — what single-flight bounds. */
5959
attempts: number
60+
/** Cache writes since the last reset: only the attempt that owns the slot writes. */
61+
writes: number
6062
/** Whether an attempt is currently in flight. */
6163
inflight: () => boolean
62-
} = { attempts: 0, inflight: () => dbtAdapterInflight !== undefined }
64+
} = { attempts: 0, writes: 0, inflight: () => dbtAdapterInflight !== undefined }
6365

6466
/**
6567
* Resolve the dbt adapter for this project, or null when there is no usable dbt
@@ -73,6 +75,16 @@ async function ensureDbtAdapter(): Promise<any | null> {
7375
// lets a second attempt start, and the first one's settle must not clear the second's
7476
// slot — that would hand the next caller a third adapter behind the second's back.
7577
let mine: Promise<any | null> | undefined
78+
// Likewise the cache: a superseded attempt returns its result to the callers that
79+
// awaited it but must not publish it, or it would overwrite what the newer attempt
80+
// stored. Every write goes through here.
81+
const publish = (value: any | null): any | null => {
82+
if (dbtAdapterInflight === mine) {
83+
dbtAdapter = value
84+
dbtAdapterInternals.writes += 1
85+
}
86+
return value
87+
}
7688
mine = (async () => {
7789
dbtAdapterInternals.attempts += 1
7890
try {
@@ -83,29 +95,23 @@ async function ensureDbtAdapter(): Promise<any | null> {
8395
const dbtConfig = dbtAdapterInternals.readConfig
8496
? ((await dbtAdapterInternals.readConfig()) as Awaited<ReturnType<typeof readDbtConfig>>)
8597
: await readDbtConfig()
86-
if (!dbtConfig) {
87-
dbtAdapter = null
88-
return null
89-
}
98+
if (!dbtConfig) return publish(null)
9099

91100
// Check if dbt_project.yml exists
92101
const fs = await import("fs")
93102
const path = await import("path")
94103
if (
95104
!fs.existsSync(path.join(dbtConfig.projectRoot, "dbt_project.yml"))
96105
) {
97-
dbtAdapter = null
98-
return null
106+
return publish(null)
99107
}
100108

101109
// Create the adapter
102110
const { create } = await import("../../../../../dbt-tools/src/adapter")
103-
dbtAdapter = await create(dbtConfig)
104-
return dbtAdapter
111+
return publish(await create(dbtConfig))
105112
} catch {
106113
// dbt-tools not available or config invalid — fall back to native
107-
dbtAdapter = null
108-
return null
114+
return publish(null)
109115
} finally {
110116
if (dbtAdapterInflight === mine) dbtAdapterInflight = undefined
111117
}
@@ -199,14 +205,16 @@ async function tryExecuteViaDbt(
199205
sql: string,
200206
limit?: number,
201207
): Promise<SqlExecuteResult | null> {
202-
// altimate_change start — share the single-flight creation path with resolveDefaultTarget
203-
if (!(await ensureDbtAdapter())) return null
208+
// altimate_change start — share the single-flight creation path with resolveDefaultTarget;
209+
// execute on the adapter this call was handed, not on a global a reset may have moved.
210+
const adapter = await ensureDbtAdapter()
211+
if (!adapter) return null
204212
// altimate_change end
205213

206214
try {
207215
const raw = limit
208-
? await dbtAdapter.immediatelyExecuteSQLWithLimit(sql, "", limit)
209-
: await dbtAdapter.immediatelyExecuteSQL(sql, "")
216+
? await adapter.immediatelyExecuteSQLWithLimit(sql, "", limit)
217+
: await adapter.immediatelyExecuteSQL(sql, "")
210218

211219
// QueryExecutionResult has: { columnNames, columnTypes, data, rawSql, compiledSql }
212220
// where data is Record<string, unknown>[] (array of row objects)
@@ -263,6 +271,7 @@ export function resetDbtAdapter(): void {
263271
// would still receive the previous adapter.
264272
dbtAdapterInflight = undefined
265273
dbtAdapterInternals.attempts = 0
274+
dbtAdapterInternals.writes = 0
266275
}
267276

268277
// ---------------------------------------------------------------------------
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// altimate_change - new file
2+
//
3+
// Pre-flight input checks shared by the warehouse tools. They run BEFORE workspace
4+
// precedence is consulted: a redirect must never forward malformed input to the
5+
// engine tool, and an empty or placeholder warehouse name must not be read as
6+
// "use the default" by the routing decision.
7+
8+
/** Warehouse names that models produce by mistake: empty strings and unsubstituted
9+
* placeholders. Both would otherwise fall through to unhelpful registry errors. */
10+
export function validateWarehouseName(warehouse: string | undefined): string | null {
11+
if (warehouse === undefined) return null
12+
if (typeof warehouse !== "string") {
13+
return "warehouse must be a string"
14+
}
15+
const trimmed = warehouse.trim()
16+
if (trimmed.length === 0) {
17+
return "warehouse is an empty string — omit the parameter to use the default warehouse, or pass a configured connection name"
18+
}
19+
if (/^[?$:@]/.test(trimmed)) {
20+
return (
21+
"warehouse name looks like an unsubstituted placeholder (" +
22+
JSON.stringify(trimmed) +
23+
"). Use `warehouse_list` to see configured warehouses."
24+
)
25+
}
26+
return null
27+
}
28+
29+
/** Table names get the same two checks; the schema tool has nothing to inspect otherwise. */
30+
export function validateTableName(table: unknown): string | null {
31+
if (typeof table !== "string" || table.trim().length === 0) {
32+
return "table is required — pass a table name, optionally schema-qualified"
33+
}
34+
if (/^[?$:@]/.test(table.trim())) {
35+
return "table name looks like an unsubstituted placeholder (" + JSON.stringify(table.trim()) + ")"
36+
}
37+
return null
38+
}

‎packages/opencode/src/altimate/tools/schema-inspect.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { SchemaInspectResult } from "../native/types"
66
import { PostConnectSuggestions } from "./post-connect-suggestions"
77
// altimate_change end
88
import { isRecord, normalizeError } from "./response-normalization"
9+
import { validateTableName, validateWarehouseName } from "./input-validation"
910
// altimate_change start — workspace precedence
1011
import * as Precedence from "../workspace/precedence"
1112
// altimate_change end
@@ -18,6 +19,17 @@ export const SchemaInspectTool = Tool.define("schema_inspect", {
1819
warehouse: z.string().optional().describe("Warehouse connection name"),
1920
}),
2021
async execute(args, ctx) {
22+
// Pre-flight validation outranks the redirect, as it does for `sql_explain`: bad
23+
// input is answered here rather than forwarded to the engine tool, and an empty
24+
// warehouse string is never read as "the default" by the routing decision.
25+
const inputError = validateTableName(args.table) ?? validateWarehouseName(args.warehouse)
26+
if (inputError) {
27+
return {
28+
title: "Schema: INVALID INPUT",
29+
metadata: { success: false, columnCount: 0, rowCount: undefined, error: inputError, error_class: "input_validation" },
30+
output: `Invalid input: ${inputError}`,
31+
}
32+
}
2133
// altimate_change start — workspace precedence
2234
const precedence = await Precedence.check(ctx.sessionID, "schema_inspect", args.warehouse)
2335
if (precedence.redirect) return precedence.redirect

‎packages/opencode/src/altimate/tools/sql-explain.ts‎

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type { SqlExplainResult } from "../native/types"
55
// altimate_change start — workspace precedence
66
import * as Precedence from "../workspace/precedence"
77
// altimate_change end
8+
import { validateWarehouseName } from "./input-validation"
89

910
/**
1011
* Detect SQL input that cannot be meaningfully EXPLAIN'd.
@@ -48,31 +49,6 @@ function validateSqlInput(sql: unknown): string | null {
4849
return null
4950
}
5051

51-
/**
52-
* Validate a warehouse name supplied by the caller.
53-
*
54-
* Empty strings and placeholder tokens slip through the optional-parameter
55-
* contract and produce unhelpful "Connection X not found" errors from the
56-
* Registry. Catch these here with a pointer to `warehouse_list`.
57-
*/
58-
function validateWarehouseName(warehouse: string | undefined): string | null {
59-
if (warehouse === undefined) return null
60-
if (typeof warehouse !== "string") {
61-
return "warehouse must be a string"
62-
}
63-
const trimmed = warehouse.trim()
64-
if (trimmed.length === 0) {
65-
return "warehouse is an empty string — omit the parameter to use the default warehouse, or pass a configured connection name"
66-
}
67-
if (/^[?$:@]/.test(trimmed)) {
68-
return (
69-
"warehouse name looks like an unsubstituted placeholder (" +
70-
JSON.stringify(trimmed) +
71-
"). Use `warehouse_list` to see configured warehouses."
72-
)
73-
}
74-
return null
75-
}
7652

7753
export const SqlExplainTool = Tool.define("sql_explain", {
7854
description:

‎packages/opencode/src/altimate/workspace/engine-types.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,12 +137,29 @@ export function clearsFloor(version: string | null): boolean {
137137
/** Strip the server prefix from the engine tools present in the catalog. */
138138
export function engineToolKeys(tools: Record<string, unknown>): Set<string> {
139139
const out = new Set<string>()
140-
for (const key of Object.keys(tools)) {
141-
if (key.startsWith(TOOL_PREFIX)) out.add(key.slice(TOOL_PREFIX.length))
140+
for (const [key, value] of Object.entries(tools)) {
141+
if (!key.startsWith(TOOL_PREFIX) || servedByForeignClient(value)) continue
142+
out.add(key.slice(TOOL_PREFIX.length))
142143
}
143144
return out
144145
}
145146

147+
/** Engine-shaped keys another MCP client owns: worth a warning, never precedence. */
148+
export function foreignEngineKeys(tools: Record<string, unknown>): string[] {
149+
return Object.entries(tools)
150+
.filter(([key, value]) => key.startsWith(TOOL_PREFIX) && servedByForeignClient(value))
151+
.map(([key]) => key)
152+
}
153+
154+
/** `MCP.tools()` stamps every entry with the client that served it. A foreign server
155+
* named e.g. `datamate_snowflake` flattens to the same `datamate_*` shape as the
156+
* engine's own tools, and only the stamp tells them apart. An entry without a stamp
157+
* (a synthetic map) is taken by prefix. */
158+
function servedByForeignClient(value: unknown): boolean {
159+
const client = (value as { client?: unknown } | null)?.client
160+
return typeof client === "string" && client !== DATAMATE_KEY
161+
}
162+
146163
/** The entry's full argv, flattening both config shapes. */
147164
export function commandArgv(entry: EntryLike | null): string[] {
148165
if (!entry) return []

0 commit comments

Comments
 (0)