Skip to content

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.

GB module-attribute

GB = 1024 ** 3

_CURRENT module-attribute

_CURRENT: ContextVar = contextvars.ContextVar('tdfs4ds_agent_query_guard', default=None)

_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'}

PRODUCT_JOIN_SMALL_ROWS module-attribute

PRODUCT_JOIN_SMALL_ROWS = 100000

PRODUCT_JOIN_SMALL_BYTES module-attribute

PRODUCT_JOIN_SMALL_BYTES = 100 * 1024 ** 2

_SQL_KEYS module-attribute

_SQL_KEYS = ('query', 'sql', 'statement', 'sql_query')

QueryRefused

Bases: BaseException

The query was not run: its plan is not compatible with a chat. Carries the verdict.

verdict instance-attribute

verdict = verdict

__init__

__init__(verdict: dict)

_Recorder

What one guarded stretch (a turn's node) learned: verdicts, sizes, the refusal.

verdicts instance-attribute

verdicts: List[dict] = []

refusal instance-attribute

refusal: Optional[dict] = None

sizes instance-attribute

sizes: Dict[str, Optional[int]] = {}

by_sql instance-attribute

by_sql: Dict[str, dict] = {}

unexplained instance-attribute

unexplained: List[str] = []

__init__

__init__()

explain_cost

explain_cost(text: str) -> dict

The optimizer's estimates in an EXPLAIN text. Pure.

human_bytes

human_bytes(b: int) -> str

human_seconds

human_seconds(s: float) -> str

agent_guard

agent_guard()

Activate the guard for the code run inside. Yields the recorder (.verdicts, .refusal).

active

active() -> Optional[_Recorder]

limits

limits() -> dict

The three limits in bytes / seconds (0 = rule off).

_is_scratch

_is_scratch(name: str) -> bool

is_data_read

is_data_read(sql: str) -> bool

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

scanned_tables(text: str) -> List[str]

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

alias_map(sql: str) -> Dict[str, str]

{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

resolve_scanned(tables: List[str], sql: str) -> List[str]

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

_run_explain(sql: str) -> str

EXPLAIN sql through the agent's own teradataml connection; the whole text.

_read_sizes

_read_sizes(tables: List[str]) -> Dict[str, Optional[int]]

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

before_data_query(sql: str) -> None

Hook of the plotting / values executors: EXPLAIN sql and raise :class:QueryRefused when it is refused. Does nothing (no statement) outside :func:agent_guard.

_reason_text

_reason_text(r: dict, fr: bool) -> str

_has_window

_has_window(question: str) -> bool

The question writes a time window (dates, "last 3 days", "yesterday"). Never reads the database.

refusal_answer

refusal_answer(verdict: dict, question: str = '', french: Optional[bool] = None) -> str

The fixed answer given when a query is refused. Written by code. Never retried with another query.

refusal_result

refusal_result(verdict: dict, question: str = '') -> dict

A skill result carrying the refusal answer and the trace of the guard.

tool_error_text

tool_error_text(verdict: dict, question: str = '') -> str

The text a guarded MCP tool returns to the model (the ERROR: convention).

sql_in_tool_input

sql_in_tool_input(kwargs) -> Optional[str]

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

guard_tool_call(kwargs, rec: Optional[_Recorder] = None) -> Optional[str]

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).