In this hands-on lab, you will act as a newly hired Retail Security SME at Big Buys, a retailer struggling with a spike in internal employee theft. Your current security tools rely on outdated static rules that fail to catch sophisticated fraud. Your mission is to build a defensible security platform that moves beyond simple reporting to advanced behavioral analysis.

What You Will Build

You will modernize the Big Buys security stack by integrating Python and AI Agents on Sigma on top of Snowflake to create a comprehensive "Loss Prevention App V2.0". Specifically, you will:

Target Audience

Participants of Snowflake Summit 2026 who are interested in getting hands-on with Sigma and Snowflake. No SQL, Python, or technical data skills are required for this hands-on lab.

Prerequisites

Footer

Step 1: Use this link to navigate to Sigma

Step 2: Create an account and then enter your email address:

Step 3: Check your inbox for a message from info@send.sigmacomputing.com and continue the sign-up process by clicking the link in that email.

Step 4: Enter your information as prompted and click Submit.

Step 5: Once you see the Sigma homepage, you are ready to proceed:

From the Sigma home page, navigate to the templates section and search for and select the Snowflake Summit 26 - Loss Prevention App Template:

Once you see the Loss Prevention Application, click the blue Explore button and then Save as and save the workbook using the format shown, replacing {YOUR_NAME} to create a unique copy:

LOSS_PREVENTION_APP_

Once saved, you're ready to proceed!

Footer

Welcome to the team! As a newly hired Shrink Expert, your first week is focused on getting "the lay of the land." Big Buys has been overwhelmed with security alerts, and you have been brought in to build a superior detection system from the ground up.

Before rolling out new solutions, we must evaluate the legacy tools.

Currently, the company relies on an Exception Based Reporting (EBR) dashboard, a system of rigid, hard-coded rules designed to catch theft. While functional, it is creating excessive "noise" leading to a loss of credibility with store managers.

Goal:
Pressure-test the existing infrastructure using the Loss Prevention App v1.0 to determine if flagged transactions are legitimate or if these legacy rules are simply burying managers in unnecessary paperwork.

Understanding Exception Based Reporting (EBR)

Big Buys currently utilizes four static, threshold-based rules:

While these catch obvious errors, they lack the nuance required for modern retail.

Investigate a High-Risk Location

Step 1: Locate the High Risk Locations table on the main dashboard:

Use the State filter to drill down specifically to Oregon:

Step 2: Observe that Store 100650 - Big Buys Salem is flagged as the highest risk location in Oregon, containing the highest volume of flagged transactions:

Step 3: Click on the Select Store column next to 100650 - Big Buys Salem to filter the entire dashboard to this specific location:

Step 4: Review the Flagged Transactions by Cashier chart. Noreen Swift stands out as the cashier with the highest volume of suspicious activity:

With Sigma, you can click on an element to see the underlying data directly.

For example, you could could select the bar chart and Show underlying data to see the flagged transaction detail data:

You could do further analysis directly there, or use AI Agents as shown in the next step.

Click the X` to close the modal:

We will use Sigma Assistant to investigate Noreen Swift's performance, starting with broad metrics and narrowing our focus.

Sigma Assistant

Step 5: Click the icon in the upper left corner of the page to return to the homepage and navigate to Sigma Assistant.

Ensure that the Cortex agent named LOSS_PREVENTION_CORTEX_AGENT is selected in the agent selection window.

Let's ask a specific question about Noreen Swift:

Summarize Noreen Swift's performance history, her ratings, key strengths, and any notable trends.

We can see that the agent has summarized her performance with a large number of related statistics. There are a large number of flagged transactions, but we want to dig deeper.

Step 6: Ask a follow-up question to see the flags in action:

Show me all the transactions Noreen handled along with the flags.

Again, we get a lot of information back, but we will want to dig deeper.

Step 7: Click the Open in Workbook icon in the Sigma Assistant view to move into a full Sigma workbook for a deeper technical investigation:

Analyze a Specific Transaction

Step 8: With the workbook open, locate the HIGH_VALUE_VOID_FLAG column. Apply a filter to show only records with a TRUE value:

Sort the data by Price in descending order to focus on the high-value alerts:

Step 9: Order Number 100284237 stands out. It contains a high-priced item that was voided. Click on the order number and select Keep only 100284237.

This creates a specific filter for this transaction:

Step 10: Disable the filter on HIGH_VALUE_VOID_FLAG to view all items within this specific order:

Key Findings

Our static EBR rule flagged the $3,000+ void as suspicious immediately. However, in this case, this wasn't "sweethearting" or theft. The customer simply decided the high-end laptop was too expensive after already purchasing a different gaming PC. Noreen Swift followed proper procedure, yet the system flagged her as a risk.

Conclusion

Static rules create false alerts for employees doing their jobs correctly. To protect Big Buys, we must transition to an ML-powered Anomaly Detection engine that can distinguish between suspicious behavior and standard customer exchanges.

Footer

Objective: In this module, you will compare the flawed "static rules" from Module 1 with a Python-based machine learning model. You will detect "Sweethearting" by analyzing the time gap between scans (Inter-Scan Latency), a behavioral pattern that is impossible to fake.

Prepare the Data

Step 1: Let's return to our saved workbook by clicking on Your documents and selecting the LOSS_PREVENTION_APP_ with your name that we saved earlier:

Step 2: Place the workbook in Edit mode, navigate to the Anomaly Detection page.

You will see the POS table (BIG_BUYS_POS_ENRICHED_SHRINK_FLAGS) which includes the store filter from Module 1:

Step 3 (if required): Add a filter on the STORE_IDENTIFIER column. Select Store 100650 - Big Buys Salem:

Step 4: Create a Child Table element from the filtered POS BIG_BUYS_POS_ENRICHED_SHRINK_FLAGS table:

Rename this new table: BIG_BUYS_POS_PYTHON_TEST

Add the Python Anomaly Detection Script

Step 5: Add a Python element from the Element bar > Data group, placing it below the BIG_BUYS_POS_PYTHON_TEST child table:

The Python script for anomaly detection is provided below. The code is commented so that you can understand how it works:

import pandas as pd

import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import LabelEncoder, StandardScaler

# 1. Get Sigma data
df = sigma.get_element('BIG_BUYS_POS_PYTHON_TEST').to_pandas()
df['SCAN_TIMESTAMP'] = pd.to_datetime(df['SCAN_TIMESTAMP'])
df = df.sort_values(['ORDER_NUMBER', 'IDX'])

# 2. Behavioral Feature Engineering
# Calculate the raw gap between scans (ISL)
df['ISL'] = df.groupby('ORDER_NUMBER')['SCAN_TIMESTAMP'].diff().dt.total_seconds().fillna(0)

# Calculate ISL Ratio: The core 'Subtle Pause' detector
df['EXPECTED_ISL_SEC'] = df['EXPECTED_SCAN_IN_MILLISECONDS'] / 1000
df['ISL_RATIO'] = df['ISL'] / df['EXPECTED_ISL_SEC'].replace(0, 1)

# Categorical Encoding for Context
le_family = LabelEncoder()
df['FAMILY_ENCODED'] = le_family.fit_transform(df['PRODUCT_FAMILY'])

# 3. Define the Context-Aware Feature Set
# Including TENURE_DAYS prevents flagging efficient veterans
features = ['PRICE', 'TENURE_DAYS', 'ISL', 'ISL_RATIO', 'FAMILY_ENCODED']
X = df[features].fillna(0)

# 4. Train the Isolation Forest
# Contamination set to 1% to isolate the most extreme outliers
model = IsolationForest(contamination=0.01, random_state=42)
df['STATUS_CODE'] = model.fit_predict(X)

# 5. Adjusted Scoring Logic
# Capture the raw anomaly scores (typically between -0.135 and +0.12)
df['RAW_SCORE'] = model.decision_function(X)

# Transform RAW_SCORE to a 0-100 Risk Scale
# Logic: Lower raw scores (negative) = Higher Risk
min_raw = df['RAW_SCORE'].min()
max_raw = df['RAW_SCORE'].max()
df['RISK_SCORE'] = 100 * (1 - (df['RAW_SCORE'] - min_raw) / (max_raw - min_raw))

# Final Status Assignment
df['STATUS'] = np.where(df['STATUS_CODE'] == -1, 'Anomaly', 'Normal')
df['ML_ANOMALY_FLAG'] = np.where(df['STATUS_CODE'] == -1, True, False)

sigma.output('python_output', df)

Step 6: Copy and paste the code into the Python element, replacing the sample code:

Step 7: Click Run (lower right corner of the element):

Once the output is generated, click on the output result. Create a child Table element from the Python output:

Rename the table MODEL_COMPARISON.

Visualize the Comparison

We will now use this table to visualize the output to compare the Python model against the original static rules.

Step 8: Create a child Chart from the MODEL_COMPARISON table:

You may want to adjust the bar and line colors to better differentiate them:

You will likely notice that the Python ML model (the red line) is significantly more selective, reducing the "noise" created by the rigid, hardcoded static rules (the grey bars):

Footer

In this module, we will review a WIP version of the Loss Prevention App V2.0 which will allow store managers to act on these insights immediately, closing the loop between detection and resolution.

Update High Risk Locations Table

Select the App v2.0 page to see the High Risk Locations table. (The underlying source has been pre-updated to the Python model output):

Step 1: In the Element panel add a new column in the GROUP BY > CALCULATIONS section named Transactions, using the formula:

COUNT([SCAN_ID])

Step 2: Set Transactions to use a whole number format:

Step 3: Add a third column calculation named PERCENT FLAGGED using the formula:

[FLAGGED TRANSACTIONS] / [TRANSACTIONS]

Step 4: Change the PERCENT FLAGGED column to use %:

Step 5: Sort the table by the PERCENT FLAGGED column in descending order to prioritize high-risk stores:

Step 6: Add Conditional formatting to the PERCENT FLAGGED column:

Add Format type > Color Scale > Custom > Sequential.

Sigma presents two square boxes that when clicked, allow you to set a custom color.

For the left box, use #FFFFFF and for the right, #761A10:

Publish the workbook and select Go to published version before proceeding:

Review Case Management

Select the CASE MANAGEMENT tab:

Clicking on any cell in the SCAN_ID column triggers a modal containing an approval workflow.

If the detail information is enough, you can choose to APPROVE, REJECT or ESCALATE a transaction:

For example, approving a transaction updates the REVIEW STATUS column and COMMENTS as well.

Footer

In this module, we will add advanced agentic capabilities to streamline the review process. By integrating AI agents directly into the workflow, we enable natural language querying of transaction data and automated case dispositioning.

Configuration of Custom Sigma Agents

Deployment of the Review Assistant

Close the current view and place the workbook back into Edit mode.

Navigate to the AI_MODAL page in the Sigma workbook and follow these configuration steps:

  1. Create a chat element from the Element Bar: select UI, and choose Chat

  1. In the Chat element, choose Select agent and then select Create a new agent:
  2. Rename the agent from Agent 1 to SHRINK_SIGMA_AGENT.
  3. Paste the provided instructions into the Instructions field, overwriting the placeholder text:
Role: You are a Fraud & Operations Analyst Assistant. Your purpose is to interpret Isolation Forest Python model results using the analyze_with_cortex tool and execute system actions (Dashboard Updates and Transaction Approvals) within the Sigma environment.

When first invoked, do not run any queries. Just introduce yourself and ask the user how you can help them.

1. Analysis Protocol (Cortex)

- Primary Tool: Use analyze_with_cortex for ALL analysis and data interpretation tasks.
- Analyst Routing: Direct all Python-related or model-output questions specifically to the ISOLATION_FOREST_MODEL_OUTPUT_INTERPRETER analyst.
- Logic Overrides:
  - ISL (Inter-Scan Latency): An ISL of 0 seconds indicates the first item scanned. Treat ISL 0 as legitimate. Do not flag or interpret it as an anomaly.
- Evaluation Requirements: When an Order Number is queried, you must analyze all associated records (both "Anomaly" and "Normal").
  - Itemization: List details and status for every record in the order.
  - Anomaly Attribution: Explain specific triggers using raw scores, risk scores, and context.
  - Comparative Analysis: For "Normal" records, explain why they fell below the risk threshold relative to the flagged items.

2. Dashboard Control Logic (Sigma Actions)

When a user requests to filter or update the dashboard for a specific store, apply the following logic:
- Numerical Input: If the user provides a 6-digit number (e.g., 100060), map this to the STORE_KEY control.
- Text Input: If the user provides a location name (e.g., "Big Buys Salem"), map this to the STORE_NAME control.
  - Note: All stores follow the naming convention "Big Buys [City]".
- Fallback Mechanism: If a control change returns "No Data" or the store cannot be identified, provide the user with 3 relevant store options to choose from.

3. Case Management & Approvals

- Workflow: To review flagged transactions, access the CASE MANAGEMENT table.
- Pre-Action Requirement: You must select the record and ask the user clarifying questions before modifying any data in the CASE MANAGEMENT input table.
- State Management: After any update to the CASE MANAGEMENT table, you must trigger a data refresh to ensure the user sees the most up-to-date information.
  1. On the right under Configure > Data elements use the + to add CASE MANAGEMENT from the App v2.0 page.
  2. Under Warehouse agents, select LOSS_PREVENTION_CORTEX_AGENT:

  1. Now let's add and configure an action to update the CASE MANAGEMENT input table based on user response to the agent:

  1. Click Save and then Publish and Go to the published version.
  2. Now let us test the agent's workflow:
    • Invoke the agent by clicking the agent icon (message icon) in the top right corner of App v2.0:

Show me the most risky transaction at the store in Salem.

This order looks suspicious. Escalate the transaction.

Use the following prompt:

Use ESCALATED as the status. For Notes, use your best judgement. Escalate only the specific scan.

Footer

Now that your Loss Prevention App V2.0 is complete, you can share it with store managers and configure automated exports.

Set up Email Burst

Step 1: Set up the email burst:

Click Create New schedule.

Select Export as email burst:

Step 2: Configure the recipients.

Step 3: Select App v2.0 - CASE MANAGEMENT as the attachment and click Create:

The export gives you a list of flagged transactions with the relevant Review Status.

For more information, see Reports overview

There is also a QuickStart, Fundamentals 11: Pixel Perfect Reporting

Footer

In this workshop, you successfully transitioned a legacy retail security strategy into a high-precision, AI-integrated operational platform. By moving away from rigid, manual thresholds and embracing behavioral analytics, you have mitigated the "noise" of false positives and provided store managers with actionable intelligence.

Core Achievements

Technical Conclusion

You have successfully engineered Loss Prevention App V2.0. This solution represents a shift from simple data reporting to a system that detects intent, explains context, and facilitates resolution.

Additional Resource Links

Blog
Community
Help Center
QuickStarts

Be sure to check out all the latest developments at Sigma's First Friday Feature page!

   

Footer