Constrained actions instead of raw SQL
Have the model emit one JSON action over handles issued for this request, constrain decoding to that schema, and compile it yourself into parameterised SQL.
Have the model emit one JSON action over handles issued for this request, constrain decoding to that schema, and compile it yourself into parameterised SQL.
An agent plans the query; a Rust engine with no model computes each figure and returns a certificate tracing it to the records, checking access on every read.
Use classic RAG when the evidence sits in one place; add an agent loop when it is spread across documents or needs tools. Most systems route between the two.
A recurring report. A slow review. A prototype that needs to work in the real world.
Where you can, don't let the model write SQL. On the Company Twin's governed path, the model asks for typed records or figures from approved data products and never writes a query at all. On the exploratory path, capable models still write SQL behind a parser, a read-only transaction and a row limit. Open-ended analysis needs a full query language, and a guard is a sensible boundary for a model that writes SQL cleanly. What we built here targets the awkward middle case: a small private model that needs open-ended queries, yet can't be trusted with raw SQL. Instead, the model emits one compact JSON action where every table, column and value is a short handle issued for that turn; decoding is masked to a schema built from those handles; and our own compiler turns the action into parameterised SQL for a read-only broker. Malformed or unauthorised queries become inexpressible rather than caught after the fact.
This is RFQ2, the second query language we built in Project Venus, our open-weight model research, following building a relation-first query language (RFQ1). To be upfront about status: the contract is locked and verified on reference cases, it hasn't been trained at scale or deployed, and the work is currently paused.
Key takeaways
The standard pattern is to let a model write SQL and guard it afterwards: parse the statement, allow only SELECT, verify the tables, tack on a row limit and run inside a read-only transaction. We do exactly that on the Twin's exploratory path, and for a capable model it holds up well; we wrote up how in letting an LLM write SQL safely.
Two snags remain. First, the model still chooses everything your guard has to police: real table names, literal values, dialect quirks and any function SQL exposes. Every guard turns into a denylist over a huge language. Second, and sharper for small models, is plain reliability. Small open models writing free-form SQL hallucinate column names, mangle syntax and mistype long identifiers. Filtering catches those after the tokens are already spent, and the model gets no help avoiding them while generating.
Constrained decoding hits both problems at once. If the model can only emit tokens that continue a valid action, and that action can only refer to handles the system issued, there isn't much left to filter.
RFQ1 was a relation-first query language written as compact prefix text, with ten fixed clauses and a grammar that could, in theory, be enforced by token masking. Once we actually ran it, three cracks opened up.
rel_ or col_ followed by 24 hex characters. Models copied them wrongly.When I audited 30 real queries, I didn't find a single remaining failure of the language itself. I found translator bugs (case-insensitive matching and aggregate filters), lost replay evidence, poorly framed historical questions, data-catalogue gaps and presentation work. That pointed straight to the fix: keep the typed relational core, and rebuild the contract around it so it's shorter, explicit and directly enforceable.
| RFQ1 | RFQ2 | |
|---|---|---|
| What the model writes | Handwritten prefix text | One canonical JSON action |
| What training and runtime use | A different internal form | The same RFQ2 object |
| Handles | rel_ or col_ plus 24 hex characters | Session-local r1, c1, v1 |
| Values | Bounded literal strings in the text | Typed, issued value handles |
| Constrained decoding | Not available on the teacher path | A JSON Schema built for each turn |
| Semantics | Some conventions hidden in the generator | Explicit aliases, grouping, ordering and page bound |
| Execution | Compiler and read-only broker | Compiler and read-only broker |
Every completion is exactly one of four actions:
A query object always carries the same 11 fields in a fixed order, writing out empty clauses rather than dropping them: common table expressions, source, joins, filter, grouping, having, selected expressions, distinct, set operations, ordering and a page. Expressions are compact tagged arrays, keeping outputs tight without inventing a second text syntax to parse. Here's a full query, minus the contract version:
{ "action": "warehouse_query", "arguments": { "query": { "with": [], "from": { "scan": "r1", "as": "o" }, "joins": [], "where": ["op", "eq", ["col", "o", "c3"], ["param", "v1"]], "group_by": { "mode": "plain", "keys": [["col", "o", "c5"]] }, "having": null, "select": [ { "as": "currency", "expr": ["col", "o", "c5"] }, { "as": "order_count", "expr": ["agg", "count", [], { "distinct": false, "filter": null, "order_by": [] }] }, { "as": "total_value", "expr": ["agg", "sum", [["col", "o", "c4"]], { "distinct": false, "filter": null, "order_by": [] }] } ], "distinct": { "mode": "none" }, "set_ops": [], "order_by": [{ "expr": ["col", "o", "c5"], "direction": "asc", "nulls": null }], "page": { "limit": 200, "offset": 0 } } }}Earlier receipts in that turn told the model that r1 is the orders table, c3 its status, c4 an amount, c5 the currency, and v1 the value "completed" pulled from the request. The model never sees real mixed-case table or column names, and never types the literal itself. It groups by currency too, because the contract requires monetary totals to stay split by currency rather than summed across them.
For each turn, the system builds a JSON Schema strictly from the handles issued so far. Relation, column and value handles become enumerations of those exact strings. Every object is closed, so stray fields can't appear. Expressions are fixed-length tuples starting with a tag from a finite set, and the page limit has to be an integer between 1 and 200.
A grammar engine compiles that schema against the model's tokeniser. At every decoding step it works out which tokens can still lead to a valid action and forces every other token's logit to negative infinity before sampling. We targeted XGrammar, which our serving engines already support for structured outputs.
The point isn't that the model was trying to misbehave; it's that a plausible wrong continuation, like a real table name remembered from training or a handle never issued this turn, simply isn't on the menu. On our first seed example, the schema came to 16,169 bytes and compiled to a native grammar against the Qwen tokeniser's 248,320-token vocabulary. That proved the grammar compiles cleanly; it loaded no model weights and says nothing about generation quality.
A JSON Schema only governs shape. It can't verify that a column handle actually belongs to the relation behind an alias, or that one aggregate isn't nested inside another. Those semantic checks live in our own compiler, sitting squarely in front of the database.
DISTINCT ON has to line up with the ordering.$1::text. No literal ever gets spliced into SQL text.From there, the compiled statement goes to the same read-only warehouse broker every other Twin query uses, enforcing organisation scope, a row cap, a statement timeout and a read-only transaction. Results come back as a size-capped receipt in the same turn, ready for the next action.
A small language is only safe when its omissions are intentional. RFQ2 leaves out raw SQL, data-changing statements, writable or recursive common table expressions, locking clauses, volatile functions and JSON-path access. Four less obvious cuts mattered just as much:
WITH TIES. It breaks the page size as a hard upper bound on returned rows.WITH across a set operation. The compiler rejects that combination until it can hoist the definitions properly, failing closed instead of guessing.We locked the contract on 13 August 2026, hashing the compiler, tests and specification so any breaking change requires a new version, a fresh replay against PostgreSQL and a new lock.
| Check | Result |
|---|---|
| Exact replay against PostgreSQL | 8 RFQ2 queries return exactly the same rows as hand-written reference SQL, covering mixed-case names, typed parameters, case-insensitive matching, aggregate filters, joins, currency partitioning, grouping sets, DISTINCT ON, windows, set operations and an unbounded intermediate result |
| Invalid queries rejected | 19 cases, including unissued handles, raw SQL fields, missing or oversized pages, incompatible types and wrong arity |
| Schema compiles for constrained decoding | Yes, under a pinned grammar engine and tokeniser; no model loaded |
| Independent reviews | 2 |
| Seed training examples | 5 records, reviewed as a format; scale generation not authorised |
Three big things remain unproved. We haven't measured what share of a real, weighted workload RFQ2 expresses; the right next check is a replay set separating source, discovery and presentation failures from language gaps. We haven't trained a model on it at scale. And the runtime admission check for return-to-base isn't deployed.
RFQ2 is on the shelf for now. Two weeks after the lock, we made serving our own open-weight models Project Venus's top priority so a pilot could run an unmodified base model without waiting for RFQ2 training data. September's adapter training used a compact action format over the Twin's existing guarded warehouse tools (where the model writes SQL) rather than RFQ2, and in late October we moved the small model onto a minimal reuse of an existing agent loop, still a candidate rather than a settled choice. RFQ2 data never went past those five seed examples.
Even paused, it paid off. The audit showed failures lived in translation and data rather than the language; short per-request handles and per-turn schemas turned out cheap to enforce; and a later architecture review still favoured governed programs with typed slots, in the spirit of RFQ2, over free SQL for runtime retrieval. If we train a small model for open-ended queries again, this contract is where I'd pick straight back up.
For numbers, the Twin now answers through a deterministic graph engine: the agent plans structured queries, and an engine with no model computes them and attaches a certificate tracing every figure back to its source records. We wrote up how that works in certified answers from a Rust graph engine. On that governed path, the model requests typed records or aggregates from an approved product and never supplies SQL at all.
RFQ2 applies the exact same split when a model does need to express an arbitrary relational query: the model proposes a structured program from a closed vocabulary, while deterministic code owns the real names, the values and the authority to execute it. If we train a small private model for exploratory analysis, that's the contract we'd build on, so the model's output and the system's guard are one and the same object.
If you're putting an agent in front of a database, first check how many of your questions can be served by approved, typed data products, taking model-written queries off the main path altogether. Where open-ended analysis genuinely is needed, design the action space before picking the model, and let a schema and compiler enforce the rules a prompt never will. Our comparison of RAG and agentic retrieval covers when an agent loop is worth the machinery, and our guide to effective prompting covers structured outputs on hosted models.
Designing a constrained action space
Models propose; deterministic code executes. See how the Company Twin keeps numbers certified and warehouse access read-only by construction. See governed queries in the Twin →
Further reading