Review the prerequisites
Suitable for: Backend developers learning Agent applications.
- Definitions, granularity, and execution boundaries in natural-language queries
- SQL runnability only proves that the syntax and execution are true; the correct answer also requires that the entity, granularity, time and permissions match the user's intent. Security constraints and business semantics must be verified separately.
How does the mechanism work?
Step-by-step explanation
- Does SELECT have no side effects?
Move from syntax restrictions to the database's actual execution capabilities.
- How to diagnose the amount doubled after JOIN?
Use duplicated numbers to expose a query-granularity problem rather than a syntax problem.
- Are the accounts of CMB Chongqing Branch and all CMB accounts in Chongqing the same?
Similar entity names still require preserving their business definitions.
Debugging · Diagnose failures
Public repair exercise: same inputs
Objectives of this level: tenant/account scope and exact SQL/parameter ordering — Locate the supplied fault and repair a copy on unchanged input.
Visual guide · Runnable SQL is one boundary
The compiler emits a governed query and bound values. Execution needs its own controls; correct syntax does not prove entity, grain, time or metric meaning. Select the figure to open it at full size.
Public repair exercise: same inputs
Run the quoted-id-is-value and foreign-account cases against the known string-concatenating function. Inspect sql and params together: a plausible SQL string with params=[] is the first divergence, and omitting the tenant/account boundary is another fault. Restore a constant governed structure with bound values and current scope checks; do not remove the quote from the test. This is guided_repair: the faulty category is supplied. Save the function below in a separate text_to_sql_guardrails_debug.py. Before consulting a repair, submit the first divergent input/field, two hypotheses and a discriminating check. Repair this copy, save your diff and rerun the identical cases; keep the original cases file unchanged.
def compile_query(payload):
# Known fault: creates SQL syntax from an account value.
account = payload["intent"]["account_ids"][0]
return {"sql": "SELECT SUM(amount_cents) FROM return_ledger WHERE account_id = '" + account + "'", "params": []}
python3 lab_runner.py grade --course text-to-sql-guardrails --module text_to_sql_guardrails_debug.py --out text_to_sql_guardrails_debug_before.json
python3 lab_runner.py grade --course text-to-sql-guardrails --module text_to_sql_guardrails_debug.py --out text_to_sql_guardrails_debug_after.json
Starting point and evidence
Download the source-only ZIP, extract it, and work in extended-agent-practice-v1 with lab_runner.py beside cases/. Python3.9+ standard library; no model, cloud, network or business request is made. Scaffold once in a fresh directory; it refuses overwrite. Reuse your module in later tracks. The empty template must exit1 on grade; scaffold exits0, overwrite exits2. Grade exits0 only when every fixed case passes and otherwise exits1.
- https://ai.lwkjob.com/downloads/extended-agent-practice-v1.zip
- https://ai.lwkjob.com/lab/extended-practice/lab_runner.py
- https://ai.lwkjob.com/lab/extended-practice/cases/text-to-sql-guardrails.json
python3 lab_runner.py scaffold --course text-to-sql-guardrails --out text_to_sql_guardrails_student.py
python3 lab_runner.py grade --course text-to-sql-guardrails --module text_to_sql_guardrails_student.py --out text_to_sql_guardrails_before.json
This course has12 public fixed cases. Each calls your compile_query(payload), records input/expected/actual/error, strict JSON types, input immutability and no output-container aliases, plus module/runner/cases SHA and Python version. Inputs are complete JSON fixtures. Unknown or missing keys, null outside explicitly allowed fields, wrong types, duplicate IDs/list members where uniqueness is required raise ValueError:input_shape; booleans are not integers. Exceptions match exact class:message. Return fresh JSON values without mutating input.
Trusted identity, approvals, receipts and policy/index metadata are fixtures assembled by the exercise. In a real service the server must obtain them from authenticated/current authority sources; accepting client JSON with these labels does not authenticate it. The function is a decision over that trusted snapshot, not the adapter or race-proof enforcement.
Local function contract
payload exactly principal/intent/limit. principal={tenant:nonempty str,enabled:strict bool,allowed_accounts:unique nonempty str list}. intent={metric:nonempty str,currency:nonempty str,start:strict nonnegative int,end:strict nonnegative int greater than start,account_ids:unique nonempty str list}. Both account lists may be empty. limit is strict int1..100. Shape failure precedes all semantic errors. Then raise ValueError with principal_disabled,metric_not_supported(unless net_return_cents),currency_not_supported(unless CNY/USD),scope_empty(empty requested accounts),account_scope(any account outside trusted allowed_accounts), in that order. Sort selected account IDs lexically. Return exactly sql/params with the template demonstrated below: placeholders count equals accounts count, tenant comes from principal, followed by sorted accounts,currency,start,end,limit. The time window is [start,end). Empty data would aggregate to0 only if this SQL were actually run; compilation is not a database result.
def compile_query(payload):
raise NotImplementedError("Implement the public local contract")
Three reviewable inputs
single-account
{
"principal": {
"tenant": "acme",
"enabled": true,
"allowed_accounts": [
"a1",
"a2",
"x' OR 1=1 --"
]
},
"intent": {
"metric": "net_return_cents",
"currency": "CNY",
"start": 100,
"end": 200,
"account_ids": [
"a1"
]
},
"limit": 10
}
Expected / 预期: {"params": ["acme", "a1", "CNY", 100, 200, 10], "sql": "SELECT COALESCE(SUM(amount_cents), 0) AS net_return_cents FROM return_ledger WHERE tenant = ? AND account_id IN (?) AND currency = ? AND event_time >= ? AND event_time < ? LIMIT ?"}
quoted-id-is-value
{
"principal": {
"tenant": "acme",
"enabled": true,
"allowed_accounts": [
"a1",
"a2",
"x' OR 1=1 --"
]
},
"intent": {
"metric": "net_return_cents",
"currency": "CNY",
"start": 100,
"end": 200,
"account_ids": [
"x' OR 1=1 --"
]
},
"limit": 10
}
Expected / 预期: {"params": ["acme", "x' OR 1=1 --", "CNY", 100, 200, 10], "sql": "SELECT COALESCE(SUM(amount_cents), 0) AS net_return_cents FROM return_ledger WHERE tenant = ? AND account_id IN (?) AND currency = ? AND event_time >= ? AND event_time < ? LIMIT ?"}
foreign-account
{
"principal": {
"tenant": "acme",
"enabled": true,
"allowed_accounts": [
"a1",
"a2",
"x' OR 1=1 --"
]
},
"intent": {
"metric": "net_return_cents",
"currency": "CNY",
"start": 100,
"end": 200,
"account_ids": [
"other"
]
},
"limit": 10
}
Expected / 预期: ValueError:account_scope
Responsibility and limits
Junior delivers a controlled parameter plan and quote/scope cases. Intermediate would connect an authorized report endpoint, row policy and execution limits and verify signed events/empty/failure semantics. Senior owns metric grain, consistency, privileged role/cache boundaries and failure-window ADRs. No actual DB role, query performance or financial correctness is certified by this compiler. The four tracks are learning activities, not job ranks. Fixed authored examples and known repairs cannot prove independent diagnosis, real-world security or hiring readiness. Keep source, initial failure, personal diff, same-input rerun and a declared changed-condition result. A reviewer-new complete contract and observed personal work are separate; disclose assistance. The five-second worker guard is not a performance SLO or hostile-code sandbox.
code example
Public repair exercise: same inputs — foreign-account
Additional review: explain why this case follows the contract and which single-field change would alter the branch. Public case: foreign-account Expected / 预期: ValueError:account_scope https://ai.lwkjob.com/lab/extended-practice/cases/text-to-sql-guardrails.json
Acceptance task for this level
tenant/account scope and exact SQL/parameter ordering — Run the supplied faulty copy, record a first divergence and two hypotheses, then repair it with a personal diff and the unchanged-case rerun.
Reading this browser’s record…
Hide the answer and check your understanding
Why inspect params alongside sql?
Expand reference derivation
An interpolated string may look runnable while losing value/structure separation and scope.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
All linked explanations and exercises (1 )
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.