tdfs4ds.agent.query_guard¶
tdfs4ds.agent.query_guard
¶
EXPLAIN gate for the queries the consumer agent sends to the database (0.3.8.10).
A chatbot must never launch a query that reads a whole large table. Before the agent
reads DATA (a chart, entity values, a feature's extremes, an SQL tool of the MCP server)
it asks the database for the plan (EXPLAIN) and refuses the query when the plan is not
compatible with a chat. The statement is then never executed.
Layers, one place:
- :func:
judge(pure): the verdict of one EXPLAIN text. Built on :func:tdfs4ds.utils.explain_cost.explain_cost(the one EXPLAIN reader); only the all-rows scans of named tables are read here. - :func:
check_query(I/O): classify the statement, EXPLAIN it, read the size of the tables scanned (DBC.TableSizeV, one read per distinct table set, kept for the turn, fail-open), judge, record the verdict. - :func:
agent_guard(context manager): the guard is active only inside it, so the plotting and values functions behave exactly as before for a Python caller (no extra statement). The agent's PLOT, VALUES and MCP nodes enter it. - :func:
before_data_query(hook): called by the plotting / values executors right before a data statement; does nothing outside :func:agent_guard.
Rules (settings, 0 / None disables a rule): a product join; estimated time above
tdfs4ds.AGENT_QUERY_MAX_SECONDS (30); a spool above AGENT_QUERY_MAX_SPOOL_GB (5) or an
overflow (*** rows); an all-rows scan of a table above AGENT_QUERY_MAX_TABLE_GB (10).
Low confidence alone never blocks: it is stated in the verdict.
Exempt on purpose: metadata reads (DBC., the FS_* catalogs, lineage, business
dictionary), statements that only read the agent's own scratch tables, and anything that is
not a read (the writes of the MCP tools are refused elsewhere).
QueryRefused derives from BaseException: the plotting code wraps its statements in
except Exception blocks that turn an error into an error entry, and a refusal must
not be turned into one. The agent nodes catch it.
_CURRENT
module-attribute
¶
_LEADING_NOISE
module-attribute
¶
_LEADING_NOISE = re.compile("^\\s*(?:/\\*.*?\\*/\\s*|--[^\\n]*\\n\\s*|LOCKING\\s+[^\\n]*?\\s+(?:FOR|IN)\\s+\\w+\\s+|(?:CURRENT|NONSEQUENCED|SEQUENCED)\\s+VALIDTIME\\s+|VALIDTIME\\s+AS\\s+OF\\s+(?:TIMESTAMP\\s+)?'[^']*'\\s+|(?:NONSEQUENCED|SEQUENCED)\\s+TRANSACTIONTIME\\s+)+", re.IGNORECASE | re.DOTALL)
_FROM_REF
module-attribute
¶
_FROM_REF = re.compile('\\b(?:FROM|JOIN)\\s+(\\(|[\\w$#\\"]+(?:\\s*\\.\\s*[\\w$#\\"]+)*)', re.IGNORECASE)
_SCAN
module-attribute
¶
_SCAN = re.compile('(?:\\bfrom|\\bjoined to)\\s+([\\w$#.]+)(?:\\s+in view\\s+[\\w$#.]+)?\\s+by way of an all-rows scan', re.IGNORECASE)
_ALIAS_REF
module-attribute
¶
_ALIAS_REF = re.compile('\\b(?:FROM|JOIN)\\s+((?:\\"[^\\"]+\\"|[\\w$#]+)(?:\\s*\\.\\s*(?:\\"[^\\"]+\\"|[\\w$#]+))?)(?:\\s+(?:AS\\s+)?(\\"[^\\"]+\\"|[A-Za-z_][\\w$#]*))?', re.IGNORECASE)
_NOT_ALIAS
module-attribute
¶
_NOT_ALIAS = {'WHERE', 'JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL', 'CROSS', 'ON', 'GROUP', 'ORDER', 'UNION', 'QUALIFY', 'HAVING', 'SAMPLE', 'WITH', 'AS', 'OUTER', 'SELECT', 'SEL', 'TOP', 'AND', 'OR', 'EXCEPT', 'MINUS', 'INTERSECT', 'NATURAL', 'USING'}
QueryRefused
¶
_Recorder
¶
What one guarded stretch (a turn's node) learned: verdicts, sizes, the refusal.
agent_guard
¶
Activate the guard for the code run inside. Yields the recorder (.verdicts, .refusal).
is_data_read
¶
True when sql is a read of DATA the guard must EXPLAIN. Pure.
A SELECT / WITH, or an INSERT / CREATE TABLE ... AS holding one. Not: other statements,
metadata reads (DBC., an FS_* object that is not a FS_T_ storage table) and
statements that read only the agent's scratch tables.
scanned_tables
¶
Tables an EXPLAIN reads by an all-rows scan ('DB.TABLE'), in plan order. Spools are left out. A table named by a correlation name keeps that name (its size is then simply unknown). Pure.
alias_map
¶
{CORRELATION NAME: 'DB.TABLE'} from the FROM / JOIN items of sql (upper case, quotes
removed). EXPLAIN names a table by its correlation name (DB.x, seen live), so the guard maps
it back to the table to find its size. A derived table's alias is not mapped. Pure.
resolve_scanned
¶
tables of an EXPLAIN (scanned_tables) with correlation names replaced by the tables they
stand for (:func:alias_map): DB.X -> DB.TABLE when X is an alias of TABLE (of
DB, or unqualified). Pure.
judge
¶
judge(explain_text: str, *, max_seconds: float = 30, max_spool_bytes: float = 5 * GB, max_table_bytes: float = 10 * GB, table_sizes: Optional[Dict[str, Optional[int]]] = None, sql: Optional[str] = None) -> dict
The verdict of one EXPLAIN text. Pure.
{"allowed", "reasons": [{"code", ...}], "notes", "cost", "tables", "summary"}. Reason
codes: product_join, time, spool, overflow, big_scan. A limit of 0 /
None switches its rule off. table_sizes maps 'DB.TABLE' (upper case) to bytes (None =
unknown, never blocks).
_run_explain
¶
EXPLAIN sql through the agent's own teradataml connection; the whole text.
_read_sizes
¶
CurrentPerm in bytes of 'DB.TABLE' names, one DBC.TableSizeV read. Fail-open: {} on any failure.
check_query
¶
check_query(sql: str, rec: Optional[_Recorder] = None, *, explain: Optional[Callable] = None, sizes: Optional[Callable] = None) -> dict
EXPLAIN sql and return the verdict (also recorded). Raises nothing.
A statement that is not a data read is {"allowed": True, "exempt": True} and nothing is
sent. When the EXPLAIN itself fails the verdict is refused with reason explain_failed
carrying the whole database error: the query is never run blind.
before_data_query
¶
Hook of the plotting / values executors: EXPLAIN sql and raise :class:QueryRefused when
it is refused. Does nothing (no statement) outside :func:agent_guard.
_has_window
¶
The question writes a time window (dates, "last 3 days", "yesterday"). Never reads the database.
refusal_answer
¶
The fixed answer given when a query is refused. Written by code. Never retried with another query.
refusal_result
¶
A skill result carrying the refusal answer and the trace of the guard.
tool_error_text
¶
The text a guarded MCP tool returns to the model (the ERROR: convention).
sql_in_tool_input
¶
The SQL text of an MCP tool call, or None when the tool carries none (a TD_* function, ...).
Looks at the top-level arguments and at parameters / input (the router tool). Pure.
guard_tool_call
¶
For a guarded MCP tool: None to let the call through, else the ERROR: text to return.
Only inside :func:agent_guard. A tool without SQL text cannot be explained: it passes, and the
trace says so. A statement that is not a SELECT / WITH is not explained (writes are refused elsewhere).