Build an Observability AI Agent on Snowflake
Overview
An agent can look like the cheapest, most successful one in its traces and still be wrong about what happened to the customer's money. In this Quickstart, we'll build the thing that catches that, end to end, in your own account.
Let's imagine we run an online store, and we're trying out AI agents to handle refund requests. Like most teams, we don't have just one candidate. We have three versions of a refund agent, built from the same LangGraph graph: fetch_facts → decide → refund_tool → respond. They get the same customer requests and call the same refund tool, which always does exactly what it's asked. The only difference is how each agent behaves.
| Agent | Model | Its flaw |
|---|---|---|
swift | claude-haiku-5-5 | Asks the refund tool for the order total, not the amount the customer asked for |
assured | claude-sonnet-5-5 | Tells the customer "refunded" after any attempt, without checking the tool's result |
precise | claude-sonnet-5-5 | None: the control |
We planted those two mistakes on purpose, because they're exactly the kind a trace can't see. All three agents look healthy in their traces: fast calls, no errors, cheap tokens. Only the refund ledger shows which one is right. Our job is to join the two, so cost and correctness land on the same row, and figure out which agent is costing the business the most.
We'll follow one path our data takes, in three phases: land it, join it, act on it.
- Cortex AI Gateway is the model endpoint and an OpenTelemetry collector. It records every model call as spans in your account, and it accepts the agents' own spans too.
- Snowpipe Streaming lands every agent step and every ledger row in seconds, in parallel with the traces.
- Dynamic tables join traces to outcomes on a run ID, incrementally, with a one-minute target lag.
- An interactive warehouse serves the app's reads at low latency.
- AI_COMPLETE explains each issue as typed fields. The model explains; it never decides the money.
- Snowflake App Runtime hosts the app with caller's rights, so every query and every fix runs as the signed-in user.
Prerequisites
- A Snowflake account in an AWS commercial region with Cortex AI Gateway
- The ACCOUNTADMIN role
- Familiarity with SQL and a terminal
What You'll Learn
- How to capture model calls and agent spans as OpenTelemetry traces with Cortex AI Gateway
- How to stream agent events and ledger rows into tables with Snowpipe Streaming
- How to join traces to business outcomes with incremental dynamic tables
- How to serve low-latency reads from an interactive warehouse
- How to generate structured root-cause diagnoses with
AI_COMPLETE - How to deploy a caller's-rights app on Snowflake App Runtime that writes corrections back
What You'll Need
- A Snowflake account with ACCOUNTADMIN. Several steps change account-level objects (see the note in the next section).
- Snowflake CLI (
snow) with a configured connection - just, a small command runner
- Docker,
openssl,jq,curland uv
What You'll Build
- Three LangGraph refund agents that call models through Cortex AI Gateway and stream their steps into Snowflake
- A pipeline of dynamic tables that grades every run against a ground-truth answer key
- A case and issue queue with
AI_COMPLETEdiagnoses and governed writeback procedures - A Next.js app on Snowflake App Runtime for the people who fix the mistakes
Setup: Role & Grants
Before we begin, let's get the lab code and the role it builds under. Everything we create lives under one role, TRACE_LAB_RL, which is what makes cleanup a single command at the end.
First, let's clone the repo and check our setup. Replace <c> with your Snow CLI connection name, here and in every command that follows.
git clone https://github.com/sfc-gh-rdominguez/o11y-hol.git cd o11y-hol cp .env.example .env # set SNOWFLAKE_ACCOUNT to ORGNAME-ACCOUNTNAME just doctor <c>
doctor checks your local tools (docker, openssl, jq, snow, curl, uv), connects with your Snow CLI connection, confirms the account matches .env, and confirms the account has Cortex AI Gateway. Nothing is created yet.
Every step in this Quickstart is a named recipe in the repo's justfile. Each one is a thin wrapper: just setup, for example, runs the Snow CLI against one SQL file with your connection name filled in. If you're ever curious what a step does, open the justfile, or run just on its own to list every recipe.
Now let's create the role. just setup runs data/migrations/001_init.sql, which is the role and grants block below. If you don't have ACCOUNTADMIN access, send this SQL block to your Snowflake admin to review and run on your behalf.
-- Run as ACCOUNTADMIN USE ROLE ACCOUNTADMIN; -- 1. Create the role for this Quickstart CREATE ROLE IF NOT EXISTS TRACE_LAB_RL COMMENT = 'Agent Traces to Business Outcomes lab'; -- 2. Grant the role to the user who will run the Quickstart GRANT ROLE TRACE_LAB_RL TO USER <your_username>; GRANT ROLE TRACE_LAB_RL TO ROLE SYSADMIN; -- 3. Warehouse privileges CREATE WAREHOUSE IF NOT EXISTS TRACE_LAB_WH WAREHOUSE_SIZE = XSMALL AUTO_SUSPEND = 60 AUTO_RESUME = TRUE INITIALLY_SUSPENDED = TRUE; GRANT OWNERSHIP ON WAREHOUSE TRACE_LAB_WH TO ROLE TRACE_LAB_RL COPY CURRENT GRANTS; -- 4. Database & schema privileges CREATE DATABASE IF NOT EXISTS REFUND_TRACE_LAB; GRANT OWNERSHIP ON DATABASE REFUND_TRACE_LAB TO ROLE TRACE_LAB_RL COPY CURRENT GRANTS; -- 5. Integration privileges -- -- N/A for this guide -- 6. Future grants -- -- N/A for this guide (TRACE_LAB_RL owns the database, so it owns every object created in it) -- 7. Stage privileges -- -- N/A for this guide -- 8. Guide-specific grants GRANT EXECUTE TASK ON ACCOUNT TO ROLE TRACE_LAB_RL; GRANT MONITOR ON AI GATEWAY SNOWFLAKE TO ROLE TRACE_LAB_RL; GRANT BIND SERVICE ENDPOINT ON ACCOUNT TO ROLE TRACE_LAB_RL; -- 9. Switch into the role for the rest of the Quickstart USE ROLE TRACE_LAB_RL; CREATE SCHEMA IF NOT EXISTS REFUND_TRACE_LAB.OUTCOMES;
Note: If you don't have ACCOUNTADMIN access, send the SQL block above to your Snowflake admin to run on your behalf. Once the role is granted, run
USE ROLE TRACE_LAB_RL;and continue with the Quickstart.
Important: Some steps can't be delegated to a custom role, so the lab runs them as ACCOUNTADMIN: replacing the account-wide Cortex AI Gateway spec, creating the TRACE_LAB_SVC service user and its network policy, and minting its programmatic access token. Those happen in the Cortex AI Gateway step, and teardown reverses each one.
Let's run setup and its two checks.
just setup <c> just check <c> 01_foundation just check <c> 01_models
Here's what that does:
- Creates TRACE_LAB_RL and grants it to you
- Creates the REFUND_TRACE_LAB database with its OUTCOMES schema
- Creates TRACE_LAB_WH, an XSMALL warehouse that suspends after 60 seconds idle, so it only bills while it's working. It runs the dynamic tables, tasks, procedures and
AI_COMPLETE.
The 01_models check confirms the two models the agents need, claude-haiku-5-5 and claude-sonnet-5-5, are available in your region. The models come from Cortex, so nothing leaves the account to call them.
Note: If you fall behind at any point,
just up <c>builds everything through the app deploy and is safe to rerun. It's meant to be a one-shot command, so you won't get the step-by-step learning, but it catches you up.
Traces Through the Gateway
Now let's turn on tracing. Cortex AI Gateway does two jobs here: it's the model endpoint, speaking the Anthropic Messages API, and it's an OpenTelemetry collector. One URL, one token, and every call is recorded.
Let's start with a snapshot of the gateway spec.
just gateway-snapshot <c>
The gateway spec is account-wide, and the change we're about to make replaces it whole, so this saves exactly what you have now. Teardown restores this snapshot and checks its hash.
Next, let's create the identity the agents call as, and its token.
just service-user <c> just pat <c>
Here's what those do:
- service-user creates TRACE_LAB_SVC, a service user with its own network policy that allows only your machine. Your account-level network policy isn't touched.
- pat mints a programmatic access token for that user, restricted to TRACE_LAB_APP_RL and valid for 7 days. If that token ever leaked, the blast radius is one role, from one network, for at most a week.
Now the important one. Let's turn on client telemetry.
just gateway-config <c>
This adds enable_client_telemetry to the spec. From here on, spans the agents export over OTLP land in AGENT_TRACE_TABLE, right beside the gateway's own. That includes the span for our refund tool, which is a step in the LangGraph graph. Prompt and response payloads aren't captured.
Let's make one real model call to test it all. spike prints a run ID; copy it for the check.
just spike <c> # prints a RUN_ID just check <c> 02_gateway_span -D run_id=<RUN_ID>
On the client side, spike is the standard Anthropic SDK pointed at the gateway URL, with tracing on and a conversation ID header carrying the run ID. That ID is what we'll join everything on.
You should see the spike's rows in AGENT_TRACE_TABLE: model, tokens, status and latency, keyed by the run ID. Spans usually land within about 20 seconds, so if the check fails, give it a few more seconds and rerun it.
Ground Truth and Agents
Now let's give the agents something to work on, starting with the answer key.
just scenario <c> just seed <c> just check <c> 03_ground_truth
Here's what the code does:
- scenario creates the business tables (orders, payments, policy versions and refund requests) plus the views that work out what each request deserved.
- seed loads 60 synthetic refund requests, each built to land in one category: 26 eligible (14 full, 12 partial), 10 out of the refund window, 9 with a payment still pending, 8 already refunded, and 7 on either side of a policy change. On November 15 the refund window shrinks from 30 days to 14, so the same order can be eligible one day and not the next.
- 03_ground_truth checks that the SQL rules agree with every seeded category.
REQUEST_FACTS decides what the business rules say about each request at the moment it was made, from the business facts alone. It never reads a trace. That makes it the answer key: every run is graded against it.
Note: In production, you usually don't get an answer key like this. There, you'd grade runs another way, with an LLM acting as a judge, or by comparing what the agent's trace says it did against the business event it actually produced. We're using a seeded answer key so every grade is exact and repeatable.
Next, the agents themselves. Let's grant them the business tables and set up streaming.
just agents <c> just keypair just set-key <c> just streaming <c>
Here's what the code does:
- agents grants TRACE_LAB_SVC the business tables, and never the answer key.
- keypair generates a key pair, and set-key registers its public half on the service user. Snowpipe Streaming authenticates with a key pair, not a PAT. The private key stays on your machine.
- streaming creates the tables the agents stream into: REFUND_EVENTS, with one row per graph step, and SYNTHETIC_CALLS.
Every table has a default <TABLE>-STREAMING pipe, so there's no pipe to create, just a GRANT INSERT. The agent code opens a channel and appends rows.
Now let's send a real request through all three agents.
just run-one <c> all REQ-008 just check <c> 04_agent_runs
run-one sends the same request, REQ-008, through all three agents. That's six real model calls through the gateway, and each graph step lands as a row in REFUND_EVENTS within seconds. The check should show one run per agent, each with its gateway spans.
Three OTel Sources
Let's look at the same runs from three places at once. The check needs a timestamp, so let's note one first, then run telemetry. It takes about a minute.
date -u '+%Y-%m-%d %H:%M:%S' # note this as <since> just telemetry <c> just check <c> 05_trace_match -D "since=<since>"
telemetry runs three requests through every agent with tracing on in three places:
- LangGraph, through LangSmith's OTel export: which nodes ran, and in what order.
- The Anthropic SDK: what the client saw, latency and retries.
- The gateway: what the server saw, model, tokens and status.
All three carry the run ID as both the trace and the conversation ID, so they're joinable on one ID. Trace delivery is best effort, so 05_trace_match reports a match rate per source and passes at 90%. You'll see all three side by side in the app's case timeline later.
Data at Scale
A handful of runs doesn't tell us what an agent costs over a quarter, so let's add some scale. History takes about a minute, so let's kick it off first and wait for it to finish.
just history <c> # 5M runs over 90 days
history generates 5 million runs over the last 90 days, in SQL, with the same three agents, the same flaws and the same payment system. Every row is labeled with where it came from, so we can always tell synthetic data from live runs. Rerunning it replaces what's there rather than piling on top.
Once history has finished, let's stand up the interactive warehouse and add live traffic on top. Note the timestamp right before simulate.
just iwh <c> just producer-up date -u '+%Y-%m-%d %H:%M:%S' # note this as <since> just simulate <c> # 30 live runs across every request category just check <c> 06_event_counts -D "since=<since>" -D runs=30 -D history_runs=5000000
Here's what the code does:
- iwh creates TRACE_LAB_IWH, the interactive warehouse that serves the app's reads.
- producer-up starts a Docker container that streams new synthetic runs continuously at 0.65 runs per second, the history's own rate, through Snowpipe Streaming.
- simulate streams 30 more live runs across every request category.
- 06_event_counts confirms the history landed at full scale, the 30 live runs streamed in, and the producer is flowing.
An interactive warehouse is built for a different shape of work than a standard one: lots of small queries, often at the same time, that each need an answer in well under a second. It reads our dynamic tables right where they are, with no copy into a separate serving store.
Note: An interactive warehouse has a 5-second query limit, can't run procedures, has a 1-hour minimum auto-suspend, and can't be a default warehouse. So the app sends reads to TRACE_LAB_IWH, sends procedures and
AI_COMPLETEto TRACE_LAB_WH, and names its warehouse on every query.
Join Traces to Outcomes
This is the join, and there's no orchestrator. Let's start with span sync.
just span-sync <c>
Today, a dynamic table can't refresh directly from AGENT_TRACE_TABLE, so span-sync creates a task that copies the lab's spans into TRACE_SPANS every minute. Spans can arrive late, so each run re-reads the last 15 minutes and merges on trace and span ID.
Now let's build the dynamic tables.
just dts <c> just check <c> 07_join_rate # the first refreshes take a minute or two
dts builds four dynamic tables, each with a one-minute TARGET_LAG:
- Incremental: GATEWAY_CALLS, one row per call-level span across about 45 million rows, and RUN_OUTCOMES, each run joined to its ledger rows and graded against the ground truth.
- Full: ROLLUP_BY_VARIANT and ROLLUP_BY_VARIANT_SOURCE. Percentiles can't refresh incrementally, so these refresh in full, but only from RUN_OUTCOMES, never the call rows.
A target lag isn't a schedule. It's a goal: this table should stay within about a minute of the data it reads, and Snowflake decides when to refresh to hit it. With incremental refresh, a refresh only processes what changed since the last one and merges it in. That's what makes a one-minute lag affordable at this scale. The tables are chained, so Snowflake refreshes them in order at a consistent point in time, and a rollup never mixes a fresh outcome with a stale call.
The very first refresh has no previous result to build on, so it computes everything from scratch. That's the minute or two the check waits on. You should see every dynamic table refreshing inside its lag, with traces joined to outcomes on the run ID.
Cases and Writeback
Now let's turn mismatches into work someone can act on.
just app-roles <c> just check <c> 09_cases
app-roles creates the two roles people use the app with, and grants both to you:
- TRACE_LAB_APP_READER_RL reads what the screens show.
- TRACE_LAB_APP_RESOLVER_RL can also resolve cases.
It runs after dts on purpose, because recreating a dynamic table drops its grants. It also builds the case logic:
- CASE_FACTS lists every run where the agent's claim and the ledger disagree: false success, over-refund or wrongful denial. Each case has the one fix the money allows, computed as owed minus posted: refund, reverse or notify. Dismiss is always allowed. Cases with the same agent, outcome, fix and finding share an issue signature.
- DIAGNOSE_ISSUE asks
AI_COMPLETEfor a structured root cause, evidence, a fix for the agent and a message for the customer, from the issue's finding and three sample cases. Results are cached by signature and prompt version. - RESOLVE_CASE and RESOLVE_ISSUE are the only way to write. They check that the case is open and the action fits, compute the amount themselves, and record a decision plus a correction row marked
ORIGIN = 'correction'.
09_cases resolves one case and one issue through those same procedures and confirms a second attempt is refused. The fix comes from the money, not the model. Every decision records CURRENT_USER(), and RUN_OUTCOMES ignores corrections, so the agent's own record stays what the agent did.
Deploy the App
Let's deploy the app. It takes about three and a half minutes: upload, remote build, deploy.
just app-deploy <c> just check <c> 10_app just app-url <c> # the URL again, any time
app-deploy puts the app in the lab's own schema, REFUND_TRACE_LAB.APP, so it doesn't depend on any account-level App Runtime setup, and even the build runs there. It deploys as TRACE_LAB_RL. The role that deploys an app owns it for good, and only the owner can redeploy, so rerun the same command after any change: same service, same URL.
Before the deploy, it gives TRACE_LAB_RL the caller grants the app needs (017_app_deploy.sql). The app runs as you, but only within what the owning role is allowed to do on your behalf: this database, these tables, these warehouses. The grants are inherited, so they cover tables created later too.
Open the URL and sign in with your Snowflake account. You'll notice there's no separate app login. The app runs with caller's rights, so every query runs as you, with your roles, and every resolve is recorded under your name.
Note: The lab roles reach the app as secondary roles. If
app-deploywarns that yours are off, run theALTER USERcommand it prints.
Explore the App
Let's walk the app the way two different teams would use it.
Support ops works the Cases tab:
- The issue queue. Instead of thousands of rows, we get a short list of issues, most money at stake first. Cases that share a cause are grouped, and each one already carries its fix, from SQL, not AI. Each panel shows its query time in milliseconds, served by the interactive warehouse.
- Open the top issue (swift over-refunding). The diagnosis panel shows
AI_COMPLETE's root cause and evidence from three real cases, a fix for the agent and a drafted customer message. They come back as typed fields, so the app renders them instead of parsing prose. Ask again regenerates it. - Open one case. The span timeline shows LangGraph, SDK and gateway spans side by side for that run, with the business rows from it. At the top is the one allowed fix, for example reverse, when more was posted than owed.
- Resolve the case. Confirm writes the correction to the ledger, recorded as you, not as a service account.
The agent owner works the Cost and cause tab. It shows money at stake per day, by failure type, across all five million runs, plus the leaderboard. And here's the punch line: swift is the cheapest per call and the least often right. If we'd picked our agent from the traces alone, we'd have picked the one quietly costing us money. Your numbers will be a little different, but the pattern won't be.
Note: If the deployed app isn't reachable, or you want to change the code, you can run it locally in Docker, signed in through your Snow CLI connection:
just web-dev <c>for a hot-reloading dev server on port 3000, orjust app-up <c>for the production build on port 8080.
Clean Up
Before we go, let's clean up so nothing keeps running in your account. If you want to keep exploring, run stop instead, which pauses everything that bills.
just stop <c> # pause: producer, task, dynamic tables, both warehouses, the app just resume <c> # pick up after stop just teardown <c> # remove everything (asks first) just clean-local # delete keys/ (the PAT and key pair); keeps .env
teardown stops the producer, then restores your gateway spec from the snapshot we took. Only then does it drop the app, REFUND_TRACE_LAB, both warehouses, TRACE_LAB_SVC and its network policy, and the lab roles. If the restore doesn't match the snapshot, it stops before dropping anything.
Important: Use
just teardownrather than dropping objects by hand, so the account-wide gateway spec is restored first. For reference, its final drops are:
-- Drop the lab objects (teardown restores the gateway spec before this) DROP APPLICATION SERVICE IF EXISTS REFUND_TRACE_LAB.APP.TRACE_LAB_APP; DROP USER IF EXISTS TRACE_LAB_SVC; DROP NETWORK POLICY IF EXISTS TRACE_LAB_SVC_POLICY; DROP DATABASE IF EXISTS REFUND_TRACE_LAB; DROP WAREHOUSE IF EXISTS TRACE_LAB_IWH; DROP WAREHOUSE IF EXISTS TRACE_LAB_WH; DROP ROLE IF EXISTS TRACE_LAB_APP_RESOLVER_RL; DROP ROLE IF EXISTS TRACE_LAB_APP_READER_RL; DROP ROLE IF EXISTS TRACE_LAB_APP_RL; -- Drop the role created for this Quickstart DROP ROLE IF EXISTS TRACE_LAB_RL;
Conclusion And Resources
We built every station on the track: traced, streamed, joined, served, explained and shipped. The traces said all three agents were healthy. The ledger showed two of them were quietly costing us money. And it all ran on one copy of the data, under one set of grants, with no exports to a separate store.
What You Learned
- Cortex AI Gateway records model calls and client spans as OpenTelemetry traces, with no collector to run
- Snowpipe Streaming lands agent steps and ledger rows in seconds through default streaming pipes
- Incremental dynamic tables join traces to outcomes on a run ID with a one-minute target lag
- An interactive warehouse serves low-latency, high-concurrency reads straight from dynamic tables
AI_COMPLETEexplains issues as typed fields, while SQL decides the money- A caller's-rights app on Snowflake App Runtime writes governed corrections, attributed to the user
Resources
This content is provided as is, and is not maintained on an ongoing basis. It may be out of date with current Snowflake instances