Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Definitions, granularity, and execution boundaries in natural-language queries

Examine the semantic layer, controlled SQL, read-only execution, and result review.

Learning objectives: 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.

Content checked: 2026-10-03 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Foundation · Understand the concepts. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

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
  1. Does SELECT have no side effects?

    Move from syntax restrictions to the database's actual execution capabilities.

  2. How to diagnose the amount doubled after JOIN?

    Use duplicated numbers to expose a query-granularity problem rather than a syntax problem.

  3. Are the accounts of CMB Chongqing Branch and all CMB accounts in Chongqing the same?

    Similar entity names still require preserving their business definitions.

Foundation · Understand the concepts

Mechanism before code

Objectives of this level: tenant/account scope and exact SQL/parameter ordering — Derive eligibility and the exact branch order from concrete inputs.

Visual guide · Runnable SQL is one boundary

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.

Mechanism before code

For the after-sales return ledger, first define a net-return amount at one ledger-event grain. Positive and reversal events use signed integer cents. The exercise compiles one controlled SQLite-placeholder query; it never accepts model SQL or executes a database. Parameter binding separates values from SQL structure, while access control and least privilege remain separate. OWASP SQL injection guidance.

An account ID containing a quote is still a value if authorized and bound. The application chooses the table/columns/template, not a model identifier. LIMIT on an aggregate does not bound scanned work. Real execution additionally needs roles, read-only/function boundaries, timeout and consistent snapshots; PostgreSQL owners/superusers/BYPASSRLS can bypass RLS under its documented rules. PostgreSQL row security. Write a branch trace for the three inputs and create one additional legal/negative input yourself before completing the function.

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

Mechanism before code — single-account

Additional review: explain why this case follows the contract and which single-field change would alter the branch. Public case: single-account 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 ?"} 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 — Submit three branch traces and two personal payloads; distinguish trusted fixture fields from client/model data.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Is an authorized quoted account automatically an injection?

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.