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.
Design · Explain the trade-offs
Changed constraints and integration decision
Objectives of this level: tenant/account scope and exact SQL/parameter ordering — Apply a changed constraint and scope the proposed platform adapter.
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.
Changed constraints and integration decision
Swap account_ids order to a2,a1; the exact compiled output must still sort a1,a2. Set end=start: ValueError:input_shape. Write a separate grain counterexample with one100-cent balance and two transaction rows, showing why JOIN then SUM could produce200 instead of100; propose an aggregate/existence solution and an actual execution validation plan, marked unexecuted here. Deliver a new-input JSON/result pair, an adapter boundary sketch and a short ADR comparing two alternatives, rejection/reconciliation behavior, ownership and reversal conditions. State implemented_local versus planned; connect to the same after-sales proposal/approval/merchant/receipt chain without inventing existing runtime features. Save the following block as text_to_sql_guardrails_variants.py beside your student module, then run it after implementation. It imports your own function, reads the public complete inputs and changes the declared fields; these two rule-visible variants are not unseen assessment.
import copy, json
from pathlib import Path
from text_to_sql_guardrails_student import compile_query
checks = json.loads(Path("cases/text-to-sql-guardrails.json").read_text())["checks"]
payload = copy.deepcopy(checks[1]["input"])
payload["intent"]["account_ids"] = ["a2", "a1"]
before = copy.deepcopy(payload)
try:
actual = compile_query(payload)
except ValueError as exc:
actual = "ValueError:" + str(exc)
assert payload == before, "input_mutation"
expected = {'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 ?', 'params': ['acme', 'a1', 'a2', 'CNY', 100, 200, 10]}
assert actual == expected, (actual, expected)
print(json.dumps({"variant":1,"input":payload,"actual":actual}, sort_keys=True))
payload = copy.deepcopy(checks[0]["input"])
payload["intent"]["end"] = payload["intent"]["start"]
before = copy.deepcopy(payload)
try:
actual = compile_query(payload)
except ValueError as exc:
actual = "ValueError:" + str(exc)
assert payload == before, "input_mutation"
expected = 'ValueError:input_shape'
assert actual == expected, (actual, expected)
print(json.dumps({"variant":2,"input":payload,"actual":actual}, sort_keys=True))
python3 text_to_sql_guardrails_variants.py
After your own compiler passes, this separate standard-library probe executes its current graded sql/params against a fixed local SQLite ledger. Its declared controls are single-account450, two-account1150, and authorized quoted-ID250 integer cents, plus denied DELETE under read-only/authorizer boundaries. Supply the actual grade report; do not substitute a self-written passed flag. Reports are editable and are not tamper-proof provenance. Inspect sqlite-report.json and preserve both hashes. LIMIT constrains aggregate output rows, not the work scanned by SUM. This authored SQLite fixture does not verify production RLS, role permissions, model SQL quality or throughput. https://ai.lwkjob.com/lab/extended-practice/sqlite_probe.py
python3 lab_runner.py grade --course text-to-sql-guardrails --module text_to_sql_guardrails_student.py --out report.json
python3 sqlite_probe.py --report report.json --out sqlite-report.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
Changed constraints and integration decision — 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 — Execute the declared changed inputs and deliver result pairs plus an adapter/ADR with implemented versus planned boundaries.
Reading this browser’s record…
Hide the answer and check your understanding
Does aggregate LIMIT10 prove bounded query cost?
Expand reference derivation
No. Scanning/aggregation may still be expensive; execution-level limits and workload validation are required.
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.