fix: explain why `sql_execute` refuses a query as a write, and stop misreading qualified columns

AN
4h ago
+1534-85

Issue for this PR

Closes #1810

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

Before → after, for every model and every warehouse:

Query, write permission deniedBeforeAfter
Unparseable SQL (e.g. unquoted Order Date)refused, raw rule dumprefused; names the parser's position and error kind; fix the syntax
A read with shell syntax (... 2>/dev/null LIMIT 5, `head -20`)refused, rule dump
SELECT 1; DELETE FROM trefused, rule dumprefused; "statement 2 of 2 is not a read (DELETE)"
A write denied by a pattern rule ("DROP*": "deny")refused, rule dumprefused; says a rule denies it, not that the agent is read-only
SELECT * FROM t WHERE note = 'don't truncate'"blocked for safety"refused; the quote is open, write it as ''
SELECT t.update, s.t.delete FROM ...writeread (not ClickHouse)
CREATE TABLE scratch.x AS ... on the scratch warehouseasked for write permissionruns like other scratch writes

Why: in long real sessions an agent without write permission had 110 sql_execute calls refused; 94 of the 102 distinct queries were SQL the engine rejects. Refusing them was right, but the agent never learned why, so it retried or stalled.

How:

  • explainWrite (sql-classify.ts) names why a query counts as a write: shell residue, an open quote, the parser error (position and kind only), or the first writing statement. sql_execute rethrows only the rule-denial error with that reason, worded for a read-only agent or a pattern rule; other errors, including a user's rejection, pass through.
  • Shell residue is reported, never stripped: running SQL other than what was sent is worse than one extra turn, and >/| are SQL operators. Detection uses anchored patterns only.
  • sql_check, query_from, sql_materialize, data_diff and the MCP workspace refusals append the same reason; hard-block errors name the matched rule (or the open quote that made a word count).
  • Refusals quote no user SQL (telemetry records tool errors); their error class is permission, or parse_error for unreadable SQL (unknown on main).
  • Unquoted dotted names (t.update, s.t.update) are columns, except on ClickHouse (a lookbehind after the parse). Not verified live: SQL Server rejecting a.b.UPDATE at compile time. SELECT 1. INTO t, 0x1.INTO and quoted qualifiers ("t".update, with a hint) stay writes. SQL Server's XML .query() is a read; on ClickHouse a 2>/dev/null-style redirect is named, not run.
  • Deliberate widening: scratch.t and scratch.main.t count as local (the catalog is the session's own scratch.duckdb).

Still blocked (negative tests, 11 dialects): INSERT/UPDATE/DELETE/MERGE, DDL, COPY INTO, a write after a read, a write after ; on one line, a write CTE, SELECT INTO (including after 1.), unparseable text, and a write with shell residue.

Sweep: every read/write decision (sql_check, sql_materialize, sql_explain, data_diff, MCP workspace, tool CLI) goes through classifyAndCheck. Drivers use a prefix only for a default LIMIT; SQLite also routes on it (#1819).

Dependency: none to pass. This PR is green on the current engine. https://github.com/AltimateAI/altimate-core-internal/pull/789 makes three more valid reads parse (AS both, a table alias last, len(DISTINCT f(...))); until a core release and the pin bump (#1816) they stay refused, with the parser's reason. Either merge order works.

How did you verify your code works?

  • New sql-readonly-guard.test.ts and sql-readonly-guard-explain.test.ts, plus refusal assertions in the materialize and MCP workspace tests. On origin/main (c00b2dc) the qualified-column, scratch-prefix and denial-message tests fail; the other read classes (comments, literals, update_ts, CTEs, EXPLAIN/SHOW/PRAGMA, two reads, whitespace, parentheses) already passed and stay as regressions.
  • SQL tool, MCP workspace, tool CLI, data_diff and release adversarial suites pass (2209 tests); typecheck clean; no markers needed (files not in v1.18.34).
  • Replayed 102 real refusals: 2 run on scratch; 100 get a reason.
  • Local review each push (last: 14e92f7e67, no P0–P2) and one independent review; valid findings fixed; fail-closed wording declined. CI: TypeScript (2/4) failed once at da71cbaf64 in control-plane/workspace.test.ts (not ours); 5/5 local, green since.

Cost side effects

None. Classification is local; the reason is computed only when a write is refused.

Screenshots / recordings

N/A, no UI.

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR
  • I checked for cost side effects (model calls, queries or cloud resources that grow with user data) and described them, or wrote "none"

🤖 Generated with Claude Code


[!NOTE]
Medium Risk
Changes core SQL permission and classification paths used by agents, CLI, MCP workspace, and data-diff; misclassification could block valid reads or weaken explanations, but behavior is heavily test-covered.

Overview
When sql_execute or related paths refuse a query as a write or under sql_execute_write, errors now include actionable reasons (which statement writes, parser position, shell fragments like 2>/dev/null, Jinja/dbt, or hard-block rules) instead of a bare permission rule dump. Tool CLI and --allow-write refusals append the same explanation before the retry hint.

The SQL classifier explainWrite / writeReason centralize those messages; sql_execute rebuilds denials via deniedWriteMessage (read-only agent vs pattern deny vs CLI), including allowed rule patterns when relevant. Hard-block refusals name the matched rule without echoing user SQL.

Classification fixes: unquoted dotted names such as t.update / s.t.update are treated as column references (reads), not write keywords—ClickHouse stays stricter. Scratch DuckDB targets under scratch.* / scratch.main.* count as local safe writes.

Docs describe how sql_execute_write classifies SQL and what agents see on deny.

Reviewed by Cursor Bugbot for commit 77469155ab6b880ee21306ec0b04da139096114c. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • New Features
    • SQL read-only refusals explain why a query was blocked, including unreadable SQL, write operations, or shell command fragments. Multi-statement errors identify the statement that triggered the refusal.
    • Write-permission denials provide tailored explanations and next steps for cases such as Jinja, scratch operations, and unavailable SQL dialects.
  • Bug Fixes
    • SQL write checks better distinguish qualified identifiers from write keywords across supported dialects.
  • Documentation
    • Added guidance on SQL write-permission classification and the information shown when a query is denied.