A Production Architecture for Snowflake CoCo Automations
From the publisher’s feed, collected in the ZeroLabs newsroom.
How AGENT TASKs Turn a Prompt Into a Scheduled, Sandboxed, Observable Data Operations Pipeline — Without a Warehouse, a DAG, or a YAML FileFrom Prompt to Production: How Snowflake CoCo Automations turn a natural-language prompt into a scheduled, sandboxed, and observable data-operations workflow — without a warehouse, DAG, or YAML file.TL;DR: CoCo Automations (Public Preview, August 21, 2026) let you schedule a natural-language prompt as a recurring Snowflake AGENT TASK. Each run executes in a managed sandbox under your default role, creates an inspectable Cortex thread, and incurs task billing plus CoCo token consumption. This article covers the architecture, five production-ready patterns, Restricted Session Scope governance, hooks, monitoring SQL, preview limits, and a deployment checklist — everything a data engineering team needs to move lightweight operational workflows off EC2 cron and into the Snowflake trust boundary.What You Will LearnHow CoCo Automations work architecturally and where they fit relative to traditional orchestrationFive concrete automation patterns with original prompts you can deploy todayHow to lock down automations with Restricted Session Scope (GA) and least-privilege RBACThe default-role trap that causes most automation failures and how to avoid itMonitoring SQL for task history, Cortex thread inspection, and cost attributionPreview limits and trade-offs to evaluate before adoptingThe Problem: Operational Glue That Lives Outside SnowflakeEvery Snowflake deployment has a shadow layer of operational scripts that nobody owns cleanly. A cron job on an EC2 instance queries WAREHOUSE_METERING_HISTORY, formats the output, and posts to Slack — with credentials that rotate manually and a Slack token in an environment variable. A Lambda function fires hourly to check credit consumption against a threshold, carrying its own IAM role, deployment pipeline, and failure mode. A GitHub Actions workflow validates data freshness using a service account key pair and pushes alerts to PagerDuty.Each script is simple in isolation. Together they form an unmanaged fleet of micro-automations spread across AWS, Azure, GitHub, and local cron. The architectural friction is not complexity — it is fragmentation. Authentication is scattered. Observability is per-tool. Cost attribution is impossible. And when the person who wrote the Lambda leaves the company, the Lambda stays running until it breaks.CoCo Automations collapse this fleet into a single architectural pattern: one prompt, one schedule, one trust boundary.| Dimension | External Glue | CoCo Automation ||--------------------|-----------------------------------|----------------------------------------|| Compute | EC2, Lambda, GitHub Actions | Snowflake-managed sandbox || Authentication | Service account key pair, IAM role| User identity, default role || Scheduling | cron, EventBridge, GitHub cron | AGENT TASK schedule || Observability | CloudWatch, custom logging | Cortex threads, task history || Governance | Per-tool IAM policies | Restricted Session Scope, RBAC || Cost attribution | Separate billing per service | Snowflake task billing + CoCo tokens || Deployment | Terraform, CDK, manual SSH | cortex automation create |What Changed: AGENT TASKs and the Managed SandboxCoCo Automations entered Public Preview on August 21, 2026 (release notes), available in all commercial regions on AWS, Azure, and GCP. They are not available in government, FedRAMP, DoD, VPS, or China deployments.How the Execution Model Differs from Traditional TasksA traditional Snowflake task executes a SQL statement or stored procedure on a warehouse you provision and a role you assign. An AGENT TASK is fundamentally different: it boots an entire CoCo sandbox — a containerized environment with file system, bash, and tool access — then runs an LLM agent loop against your prompt. The agent can read files, execute SQL, call MCP servers, and write output, all within that sandbox. No warehouse provisioning is required; Snowflake manages the compute.Each automation lives as an AGENT TASK in USER$.PUBLIC, prefixed with COCO_ROUTINE_. The sandbox mounts the user's DEFAULT$ workspace stage at /workspace by default, so files written there persist between runs. When the schedule fires, Snowflake creates a Cortex thread for the run — every agent message, tool call, and result is captured in that thread and linked to the parent task's history.The key architectural distinction: this is not “scheduled SQL.” It is a scheduled agent with access to the full CoCo toolset, running under your identity, constrained by your RBAC and (optionally) a Restricted Session Scope ceiling.Snowflake Agent Task architecture: scheduled execution, sandboxed agent loop, and the two policy boundaries that constrain it.The Default-Role TrapThis is the single most common cause of automation failures, and it catches experienced engineers.Consider this scenario: you build an automation interactively in CoCo under the DATA_ENGINEER role. It queries SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY, formats a cost report, and writes it to /workspace. Everything works. You schedule it for 7 AM daily. The first scheduled run returns zero rows.The reason: scheduled runs execute under your default role, not whatever role was active in your CoCo session. If your default role is PUBLIC — or any role without IMPORTED PRIVILEGES on the SNOWFLAKE database — the ACCOUNT_USAGE query silently returns nothing. The run "succeeds" with an empty report.Before scheduling any automation:-- What role will your automation actually run under?SHOW PARAMETERS LIKE 'DEFAULT_ROLE' IN USER;-- If it's wrong, fix it:ALTER USER SATISH SET DEFAULT_ROLE = 'DATA_ENGINEER';-- Verify your default role can reach the objects your prompt needsUSE ROLE DATA_ENGINEER;SELECT COUNT(*) FROM SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORYWHERE START_TIME >= DATEADD('hour', -24, CURRENT_TIMESTAMP());Also check your default secondary roles. If set to ALL, the run can access any object reachable through any of your granted roles — which may be more than you intend for an unattended agent.Preview LimitsDuring public preview, the following constraints apply:Minimum schedule frequency: 1 hour. The CLI parser accepts shorter intervals, but sub-hourly is not supported.Thread and run history retention: 2 months.Schedules are time-based only. Event-based triggers (e.g., stream-driven) are not supported.No mid-run attachment. You cannot connect to a running automation or resume it interactively. Inspection is read-only via thread transcripts.Sandbox provisioning adds startup latency. Runs may take extra time to begin while Snowflake spins up the sandbox.Implementation: Five Production Automations1. Daily Warehouse Cost Anomaly DetectorProblem: Warehouse spend creeps up without detection until the monthly bill arrives.Prompt file: prompts/daily-cost-monitor.mdQuery SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY for the last 24 hours.Group credit consumption by warehouse name.Flag any warehouse that consumed more than 50 credits in a single day.Compare today's total to the 7-day rolling average.If any warehouse exceeds 150% of its rolling average, mark it as anomalous.Write a summary table to /workspace/cost-report.md with columns:warehouse, credits_today, rolling_avg_7d, pct_change, status.This run is unattended. Do not ask follow-up questions.End with a one-line status: CLEAN if no anomalies, ALERT if any found.cortex automation create \ --name wh_cost_anomaly \ --prompt-file prompts/daily-cost-monitor.md \ --schedule "daily at 7am" \ --timezone America/Los_Angeles \ --model auto2. Dynamic Table Refresh Lag MonitorProblem: Dynamic tables with TARGET_LAG settings can fall behind without triggering any alert. By the time someone notices, downstream dashboards have been serving stale data for hours.cortex automation create \ --name dt_lag_monitor \ --prompt "Query SNOWFLAKE.ACCOUNT_USAGE.DYNAMIC_TABLE_REFRESH_HISTORY for the last 2 hours. \For each dynamic table, compare the actual refresh lag to its configured TARGET_LAG. \Flag any table where actual lag exceeds 2x the target. \Include the fully qualified table name, target_lag, actual_lag, last_refresh_time, and state. \Write results to /workspace/dt-lag-report.md. \This run is unattended. Do not ask questions. \End with: HEALTHY if all within threshold, DEGRADED if any exceeded." \ --schedule "every 2 hours"3. Data Freshness SLA CheckProblem: Executive dashboards query tables that may not have refreshed within SLA, but nobody checks until an executive complains.cortex automation create \ --name freshness_sla \ --prompt-file prompts/data-freshness-check.md \ --schedule "every Tuesday at 8am and every Thursday at 3pm" \ --timezone America/New_York4. MCP-Connected Jira Sprint Velocity ReportProblem: The data engineering backlog grows without visibility into actual throughput. Standup discussions rely on memory instead of data.cortex automation create \ --name sprint_velocity \ --prompt "Connect to the Jira MCP server. Pull all issues in the DATA-PLATFORM project \that transitioned to Done in the last 7 days. Group completed issues by epic. \Calculate story points completed per epic vs. points planned at sprint start. \List any issues still In Progress for more than 5 business days. \Write the velocity report to /workspace/sprint-velocity.md. \This run is unattended. Do not ask follow-up questions. \End with: ON_TRACK if >80% of planned points completed, AT_RISK otherwise." \ --schedule "every Monday at 8:30am" \ --timezone America/Chicago \ --mcp PLATFORM_DB.MCP.JIRA_CONNECTOR5. Schema Drift DetectorProblem: Production schemas change without warning — a column gets renamed, a table is dropped, a data type changes — and downstream pipelines break hours later.cortex automation create \ --name schema_drift \ --prompt-file prompts/schema-drift-detector.md \ --schedule "daily at 5am" \ --timezone UTCPrompt file: prompts/schema-drift-detector.mdQuery SNOWFLAKE.ACCOUNT_USAGE.COLUMNS for the ANALYTICS database.Compare today's column inventory (table_name, column_name, data_type, ordinal_position)against yesterday's snapshot stored in /workspace/columns-snapshot.csv.If /workspace/columns-snapshot.csv does not exist, create it from today's data and exit.If it exists, diff the two sets and report:- New columns added (table, column, type)- Columns removed (table, column)- Data type changes (table, column, old_type, new_type)Write drift results to /workspace/schema-drift-report.md.Overwrite /workspace/columns-snapshot.csv with today's data for the next run.This run is unattended. Do not ask questions.End with: NO_DRIFT if no changes, DRIFT_DETECTED with count if changes found.Security and GovernanceLeast-Privilege RBAC for AutomationsThe EXECUTE AGENT TASK privilege is granted to PUBLIC by default — meaning every user in your account can create automations. For production environments, replace this with a tiered privilege model:USE ROLE SECURITYADMIN;-- Remove the default grantREVOKE EXECUTE AGENT TASK ON ACCOUNT FROM ROLE PUBLIC;-- Tier 1: Can create and manage their own automationsCREATE ROLE IF NOT EXISTS AUTOMATION_CREATOR;GRANT EXECUTE AGENT TASK ON ACCOUNT TO ROLE AUTOMATION_CREATOR;-- Tier 2: Can view automation history but not create-- (uses standard MONITOR privilege on the user's task objects)CREATE ROLE IF NOT EXISTS AUTOMATION_VIEWER;-- Assign to specific usersGRANT ROLE AUTOMATION_CREATOR TO USER DATA_ENGINEER_1;GRANT ROLE AUTOMATION_CREATOR TO USER PLATFORM_LEAD;GRANT ROLE AUTOMATION_VIEWER TO USER ENGINEERING_MANAGER;Restricted Session ScopeRestricted Session Scope (RSS) became generally available on September 3, 2026. RSS is a privilege ceiling — it limits what an agent can do on behalf of a user without modifying their roles. For automations, this is the governance control that makes unattended agent runs acceptable in regulated environments.Without RSS, an automation created by a user who holds ACCOUNTADMIN runs with ACCOUNTADMIN privileges. The agent could, in theory, drop a database if the prompt is ambiguous enough. RSS caps the damage surface.-- Create an RSS: read everywhere, write only to the user's personal DBCREATE OR ALTER RESTRICTED SESSION SCOPE governance_db.public.automation_ceiling AS $$privilege_scopes: allowed_privileges: - privileges: [data read, program usage, object discovery, compute usage] account: [all] - privileges: [data write] databases: [USER$]role_scopes: blocked_roles: [ACCOUNTADMIN, SYSADMIN, SECURITYADMIN] allow_role_switching: false$$;-- Attach it to a session policyCREATE SESSION POLICY governance_db.public.agent_ceiling_policy AGENT_RESTRICTED_SESSION_SCOPE = 'GOVERNANCE_DB.PUBLIC.AUTOMATION_CEILING';-- Apply account-wide (user-level overrides are also supported)ALTER ACCOUNT SET SESSION POLICY governance_db.public.agent_ceiling_policy;For simpler setups, use a predefined scope instead of writing YAML:Hooks are bash commands that run before and after the agent loop. They are deterministic, don’t consume agent turns, and are useful for fixed setup and teardown. But their failure semantics are counterintuitive, and this catches people.What I learned running hooks in practice:A broken pre-run hook doesn’t fail the run. The sandbox becomes unavailable, every tool call the agent makes fails, and the agent produces a response saying “I couldn’t access the tools.” But task history reports SUCCESS. If you rely on task state for alerting, you will miss this entirely.A broken post-run hook loses output silently. If your post-run hook is the thing that publishes results — a git push, a file copy, an API call — and it fails, the agent's work is gone. Task history still says SUCCESS.You cannot append to files on the mounted workspace stage. The >> operator fails with Operation not supported on any existing file. This also kills Git: Git appends to .git/logs/HEAD after the first commit, so a persistent repo on /workspace fails on the second run. Clone to /tmp instead — it is re-created each run.# Pattern: clone to /tmp, not /workspacecortex automation create \ --name code_review \ --prompt-file prompts/code-review.md \ --schedule "daily at 6am" \ --pre-run-hook "git clone --depth 1 https://github.com/acme/analytics /tmp/analytics" \ --pre-run-timeout 90Production rule: Never rely on task state alone. Always inspect the Cortex thread transcript to verify that hooks executed and the agent completed its intended work.Monitoring and ObservabilityTask HistoryTwo sources are available. SNOWFLAKE.INFORMATION_SCHEMA.TASK_HISTORY gives zero-latency results but caps at 7 days. SNOWFLAKE.ACCOUNT_USAGE.TASK_HISTORY supports 365 days but has up to 45 minutes of latency.-- Recent runs for a specific automation (zero latency, max 7 days)SELECT name, state, scheduled_time, completed_time, DATEDIFF('second', scheduled_time, completed_time) AS duration_sec, error_code, error_messageFROM TABLE(SNOWFLAKE.INFORMATION_SCHEMA.TASK_HISTORY( TASK_NAME => 'COCO_ROUTINE_WH_COST_ANOMALY', SCHEDULED_TIME_RANGE_START => DATEADD('day', -7, CURRENT_TIMESTAMP())))ORDER BY scheduled_time DESC;Cortex Thread InspectionEach run produces a Cortex thread containing every agent message, tool call, and result. The THREAD_MESSAGES function returns JSON:-- Retrieve the full transcript for a runSELECT TRY_PARSE_JSON( SNOWFLAKE.CORTEX.THREAD_MESSAGES()) AS messages;To find the thread ID, use cortex automation doctor from the CLI, or extract the query_id from task history and trace it to the thread.CLI Management# List all automations and their statecortex automation list# Detailed status, recent runs, and thread IDscortex automation doctor wh_cost_anomaly --limit 5# Trigger an immediate run (outside schedule)cortex automation execute wh_cost_anomaly# Trigger and wait for completioncortex automation execute wh_cost_anomaly --wait# Pause scheduled runscortex automation suspend wh_cost_anomaly# Resume scheduled runscortex automation resume wh_cost_anomaly# Delete the automation permanentlycortex automation drop wh_cost_anomaly# Read the full transcript of a specific runcortex conversations transcript CostDuring public preview, automations incur two cost streams:Standard Snowflake task billing — serverless compute for the AGENT TASK execution.CoCo token consumption — model inference credits, tracked in CORTEX_AI_FUNCTIONS_USAGE_HISTORY.System-initiated analysis does not incur charges. There is no warehouse cost for the automation itself; however, SQL queries the agent executes run against the user’s default warehouse.Cost optimization:--model auto lets Snowflake select the most cost-effective model for the task.Keep prompts focused. A prompt that does one thing well costs fewer tokens than a prompt that does five things loosely.Use hooks for deterministic setup instead of burning agent turns on pip install or git clone.Use --dry-run to preview the generated AGENT TASK SQL without creating the automation.Trade-OffsWhen to Use CoCo AutomationsLightweight operational checks that currently run on human memory or fragile cron jobsMonitoring workflows that query ACCOUNT_USAGE views and produce natural-language summariesDigests that combine SQL results with formatting, context, and recommendationsMCP-connected workflows (Jira, Slack, GitHub) that need Snowflake data contextWhen to Avoid CoCo AutomationsProduction ETL/ELT where determinism and idempotency are requiredWorkflows needing parallel fan-out or complex dependency graphsJobs where any variation in agent behavior is unacceptableWorkloads requiring more compute than a single sandboxSub-hourly scheduling requirementsFedRAMP, DoD, or government compliance environmentsProduction Deployment ChecklistDefault role verified: DEFAULT_ROLE can access all objects the prompt needsDefault secondary roles reviewed: not unintentionally granting broad accessRestricted Session Scope configured and attached via session policyEXECUTE AGENT TASK revoked from PUBLIC, granted to specific rolesPrompt tested interactively under the default role (not your current session role)Prompt includes “unattended” instructions: no follow-up questions, explicit output path, success/failure status lineHooks tested independently; post-run hook failure path consideredWorkspace persistence strategy decided: mounted stage vs. --no-workspaceCost monitoring in place: SERVERLESS_TASK_HISTORY + CORTEX_AI_FUNCTIONS_USAGE_HISTORYThread inspection process documented for the operations teamMCP server access verified under the default role (if applicable)SummaryFive architectural takeaways:CoCo Automations are not scheduled SQL. They are scheduled agent runs with access to bash, files, MCP servers, and the full CoCo toolset. This makes them suited for operational workflows that need reasoning, not just execution.The default-role trap is real. Test every automation under your DEFAULT_ROLE, not your interactive session role. This is the number one source of "it worked in my session but failed on schedule."RSS is your governance boundary. Without Restricted Session Scope, an unattended agent inherits whatever privileges the creating user has — including ACCOUNTADMIN. Apply RSS as a standing control, not an afterthought.Task history lies about hooks. A failing hook does not fail the run. The only reliable source of truth is the Cortex thread transcript.The right comparison is not Airflow. CoCo Automations replace the operational glue that currently lives on EC2 cron, Lambda, and GitHub Actions — the scripts nobody owns, nobody monitors, and nobody can attribute cost to.The important change is not that Snowflake can schedule a prompt. The important change is that an entire category of micro-automations — the ones that fragment your authentication, scatter your observability, and hide your costs across three cloud consoles — can now live inside a single trust boundary, governed by RBAC and RSS, observable through Cortex threads, and deployed with one command.GitHub RepositoryThe complete Snowflake CoCo automations implementation is available on GitHub:snowflake-coco-automationsYou can explore the implementation, review the automation workflows, and use the repository as a starting point for your own Snowflake CoCo automation projects.Found this useful? 👏 Give it a clap — it helps others discover it too.Follow for weekly Snowflake engineering deep dives, practical architecture insights, and technical quick bytes. ❄️You may use, share, adapt, and build upon this work. For public redistribution or substantial adaptation, please retain attribution and include a link to the original article or repository and the author’s LinkedIn profile. Private and internal use requires no attribution. Provided “as is” for educational purposes. Please validate and test all examples before using them in production. Views are my own and do not represent any current or former employer.A Production Architecture for Snowflake CoCo Automations was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.