AWSAWS Certified Generative AI Developer - Professional2026-103.1 Implement input and output safety controls
Approve generated SQL before Athena execution
Completed by the knowledge check
Learning objective
Validate generated SQL syntax, authorization, scope, and execution safety before running approved queries with Amazon Athena.
Core idea
Generated SQL is a proposed program, not an answer ready for execution. A statement can parse correctly while reading the wrong tenant, exposing restricted columns, scanning excessive data, or writing to an unexpected destination. The model’s explanation that a query is safe does not establish any of these properties.
Use separate gates for syntax, authorization, scope, and execution safety. Syntax establishes whether the statement has the intended structure. Authorization establishes whether the caller and execution identity may access the requested resources. Scope establishes whether the query fits the business question and permitted data boundary. Execution safety establishes whether the approved operation runs within controlled resources and output locations.
Bind approval to the exact query and execution context. If the model rewrites the SQL after approval, the approved program no longer exists. Store the proposed statement, validated representation, caller context, and policy decision together so a retry cannot turn approval of one query into permission for another.
How it works
Validate structure before engine submission
Parse the generated SQL using a parser compatible with the application’s supported Athena dialect. Inspect the parsed structure rather than searching for prohibited words. Comments, quoted identifiers, nested queries, and expressions can make substring checks misleading. For an analytics assistant, an application policy might permit one read-only SELECT statement and reject other statement types.
This is an application restriction, not an Athena restriction: Athena supports more than read-only analysis. Build a positive statement allowlist, inspect every referenced relation and expression, and reject unsupported syntax instead of delegating uncertainty to execution. Do not accept a schema-valid JSON field named SQL as proof that its contents are safe; see 3.1.4.
Athena’s EXPLAIN provides engine-side validation and planning. EXPLAIN (TYPE VALIDATE) validates the statement, while EXPLAIN (TYPE IO) provides information about tables and schemas read. Use these checks after the application has restricted the candidate’s structure and execution context.
EXPLAIN does not scan data, although it calls AWS Glue for metadata and can incur Glue charges above the free tier. EXPLAIN ANALYZE executes the query and scans data. It is therefore an execution and measurement mechanism, not a safe substitute for a pre-execution syntax gate. Choose it only after the query has passed the execution policy.
Enforce permissions and business scope
Athena query permissions span several systems. AWS documents permissions for Athena API actions, underlying Amazon S3 data locations, and AWS Glue Data Catalog metadata. Giving the application athena:StartQueryExecution alone neither grants all required data access nor proves that the end user is entitled to the result.
For data and metadata registered with AWS Lake Formation, enforce table and column scope for the execution identity through Lake Formation permissions, in addition to the application check. These permissions do not protect Athena query-result locations in S3; IAM policies for S3 control result access.
Use a least-privilege execution identity with access only to the approved resources. Separately validate the verified end-user context before accepting the model’s requested tables, columns, and tenant scope. A shared application role can have broader access than an individual user, so the application’s authorization decision cannot be replaced by the role’s successful query.
Resolve QueryExecutionContext.Catalog and Database from trusted configuration. Inspect qualified table names too: selecting a default database does not make every relation in the SQL belong to it. Derive required tenant predicates and permitted data ranges from authenticated context, not from an untrusted user phrase such as all accounts.
Scope includes meaning as well as permissions. A question about last month’s revenue should not become a lifetime scan because the generated filter is missing. Validate required dates, permitted joins, selected columns, and aggregation level against the request contract. If an acceptable query cannot be constructed, ask for the missing scope or decline; do not execute a broader interpretation for convenience.
EXPLAIN is useful evidence but not the authorization authority. AWS documents that Lake Formation row or cell filtering information is not shown in EXPLAIN output. A plan therefore cannot certify the complete effective data-access boundary. Keep the permission decision independent from the visible plan.
Constrain execution and results
StartQueryExecution accepts the approved QueryString, QueryExecutionContext, and WorkGroup. For approved WHERE predicates, bind trusted tenant and date values to ? placeholders through ExecutionParameters, which applies values in query order. Use a trusted workgroup rather than one chosen by generated content. Workgroup configuration can override client result settings through EnforceWorkGroupConfiguration. Fix the approved results location and encryption policy there so model output cannot select an arbitrary destination.
Set BytesScannedCutoffPerQuery to bound scanned data. AWS documents that the per-query usage control cancels a query that exceeds the configured limit. Workgroup-wide usage controls instead track aggregate usage over a period and can notify through Amazon SNS. An aggregate alert is not the same mechanism as per-query cancellation.
A returned QueryExecutionId means the query has been submitted, not that safe results are available. Use GetQueryExecution to inspect QueryExecution.Status.State; release only after successful completion and any required result checks. QUEUED and RUNNING are pending states; FAILED and CANCELLED are terminal failure outcomes. Track Statistics.DataScannedInBytes to compare actual work with your approved budget.
When the application deadline expires, call StopQueryExecution with the execution identifier and confirm the resulting state. Cancellation is not a promise of zero work or zero cost. AWS notes that failed or canceled queries can leave partial results in S3. Withhold them from the answer path and handle their cleanup under the results retention policy.
A returned execution identifier is only a submission: results are released only after successful completion, and a pending query is stopped when the application deadline expires.
For retries of the same approved submission, preserve ClientRequestToken. Athena returns the same execution identifier for a repeated token and rejects changes to parameters such as QueryString. This token provides submission idempotency, not authorization: AWS notes that a reused token can return the identifier even when the requester lacks permission on the referenced tables. Recheck the application’s caller binding before exposing execution information or results.
Key distinctions and trade-offs
Engine validation catches syntax and planning problems; application validation decides what programs are permitted. AWS permissions restrict resource access; business scope narrows what this request should do within that access. A correct aggregate over an unauthorized population fails both the security and meaning requirements.
A result row limit bounds returned rows, not necessarily bytes scanned. Required partition predicates and the workgroup scan cutoff address different parts of that risk. The cutoff limits damage after execution begins; it does not excuse accepting an obviously excessive query.
Architecture / decision scenario
A sales assistant can report regional revenue for the authenticated manager’s assigned region and a requested month. Its validator permits a single read-only query against approved revenue relations, requires the trusted region and month predicates, and rejects restricted customer-detail columns.
After structural validation, it submits EXPLAIN (TYPE VALIDATE) and inspects the relevant IO plan. It does not use EXPLAIN ANALYZE for this gate. The execution identity has narrowly scoped Athena, Glue, and S3 permissions, plus Lake Formation table and column permissions for the registered revenue data. Application checks enforce the manager’s region independently.
The approved statement runs unchanged in a configured workgroup with enforced results settings and a per-query scan cutoff. The service records the approval, submission token, and execution identifier. Pending queries remain pending; cancellation or failure produces no business answer. Only a successful result with the expected aggregate contract reaches the model’s final explanation.
Common exam traps
- Using keyword checks instead of inspecting SQL structure.
- Treating
EXPLAIN ANALYZEas non-executing validation. - Equating application-role permissions with end-user authorization.
- Assuming a database default prevents qualified cross-database references.
- Treating a workgroup aggregate alert or result
LIMITas a scan cutoff. - Rewriting an approved query without repeating its approval gates.
What to remember
Approve the program, its caller, its scope, and its execution envelope independently. Athena planning is evidence, not a security policy. Submit the unchanged approved SQL with trusted context and workgroup settings, track completion, and protect results as carefully as source data.
Knowledge check
A generated query has passed the application’s structural checks. Before running it, the gateway wants Athena to validate the statement without scanning any data. Which call fits?
EXPLAIN ANALYZE on the queryStartQueryExecution , then StopQueryExecution once the state is RUNNINGEXPLAIN (TYPE VALIDATE) on the queryEXPLAIN validates and plans without scanning data, although it calls AWS Glue for metadata. EXPLAIN ANALYZE executes the query to collect runtime statistics, and starting then stopping a query is execution too, which a pre-execution gate must avoid.A manager asks for “revenue for all regions”. The application’s Athena role can read every region, but the manager is assigned only to EMEA. Where should the region predicate in the approved query come from?
ExecutionParametersA generated query returns only ten rows but can scan an entire multi-terabyte table. Which control cancels a query that scans too much data?
BytesScannedCutoffPerQuery on the workgroupLIMIT 10 clause in the approved queryLIMIT does not bound the scan. The per-query control cancels a query that exceeds its limit, while a workgroup-wide control tracks aggregate usage over a period and notifies rather than cancelling the query.A query passes every gate and is approved. Before submission, the model revises it to add a join to a customer-detail table. What should the gateway do?
ClientRequestTokenClientRequestToken gives submission idempotency, not authorization, and reviewing cost after execution cannot undo an exposure.