1h 2m read

AI SQL Query Audit Trails: Correlating User, Tool and Warehouse Query IDs

Design an MCP-to-warehouse AI SQL audit trail with correlation IDs, effective principals, normalized SQL hashes, redaction, retention and error events.

AI SQL Query Audit Trails: Correlating User, Tool and Warehouse Query IDs

Author: jackey.ye | Updated: 2026-11-26

An AI SQL audit trail correlates three identifier layers: the human user who asked, the MCP tool call that carried the request, and the warehouse query ID that executed it. This tutorial builds that chain, covering correlation IDs, effective principals, normalized SQL hashes, redaction, retention and error events. It collects evidence; it does not guarantee the SQL was correct.

This is a narrow operational design guide. It complements rather than repeats the existing Singdata posts on read-only SQL and least-privilege controls for MCP lakehouse access and on connecting AI coding agents safely to a warehouse, which cover authorization and connection hardening. Here the subject is only what you persist, how you join the layers, and what the joined record can and cannot prove. You will leave with a correlation store schema, an eight-step workflow with checkpoints, and a reviewer checklist.

What Does an AI SQL Audit Trail Need to Correlate?

It needs to correlate five hops: human principal, MCP host session, tool call, effective warehouse principal, and warehouse query or job ID. No single layer holds the whole chain. The warehouse records the principal that authenticated to it, which in a shared-service-principal design is the service account, not the person who typed the question. The MCP layer knows the person and the tool call, but MCP defines no standard request or response field for a downstream warehouse query ID — nothing in the protocol itself carries one.

The reason sits in the protocol architecture. MCP defines hosts (LLM applications that initiate connections), clients (connectors inside the host) and servers (services that provide capabilities), communicating over JSON-RPC 2.0 with stateless, self-contained requests (MCP specification, 2026-07-28). Tools are server features the model can invoke. Because no standard field exists, the host must mint its own identifier and carry it across the boundary. The one exception is a custom tool you control: if it runs the query itself, it can capture the warehouse query ID and return it in its own tool result, so a tool call can map directly to a query. That is an application convention, not a protocol guarantee, and the correlation ID is still what lets you join the layers when the tool result never arrives.

Which Identifiers Must Be Generated Before Execution vs Captured at Execution Time?

Generate correlation_id, tool_call_id, attempt_id, host session ID, requested human principal and requested role before the tool runs. Capture warehouse query_id or job_id, effective principal, warehouse session_id, start and end times, status and error code after execution.

Keep attempts and queries separate. Mint a new attempt_id on every retry, so three retries of the same request stay distinguishable instead of overwriting one tool call record. Model the relationship as one-to-many: a single tool call can produce several warehouse queries — a retry after failure, an execution plus a metadata lookup, or a multi-statement batch — so the correlation store holds one row per warehouse query and points each back to its tool_call_id and attempt_id. A tool call with zero warehouse rows and a tool call with five are both normal; the cardinality is data, not an assumption.

The halves join only when the pre-execution identifier is propagated into the warehouse session itself.

Propagation mechanisms differ by platform. Snowflake exposes a QUERY_TAG session parameter, and QUERY_HISTORY carries a matching query_tag column (Snowflake QUERY_HISTORY view). BigQuery attaches key-value labels to jobs, and the JOBS view returns them in a labels record (BigQuery JOBS view). Databricks accepts query_tags as a session configuration parameter and stores them in the query_tags map of system.query.history; tags are limited to 10 KB per session, and when the limit is exceeded incoming tags are dropped with a tags_dropped: true sentinel, while oversized or invalid keys are discarded with a tag_invalid: true sentinel (Databricks query tags).

If your tool reuses a pooled warehouse session across users, set the tag before each execution and clear it right after. A tag left behind on a pooled session leaks onto the next user's query and produces cross-user attribution — the worst possible failure for an audit trail. Wrap execution so that setting the tag, running the statement and resetting the tag happen together, and treat a failed reset as a reason to discard the session rather than return it to the pool.

Treat client_application in Databricks as a hint, not an identity: the documentation states it is derived from information provided by client applications and, while values are expected to remain static, this cannot be guaranteed (Databricks query history system table).

-- Example configuration — validate in your target environment.
  -- Set immediately before execution on a pooled session...
  ALTER SESSION SET QUERY_TAG = '{"correlation_id":"c-8f21","tool_call_id":"t-4471","attempt_id":"a-8801","app":"singdata_mcp"}';
  -- ...and reset right after, so the next user on this session cannot inherit the tag.
  ALTER SESSION UNSET QUERY_TAG;
  

The app key is an application marker, not a vendor feature: it lets your reconciliation queries pick out only the rows this tool wrote, instead of every query that happens to carry some tag.

How Do You Distinguish the Human Chat User From the Effective Warehouse Principal?

Record both, plus the delegation path between them. In the common pattern the MCP server connects with one shared service principal, so the warehouse's user_name reflects that account and the person behind the question disappears. Storing the human principal at the host layer and the effective principal at the warehouse layer, with the edge that links them, restores attribution.

Some warehouses expose the split natively. Databricks documents executed_by as the user who ran the statement and executed_as as the user or service principal whose privilege was used, with a matching executed_as_user_id (Databricks query history system table). Snowflake exposes user_type and an agent_type column whose values include CORTEX_AGENT, CORTEX_LITE_AGENT and EXTERNAL_AGENT, with EXTERNAL_AGENT covering a SERVICE_AGENT user type, a custom OAuth integration configured with IS_AGENTIC = TRUE, or an OAuth token exchange with act type agent (Snowflake QUERY_HISTORY view).

Where no native delegation field exists, the link is only as trustworthy as the host's own logging. That is an evidence limitation, not something a schema can repair. Authorization design — which role the service principal may hold and what it may read — belongs to the least-privilege guide; this section stores only the resulting evidence.

How Should You Normalize and Hash SQL Without Losing the Executed Statement?

Keep the executed SQL text as the authoritative record and compute a normalized hash only as a grouping key. The hash answers "have we seen this shape before"; the text answers "what actually ran". Storing the hash alone discards the evidence a reviewer needs.

Normalization should strip literals, comments, whitespace and case differences in case-insensitive identifiers, and must not strip object identifiers or predicates that change meaning. Vendor fingerprints are useful reference points rather than something to reimplement blindly. Snowflake's query_hash is computed from canonicalized SQL text and is identical for queries differing only in case-insensitive identifiers, session variables, stage names, whitespace or comments; query_parameterized_hash parameterizes literals used in predicates with comparison operators (Snowflake query hash). Both have companion version columns, query_hash_version and query_parameterized_hash_version, because the hashing logic can change and produce different hashes for the same query.

BigQuery's query_info.query_hashes.normalized_literals ignores comments, parameter values, UDFs and literals, and the value differs when underlying views change or when a SELECT * picks up a changed table schema (BigQuery JOBS view). Redshift separates user_query_hash (includes literals) from generic_query_hash (excludes them) and carries query_hash_version (Redshift SYS_QUERY_HISTORY). Always store the version alongside the hash, or a version change will look like a new query family.

What Should You Redact Before Persisting Prompts and SQL?

Redact at ingestion, keep a controlled-access path to the unredacted original, and log the redaction decision itself. Categories to redact include credentials and tokens appearing in prompts, connection strings, and personal data inside SQL literals. Record what was removed, by which rule, and when, so a reviewer can tell an empty field from a redacted one.

Distinguish irreversible redaction from reversible tokenization. Redaction lowers evidence value permanently; tokenization preserves joinability under a separate access control. Either way, the vendor side may already be masking. Databricks returns <REDACTED> in statement_text by default unless the reader is an account admin or a member of the databricks_pii_access account-level group (Databricks query history system table). Snowflake populates bind_values unless the array is too large or the ALLOW_BIND_VALUES_ACCESS parameter is FALSE, in which case the column contains NULL (Snowflake QUERY_HISTORY view). Your audit design must account for both, because a NULL bind value may mean redaction rather than absence.

# Illustrative rule definition only — this is not an executable script.
  # It describes intent; implement the rule in your own redaction service and test it.
  rule: redact_bearer_tokens
  match: /(Bearer\s+)[A-Za-z0-9._\-]+/
  replace: $1[REDACTED:token]
  record: rule_id, field, timestamp
  

Read that block as pseudoconfiguration. There is no runtime that parses it as written — no YAML loader is specified, and record is a field list, not a statement. Treat it as the specification you hand to whoever writes the redaction step, then verify against real samples before it touches production data.

How Do You Record Error, Timeout, Cancellation and Denied-Query Events?

Treat non-success outcomes as first-class rows, not gaps. A missing warehouse row is ambiguous: it may be a denial that never reached execution, a client-side timeout, a cancellation, or simply a query that executed but has not yet appeared in the history view. Each layer has its own status vocabulary, and the two must be reconciled rather than assumed to match.

That last case matters more than it looks. A missing query ID is evidence about what the store can see, not proof that nothing ran. Query-history views lag, and some executions may never surface in a given view at all. Before you call an attempt an orphan, wait out the latency window and check the attempt's own status record; only then is "unexplained" a fair label.

Snowflake's ACCOUNT_USAGE.QUERY_HISTORY reports execution_status as success, fail or incident, while the INFORMATION_SCHEMA table function adds transitional values resuming_warehouse, running, queued, blocked, success, failed_with_error and failed_with_incident, alongside error_code and error_message (Snowflake QUERY_HISTORY table function). BigQuery reports state as PENDING, RUNNING or DONE with an error_result record. Redshift's status takes planning, queued, running, returning, failed, canceled or success, and its aborted flag documents a trap: if a client disconnects before receiving results, the query is marked canceled even if it completed successfully in the backend (Redshift SYS_QUERY_HISTORY). Databricks uses FINISHED, FAILED or CANCELED.

MCP provides cancellation and error reporting as protocol utilities, so the tool layer can record a cancellation the warehouse never saw. Store all timestamps in UTC and convert at query time: a Singapore team reading SGT (UTC+8) and a US team reading PT or ET should share one stored instant, not local values.

How Should You Set Retention and Access Controls on the Correlation Store?

Set retention per layer to the shortest period that satisfies the audit need, and never exceed the shortest source the store depends on unless the store itself captured the raw fields. Source boundaries differ widely. Snowflake's ACCOUNT_USAGE views retain one year while the INFORMATION_SCHEMA table functions retain seven days (Snowflake query hash). BigQuery's INFORMATION_SCHEMA.JOBS shows running jobs plus history for the past 180 days (BigQuery JOBS view). Databricks system tables default to 395 days of free retention, configurable by an account admin, with two documented caveats: in a disaster or total data loss Databricks does not guarantee recovery of all system table data for the configured period, and configurable retention is limited to the HIPAA, HITRUST, PCI, C5 and TISAX standards (Databricks system tables).

For access, define separate roles for redacted read, unredacted investigation and store administration, time-box elevation, and audit the auditors. These are engineering controls that support an audit position; they do not by themselves establish compliance with any framework.

Why Does Evidence Collection Not Guarantee SQL Correctness?

An audit trail proves what was submitted, by whom, through which tool, and what the warehouse did with it. It does not prove the query returned the right answer. A statement can succeed with a wrong join, a stale table, or a misinterpreted prompt, and the trail will faithfully record a successful execution.

Correctness verification belongs elsewhere: reconciliation against known totals, review of generated SQL before execution for high-impact queries, and result validation. The agent-connection guide covers those verification checkpoints. Keep the boundary explicit in your documentation so that a complete trail is never read as an accuracy claim.

Comparison: What Each Warehouse Exposes for Correlation

The table below compares the four warehouses on the fields this design depends on. It reflects vendor documentation checked 2026-11-26; field availability varies by view, edition and account configuration, so confirm against your own account before building the join.

Correlation-relevant fields by warehouse, from vendor documentation checked 2026-11-26. Field availability varies by view, edition and account configuration; confirm against your own account before building the join.

Field

Snowflake

BigQuery

Redshift

Databricks

Native query/job ID

query_id

job_id

query_id; query_uuid

statement_id

Session ID

session_id

session_info

session_id

session_id

Requesting user field

user_name

user_email; principal_subject

username; user_id

executed_by; executed_by_user_id

Effective-principal field

role_name; role_type

not documented in cited source

not documented in cited source

executed_as; executed_as_user_id

Agent/delegation field

agent_type; user_type

not documented in cited source

not documented in cited source

executed_as

Tag/label mechanism

QUERY_TAG → query_tag

job labels

query_label

query_tags (10 KB/session)

Normalized hash + version

query_hash, query_parameterized_hash + version columns

query_info.query_hashes.normalized_literals; no version column documented

user_query_hash, generic_query_hash + query_hash_version

not documented in cited source

Status/error fields

execution_status, error_code, error_message

state, error_result

status, aborted, error_message

execution_status, error_message

Documented retention

1 year (ACCOUNT_USAGE); 7 days (table functions)

180 days (JOBS)

not documented in cited source

395 days default

Prerequisites

Confirm these before building the chain:

  • An MCP host or client that can mint and log a correlation ID per tool call plus an attempt ID per retry, and that exposes the human principal to your logging sink.

  • Warehouse access to the query-history view or system table you will join against, with the privilege needed to read other users' rows.

  • A destination store — table, object storage or log sink — for correlation records, with an owner named.

  • A written redaction policy covering prompts, SQL literals and bind values.

  • Edition and configuration caveats resolved: which Snowflake view exposes which column, BigQuery view scope, and the Databricks account-admin or databricks_pii_access requirement for unredacted statement text.

No credentials belong in any configuration file, example or log line.

Engineering Workflow: Building the Correlation Chain

Work through the steps in order; each has a checkpoint and an observable result.

  1. Define the correlation record schema. Checkpoint: every field has a type, an owner and a retention tag. Expected result: a reviewed DDL that the store is created from.

  2. Mint correlation_id, tool_call_id and attempt_id in the MCP host before invocation. Checkpoint: all three are logged before the tool request leaves the host, and a retry mints a fresh attempt_id. Expected result: a host log line with no warehouse ID yet.

  3. Propagate the correlation ID into the warehouse session via query tag or job label, then reset it after execution when the session is pooled. Checkpoint: the tag string is under the platform limit and no tag survives the execution. Expected result: the next warehouse query carries the tag, and the one after does not.

  4. Capture the warehouse query/job ID and effective principal after execution. Checkpoint: the captured ID matches the tagged query, and each row names its attempt_id. Expected result: one row per warehouse query, all tied back to the tool call.

  5. Normalize and hash the SQL while storing the executed text. Checkpoint: hash version is recorded. Expected result: repeated queries group under one hash.

  6. Apply redaction and record the decision. Checkpoint: the redaction rule ID and timestamp are stored. Expected result: a redacted statement plus an audit note.

  7. Capture terminal status including error, cancel and denied. Checkpoint: no attempt ends without a status. Expected result: every attempt has a row.

  8. Reconcile tool-layer and warehouse-layer records and flag orphans after the grace window, filtered to your own application tags and joined on the parsed tag tuple when no warehouse ID was stored. Checkpoint: orphan count is reviewed and stable across runs, and no retry is masked by a sibling attempt. Expected result: a list of unmatched records on each side.

# Example configuration — validate in your target environment.
  step_3.tag = {"correlation_id": "<minted>", "tool_call_id": "<minted>"}
  step_3.max_bytes = 10240   # Databricks per-session limit
  

Reusable Asset: Correlation Store Schema and Reconciliation Query

The asset below uses Snowflake syntax as the worked example. Equivalent field names for other platforms appear in comments.

-- Example DDL and reconciliation queries (Snowflake). Validate in your target environment.
  CREATE SCHEMA IF NOT EXISTS audit;
  
  CREATE TABLE IF NOT EXISTS audit.ai_query_correlation (
    correlation_id        VARCHAR        NOT NULL,  -- minted by MCP host
    tool_call_id          VARCHAR        NOT NULL,  -- minted by MCP host; one call may fan out to many queries
    attempt_id            VARCHAR        NOT NULL,  -- minted per retry, so re-runs stay distinct
    attempt_no            NUMBER,                    -- 1..n within a tool call
    host_session_id       VARCHAR,
    human_principal       VARCHAR,                  -- BigQuery: user_email; Databricks: executed_by
    effective_principal   VARCHAR,                  -- Databricks: executed_as; Snowflake: user_name
    delegation_path       VARCHAR,                  -- human -> tool -> service principal -> role
    warehouse_query_id    VARCHAR,                  -- Snowflake: query_id; BigQuery: job_id; Databricks: statement_id
    warehouse_session_id  VARCHAR,                  -- Snowflake: session_id; Redshift: session_id
    sql_hash              VARCHAR,                  -- Snowflake: query_hash; Redshift: generic_query_hash
    sql_hash_version      NUMBER,                   -- Snowflake: query_hash_version
    executed_sql_redacted VARCHAR,
    redaction_applied     BOOLEAN,
    status                VARCHAR,                  -- Snowflake: execution_status; Redshift: status
    error_code            VARCHAR,
    started_at_utc        TIMESTAMP_NTZ,
    ended_at_utc          TIMESTAMP_NTZ
  );
  
  -- Parsed tag view: one row per warehouse query whose QUERY_TAG is valid JSON,
  -- exposing the four values the app writes. Equality on these replaces string matching.
  CREATE OR REPLACE VIEW audit.v_query_tag AS
  SELECT
    q.query_id,
    q.user_name,
    q.query_tag,
    q.start_time,
    TRY_PARSE_JSON(q.query_tag):app::string            AS tag_app,
    TRY_PARSE_JSON(q.query_tag):correlation_id::string AS tag_correlation_id,
    TRY_PARSE_JSON(q.query_tag):tool_call_id::string   AS tag_tool_call_id,
    TRY_PARSE_JSON(q.query_tag):attempt_id::string     AS tag_attempt_id
  FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY q
  WHERE TRY_PARSE_JSON(q.query_tag) IS NOT NULL;
  
  -- Query 1: host-side attempts with no warehouse row (orphans), tested on q.query_id.
  -- A 2-hour grace window lets ACCOUNT_USAGE catch up before an attempt is flagged.
  -- Match on warehouse_query_id when captured; otherwise fall back to the FULL tuple
  -- (app + correlation_id + tool_call_id + attempt_id), so a retry that never executed
  -- is still flagged even though a sibling attempt of the same correlation did run.
  SELECT
    c.correlation_id,
    c.tool_call_id,
    c.attempt_id,
    c.attempt_no,
    c.status AS host_status,
    c.warehouse_query_id,
    c.started_at_utc
  FROM audit.ai_query_correlation c
  LEFT JOIN audit.v_query_tag q
    ON q.query_id = c.warehouse_query_id
    OR (c.warehouse_query_id IS NULL
        AND q.tag_app            = 'singdata_mcp'
        AND q.tag_correlation_id = c.correlation_id
        AND q.tag_tool_call_id   = c.tool_call_id
        AND q.tag_attempt_id     = c.attempt_id)
  WHERE q.query_id IS NULL
    AND c.started_at_utc >= DATEADD('day', -7, CURRENT_TIMESTAMP())
    AND c.started_at_utc <= DATEADD('hour', -2, CURRENT_TIMESTAMP());
  
  -- Query 2: warehouse rows THIS application tagged that the store never recorded.
  -- The parsed app filter limits the scan to singdata_mcp rows, not every non-null tag.
  -- The join mirrors Query 1: exact query_id, or the same full tuple when the row
  -- exists but its warehouse_query_id was never written back — so a known attempt
  -- is not misreported as unlogged.
  SELECT
    q.query_id,
    q.user_name,
    q.query_tag,
    q.start_time
  FROM audit.v_query_tag q
  LEFT JOIN audit.ai_query_correlation c
    ON c.warehouse_query_id = q.query_id
    OR (c.warehouse_query_id IS NULL
        AND c.correlation_id = q.tag_correlation_id
        AND c.tool_call_id   = q.tag_tool_call_id
        AND c.attempt_id     = q.tag_attempt_id)
  WHERE q.tag_app = 'singdata_mcp'
    AND c.correlation_id IS NULL
    AND q.start_time >= DATEADD('day', -7, CURRENT_TIMESTAMP())
    AND q.start_time <= DATEADD('hour', -2, CURRENT_TIMESTAMP());
  

Four deliberate choices. Orphans are tested on q.query_id IS NULL, so a row that never resolves in the history view is caught rather than only a null-stored ID. The app filter runs on the parsed tag value, so other teams' tagged queries stay out of your orphan report and you are never asked to explain rows you never wrote. The two-hour grace window is a starting point, not a universal constant — measure your own latency and widen it until the orphan count stops shrinking. And when warehouse_query_id was never captured, the fallback matches the full tuple of app, correlation, tool call and attempt rather than the correlation alone.

That last point carries real weight. Matching on correlation_id by itself would let one successful attempt hide a sibling retry that never ran, because both share the correlation. The parsed tuple on attempt_id keeps retries distinct, which is why the fallback and the Query 2 join both use it. Both queries read from the same parsed tag view, so string concatenation and case sensitivity stop being part of the comparison.

A missing warehouse_query_id also has two meanings: the query truly never ran, or it ran and has not landed in the history view. That is why the attempt carries its own status, why the orphan query checks the grace window, and why the tuple fallback exists to catch the second case when the record arrived but the ID did not.

Acceptance Checklist

Hand this to a reviewer:

  • Every tool call has a correlation_id recorded before execution.

  • Every warehouse row joins back to a tool call by query_id or by the parsed tag tuple of app, correlation, tool call and attempt, or is explicitly flagged as orphaned.

  • Human and effective principals are both stored, with the delegation path.

  • Executed SQL is stored redacted, alongside the hash and hash version.

  • Error, cancel and denied outcomes appear as rows, not gaps.

  • Retention per layer is documented and does not exceed its source.

  • Access roles separate redacted read from unredacted investigation.

  • The documentation states that the trail is evidence, not a correctness guarantee.

Frequently Asked Questions

Short answers to the questions reviewers raise most often about MCP-to-warehouse audit design.

Can you join an MCP tool call directly to a Snowflake query_id?

Not natively, because MCP defines no standard field for a warehouse query ID. The join has to be built: the host mints a correlation ID, sets it through the QUERY_TAG session parameter, and stores the returned query_id alongside it. The query_tag column in QUERY_HISTORY then supplies the join key. One shortcut is a custom tool that executes the query itself and returns the query_id in its own result — a reliable convention, but your own, not a protocol guarantee.

Is a normalized SQL hash sufficient evidence of what query ran?

No. A hash is a grouping key, not a record of execution, and vendor hash logic changes across versions — Snowflake exposes query_hash_version and query_parameterized_hash_version precisely because the same query can hash differently between versions. Retain the executed SQL text as the authoritative evidence and store the hash beside its version.

How do you audit queries run by a shared service principal?

Record the human principal at the MCP host layer and the effective principal at the warehouse layer, then store the delegation edge between them. Where the warehouse exposes a native field — Databricks executed_as and executed_as_user_id in the query history system table — use it; otherwise the link is only as trustworthy as host logging.

What happens to the audit trail when a query is canceled or denied?

A denied query may never reach the warehouse, so the tool layer must record the denial itself. A canceled query can still appear warehouse-side, and Redshift documents that a client disconnect marks a query canceled even if it completed successfully in the backend. Record one attempt_id per try, allow one tool call to fan out to several warehouse queries, and reconcile both layers rather than assuming one row per attempt. Treat a missing query ID as "not yet visible" until the latency window passes.

Does a complete audit trail prove the AI-generated SQL was correct?

No. The trail proves what was submitted, by whom, through which tool, and what the warehouse did with it — not that the result was right. A query can succeed with a wrong join or a stale table, so correctness needs separate validation such as reconciliation against known totals or review before execution.

Related Articles