1. Overview
Retailers, consumer brands, and mobility operators plan inventory, staffing, and promotions around one recurring question: how much demand will this location see over the next two weeks? Answering it for every store, product, or station—rather than for the business as a whole—is fine-grained demand forecasting. Training a separate model for every series gets slower and more expensive as locations and products grow. Planners also need to know whether last month's promotion worked, which locations have unusual or broken data today, and who can call the AI models behind those answers.
In this codelab, you build that fine-grained demand forecasting solution entirely in BigQuery SQL. Each of the busiest bike-share stations in bigquery-public-data.new_york_citibike.citibike_trips plays the role of a store-level demand series, and daily trips play the role of units sold. Instead of training one model per series, you forecast every station at once with zero-shot TimesFM (Google's pre-trained Time Series Foundation Model). You then measure promotion lift against control locations, quarantine broken sensor feeds before anomaly detection, and turn the results into an executive brief.
Calling foundation models from SQL introduces two operational risks: IAM governance and data reliability. First, analysts with broad project roles can invoke BigQuery AI.GENERATE implicitly with end-user credentials (EUC)—omitting connection_id so BigQuery uses the caller's own credentials—without centralized cost controls. Second, unguarded time-series pipelines miss planned promotional drivers or degrade on flatlined sensor feeds. Using service account impersonation, you verify that least-privilege analysts cannot make implicit EUC calls even while Gemini Enterprise Agent Platform (aiplatform.googleapis.com, the API hosting Gemini models) stays enabled. Instead, they must route requests through an approved BigQuery Cloud Resource connection.
The same pattern applies to store-and-SKU sales, warehouse throughput, or call-center volume: replace the station with your location or product key and the trip count with your demand measure.

The diagram shows the method you follow in this codelab, read clockwise from the top left:
- Business questions: start from three questions about demand, data quality, and promotions.
- Data preparation: build daily demand tables from public bike-share trips.
- Predict: forecast 14 days for every station, and measure accuracy on held-out days.
- Monitor: set aside a flatlined feed, and flag unusual days.
- Explain and generate executive brief: restrict who can call Gemini, measure whether the promotion worked, and generate the brief.
- Decisions: after the lab, use the forecast and the brief for staffing, repair, and promotion decisions.
Code samples in this codelab are licensed under the Apache License, Version 2.0.
What you'll learn
- Run zero-shot multivariate demand forecasting with
AI.FORECAST(Preview) using past and future covariates inside the supported context window, and evaluate 14-day holdout accuracy withAI.EVALUATE. - Build pre-flight SQL variance guardrails (
STDDEV_POP) that quarantine degenerate zero-variance (constant-value) time series before runningAI.DETECT_ANOMALIES. - Enforce and verify least-privilege IAM isolation for BigQuery
AI.GENERATEvia--impersonate-service-accountwhileaiplatform.googleapis.comstays active, and audit per-principal job attribution inINFORMATION_SCHEMA.JOBS. - Quantify promotional lift against parallel negative-control stations with
AI.CAUSAL_EFFECT(Preview). - Generate typed
STRUCTexecutive briefs as the restricted analyst withAI.AGG(output_schema, GA) and Gemini Flash over the governed connection.
What you'll do
- Configure environment variables, enable required APIs, and build per-location daily demand tables from public NYC Citi Bike trips.
- Forecast the next 14 days for every station in one zero-shot query, and evaluate 14-day holdout accuracy against historical demand.
- Quarantine a broken sensor feed, then detect real ridership anomalies on unpromoted stations.
- Lock Gemini access behind an approved Cloud Resource connection, and prove it as a restricted analyst.
- Measure promotion lift against unpromoted control stations, and have the analyst generate a typed executive brief.
- Clean up every cloud resource the lab created.
What you'll need
- A Google Cloud project with billing enabled and permissions to enable APIs, create service accounts, modify project and BigQuery connection IAM policies, and run BigQuery jobs (
roles/owneror equivalent admin roles). - Cloud Shell with
gcloud,bq,curl, andjqpre-installed. - Working familiarity with BigQuery SQL, Cloud IAM, and the
gcloudCLI.
Challenges this codelab solves
Challenge | How this codelab solves it | Step |
How much demand will each location see over the next 14 days, given the promotion and holiday calendar? | One zero-shot multivariate | Forecast demand and evaluate accuracy |
How accurate is the forecast on held-out history? | A 14-day holdout accuracy evaluation with | Forecast demand and evaluate accuracy |
Which locations are reporting broken or unusual data? | A | Quarantine broken feeds and detect anomalies |
Who is allowed to call the Gemini models that write the executive brief? | A restricted analyst identity that can reach Gemini only through an approved Cloud Resource connection | Isolate Gemini access with least-privilege IAM |
Did the promotion lift demand, or would it have happened anyway? |
| Measure promotion lift and generate the executive brief |
What should leadership do next? | A typed executive brief that the restricted analyst generates with | Measure promotion lift and generate the executive brief |
In this section, you reviewed the six-stage forecasting method, the AI governance goals, and the Public Preview scope for this lab. Next, you review the architecture and configure your environment.
2. Set up the environment
Start by reviewing the lab architecture and preparing your project: set environment variables, enable the required APIs, and create the BigQuery dataset.
Review the lab architecture

The diagram shows everything you deploy and use in this codelab. You create one BigQuery dataset, a BigQuery Cloud Resource connection, and a restricted analyst service account. You enable five APIs: BigQuery, BigQuery Connection, Gemini Enterprise Agent Platform (aiplatform.googleapis.com), IAM, and IAM Service Account Credentials. Forecasting, evaluation, anomaly detection, and causal analysis run inside BigQuery, with no model for you to train or host. Only AI.GENERATE and AI.AGG call a Gemini Flash model, and they reach it through the connection. You act as the Data Engineer. The Business Analyst is the restricted analyst service account, which you impersonate.
Each step builds one part of the diagram:
- Set up the environment (this step): enable the APIs and create the dataset.
- Prepare the demand tables: build the Curated Tables.
- Forecast demand and evaluate accuracy: run
AI.FORECASTandAI.EVALUATE. - Quarantine broken feeds and detect anomalies: apply the Variance Guardrail, then run
AI.DETECT_ANOMALIES. - Isolate Gemini access with least-privilege IAM: create the service account and the connection, run the
AI.GENERATEaccess test, and auditINFORMATION_SCHEMA.JOBS. - Measure promotion lift and generate the executive brief: run
AI.CAUSAL_EFFECT, then generate theAI.AGGbrief as the Business Analyst. - Clean up: delete the dataset, the connection, the service account, and the IAM bindings.
Initialize environment variables and enable APIs
In Cloud Shell, export the lab environment variables, configure your quota project, and enable the five required Google Cloud APIs. These commands also create your working directory and BigQuery dataset in the us multi-region:
export PROJECT_ID="$(gcloud config get-value project)"
export PROJECT_NUMBER="$(gcloud projects describe "${PROJECT_ID}" --format="value(projectNumber)")"
export GOOGLE_CLOUD_QUOTA_PROJECT="${PROJECT_ID}"
export WORK_DIR="${HOME}/bq-timesfm-causal-iam-lab"
export BQ_LOCATION="us"
export DATASET_ID="citibike_ai_ops"
export CONNECTION_ID="approved_bq_ai_conn"
export CONN_URL="https://bigqueryconnection.googleapis.com/v1/projects/${PROJECT_ID}/locations/${BQ_LOCATION}/connections/${CONNECTION_ID}"
export ANALYST_SA_NAME="bq-analyst-restricted"
export ANALYST_SA_EMAIL="${ANALYST_SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"
export CALLER_EMAIL="$(gcloud config get-value account)"
if [[ "${CALLER_EMAIL}" == *.gserviceaccount.com ]]; then
export CALLER_MEMBER="serviceAccount:${CALLER_EMAIL}"
else
export CALLER_MEMBER="user:${CALLER_EMAIL}"
fi
export GEMINI_MODEL="gemini-3.5-flash"
export TIMESFM_MULTIVARIATE_MODEL="TimesFM 3.0"
gcloud config set billing/quota_project "${PROJECT_ID}"
if [[ -f "${HOME}/.config/gcloud/application_default_credentials.json" ]]; then
gcloud auth application-default set-quota-project "${PROJECT_ID}"
fi
gcloud services enable \
bigquery.googleapis.com \
bigqueryconnection.googleapis.com \
aiplatform.googleapis.com \
iam.googleapis.com \
iamcredentials.googleapis.com \
--project="${PROJECT_ID}"
mkdir -p "${WORK_DIR}"
cd "${WORK_DIR}"
if ! bq show --dataset "${PROJECT_ID}:${DATASET_ID}" >/dev/null 2>&1; then
bq mk --dataset --location="${BQ_LOCATION}" "${PROJECT_ID}:${DATASET_ID}"
fi
Verification
Confirm that the BigQuery dataset exists in your project:
bq show --dataset "${PROJECT_ID}:${DATASET_ID}" >/dev/null && echo "dataset_ok=${DATASET_ID}"
Confirm that the output matches:
dataset_ok=citibike_ai_ops
In this section, you configured your environment variables, enabled the required APIs, and created the BigQuery dataset. Next, you build the curated demand tables.
3. Prepare the demand tables
With the environment ready, you build the curated NYC Citi Bike demand tables that the forecasting, anomaly, and causal queries read.
Build the curated NYC Citi Bike demand tables
Create setup_tables.sql to materialize three deterministic tables from bigquery-public-data.new_york_citibike.citibike_trips (2017-01-01 through 2017-08-14, 226 days). The six active stations start from real NYC Citi Bike trip counts; the script injects a known promotional lift on ranks 1–3 and adds a synthetic 7th flatline sensor feed:
station_daily_raw: Top 6 busiest stations across a gap-freeGENERATE_DATE_ARRAYspine (so every station has a row for every day;NULLtimestamps/durations filtered out; zero-trip blizzard days imputed viaCOALESCEand station averages). Ranks 1–3 (PROMO_TREATED) receive simulated spring (May 1–14) and summer (August 1–14) promotional lifts alongside covariates—external explanatory features (is_weekend,is_us_holiday,is_promo_window). Ranks 4–6 (CONTROL_PLACEBO) keep unmodified Citi Bike counts, including real weather/event drops such as2017-08-07. A 7th degenerate series (Station_Maintenance_Flatline,daily_trips = 100.0) tests the variance guardrail.station_multivariate_input: Combines 226 historical days for the 6 active stations (1,356non-null rows) with 14 future horizon days (2017-08-15to2017-08-28,84rows). Future rows leave target columns and past covariatesNULL, populateis_weekendandis_us_holiday, and setis_promo_window = 1onAugust 21–27for ranks 1–3 to model a planned campaign.station_causal_input: Contains 6-station daily demand (1,356rows) with only the August promotion overlay on treated hubs (ranks 1–3) and unmodified counts on negative-control hubs (ranks 4–6).AI.CAUSAL_EFFECTfits a pre-August baseline ("counterfactual") model to estimate August demand without a promotion, so omitting the May promo keeps that baseline uncontaminated. By contrast,AI.FORECASTneeds the May promo to learn howis_promo_window = 1lifts demand.
cat << 'EOF' > setup_tables.sql
-- Copyright 2026 Google LLC
-- SPDX-License-Identifier: Apache-2.0
CREATE OR REPLACE TABLE `__PROJECT_ID__.__DATASET_ID__.station_daily_raw`
AS
WITH
filtered_trips AS (
SELECT
start_station_name AS station_name,
DATE(starttime) AS trip_date,
CAST(tripduration AS FLOAT64) AS tripduration_sec,
IF(usertype = 'Subscriber', 1.0, 0.0) AS is_subscriber
FROM `bigquery-public-data.new_york_citibike.citibike_trips`
WHERE
starttime IS NOT NULL
AND start_station_name IS NOT NULL
AND tripduration IS NOT NULL
AND tripduration > 0
AND DATE(starttime) BETWEEN DATE '2017-01-01' AND DATE '2017-08-14'
),
top_station_totals AS (
SELECT
station_name,
COUNT(*) AS total_trips
FROM filtered_trips
GROUP BY station_name
ORDER BY total_trips DESC, station_name ASC
LIMIT 6
),
top_stations AS (
SELECT
station_name,
ROW_NUMBER() OVER (ORDER BY total_trips DESC, station_name ASC) AS station_rank
FROM top_station_totals
),
date_spine AS (
SELECT trip_date
FROM UNNEST(GENERATE_DATE_ARRAY(DATE '2017-01-01', DATE '2017-08-14')) AS trip_date
),
daily_agg AS (
SELECT
station_name,
trip_date,
CAST(COUNT(*) AS FLOAT64) AS raw_trips,
AVG(tripduration_sec) AS raw_avg_duration,
AVG(is_subscriber) AS raw_sub_share
FROM filtered_trips
WHERE station_name IN (SELECT station_name FROM top_stations)
GROUP BY station_name, trip_date
),
imputed_series AS (
SELECT
s.station_rank,
s.station_name,
CASE
WHEN s.station_rank <= 3 THEN 'PROMO_TREATED'
ELSE 'CONTROL_PLACEBO'
END AS cohort,
d.trip_date,
COALESCE(a.raw_trips, 0.0) AS base_daily_trips,
COALESCE(
a.raw_avg_duration, AVG(a.raw_avg_duration) OVER (PARTITION BY s.station_name), 600.0)
AS avg_trip_duration_sec,
COALESCE(a.raw_sub_share, AVG(a.raw_sub_share) OVER (PARTITION BY s.station_name), 0.8)
AS subscriber_share,
IF(EXTRACT(DAYOFWEEK FROM d.trip_date) IN (1, 7), 1, 0) AS is_weekend,
IF(
d.trip_date IN (
DATE '2017-01-02', DATE '2017-01-16', DATE '2017-02-20', DATE '2017-05-29',
DATE '2017-07-04'),
1,
0) AS is_us_holiday,
IF(
s.station_rank <= 3
AND (
d.trip_date BETWEEN DATE '2017-05-01' AND DATE '2017-05-14'
OR d.trip_date BETWEEN DATE '2017-08-01' AND DATE '2017-08-14'),
1,
0) AS is_promo_window
FROM top_stations AS s
CROSS JOIN date_spine AS d
LEFT JOIN daily_agg AS a
ON s.station_name = a.station_name AND d.trip_date = a.trip_date
)
SELECT
station_rank,
station_name,
cohort,
trip_date,
CASE
WHEN station_rank <= 3 AND trip_date BETWEEN DATE '2017-05-01' AND DATE '2017-05-14'
THEN ROUND(base_daily_trips * 1.25 + 60.0, 2)
WHEN station_rank <= 3 AND trip_date BETWEEN DATE '2017-08-01' AND DATE '2017-08-14'
THEN ROUND(base_daily_trips * 1.35 + 80.0, 2)
ELSE base_daily_trips
END AS daily_trips,
ROUND(avg_trip_duration_sec, 2) AS avg_trip_duration_sec,
ROUND(subscriber_share, 4) AS subscriber_share,
is_weekend,
is_us_holiday,
is_promo_window
FROM imputed_series
UNION ALL
SELECT
7 AS station_rank,
'Station_Maintenance_Flatline' AS station_name,
'DEGENERATE_SENSOR' AS cohort,
trip_date,
100.0 AS daily_trips,
600.0 AS avg_trip_duration_sec,
0.8 AS subscriber_share,
IF(EXTRACT(DAYOFWEEK FROM trip_date) IN (1, 7), 1, 0) AS is_weekend,
IF(
trip_date IN (
DATE '2017-01-02', DATE '2017-01-16', DATE '2017-02-20', DATE '2017-05-29',
DATE '2017-07-04'),
1,
0) AS is_us_holiday,
0 AS is_promo_window
FROM date_spine;
CREATE OR REPLACE TABLE `__PROJECT_ID__.__DATASET_ID__.station_multivariate_input`
AS
WITH
active_stations AS (
SELECT DISTINCT station_rank, station_name, cohort
FROM `__PROJECT_ID__.__DATASET_ID__.station_daily_raw`
WHERE station_rank <= 6
),
future_dates AS (
SELECT trip_date
FROM UNNEST(GENERATE_DATE_ARRAY(DATE '2017-08-15', DATE '2017-08-28')) AS trip_date
)
SELECT
station_rank,
station_name,
cohort,
trip_date,
daily_trips,
avg_trip_duration_sec,
subscriber_share,
is_weekend,
is_us_holiday,
is_promo_window
FROM `__PROJECT_ID__.__DATASET_ID__.station_daily_raw`
WHERE station_rank <= 6
UNION ALL
SELECT
s.station_rank,
s.station_name,
s.cohort,
f.trip_date,
CAST(NULL AS FLOAT64) AS daily_trips,
CAST(NULL AS FLOAT64) AS avg_trip_duration_sec,
CAST(NULL AS FLOAT64) AS subscriber_share,
IF(EXTRACT(DAYOFWEEK FROM f.trip_date) IN (1, 7), 1, 0) AS is_weekend,
0 AS is_us_holiday,
IF(s.station_rank <= 3 AND f.trip_date BETWEEN DATE '2017-08-21' AND DATE '2017-08-27', 1, 0)
AS is_promo_window
FROM active_stations AS s
CROSS JOIN future_dates AS f;
CREATE OR REPLACE TABLE `__PROJECT_ID__.__DATASET_ID__.station_causal_input`
AS
WITH
filtered_trips AS (
SELECT
start_station_name AS station_name,
DATE(starttime) AS trip_date
FROM `bigquery-public-data.new_york_citibike.citibike_trips`
WHERE
starttime IS NOT NULL
AND start_station_name IS NOT NULL
AND tripduration IS NOT NULL
AND tripduration > 0
AND DATE(starttime) BETWEEN DATE '2017-01-01' AND DATE '2017-08-14'
),
active_stations AS (
SELECT DISTINCT station_rank, station_name, cohort
FROM `__PROJECT_ID__.__DATASET_ID__.station_daily_raw`
WHERE station_rank <= 6
),
date_spine AS (
SELECT trip_date
FROM UNNEST(GENERATE_DATE_ARRAY(DATE '2017-01-01', DATE '2017-08-14')) AS trip_date
),
daily_counts AS (
SELECT
station_name,
trip_date,
CAST(COUNT(*) AS FLOAT64) AS base_daily_trips
FROM filtered_trips
WHERE station_name IN (SELECT station_name FROM active_stations)
GROUP BY station_name, trip_date
)
SELECT
s.station_rank,
s.station_name,
s.cohort,
d.trip_date,
CASE
WHEN s.station_rank <= 3 AND d.trip_date BETWEEN DATE '2017-08-01' AND DATE '2017-08-14'
THEN ROUND(COALESCE(c.base_daily_trips, 0.0) * 1.35 + 80.0, 2)
ELSE COALESCE(c.base_daily_trips, 0.0)
END AS daily_trips
FROM active_stations AS s
CROSS JOIN date_spine AS d
LEFT JOIN daily_counts AS c
ON s.station_name = c.station_name AND d.trip_date = c.trip_date;
EOF
sed -i "s/__PROJECT_ID__/${PROJECT_ID}/g; s/__DATASET_ID__/${DATASET_ID}/g" setup_tables.sql
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false < setup_tables.sql
Verification
Confirm that the dataset exists and verify the deterministic row counts, calendar-spine coverage, zero NULL historical metrics, future horizon layout, and zero-variance station injection:
bq show --dataset "${PROJECT_ID}:${DATASET_ID}" >/dev/null
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false --format=csv \
"SELECT FORMAT('raw=%d,stations=%d,days=%d,raw_nulls=%d,flat=%d,mv_total=%d,mv_fut=%d,mv_fut_null=%d,mv_fut_cov=%d,causal=%d',
(SELECT COUNT(*) FROM \`${PROJECT_ID}.${DATASET_ID}.station_daily_raw\`),
(SELECT COUNT(DISTINCT station_name) FROM \`${PROJECT_ID}.${DATASET_ID}.station_daily_raw\`),
(SELECT COUNT(DISTINCT trip_date) FROM \`${PROJECT_ID}.${DATASET_ID}.station_daily_raw\`),
(SELECT COUNTIF(daily_trips IS NULL OR avg_trip_duration_sec IS NULL OR subscriber_share IS NULL) FROM \`${PROJECT_ID}.${DATASET_ID}.station_daily_raw\`),
(SELECT COUNT(*) FROM (SELECT station_name FROM \`${PROJECT_ID}.${DATASET_ID}.station_daily_raw\` GROUP BY station_name HAVING COALESCE(STDDEV_POP(daily_trips), 0.0) = 0.0)),
(SELECT COUNT(*) FROM \`${PROJECT_ID}.${DATASET_ID}.station_multivariate_input\`),
(SELECT COUNTIF(trip_date > DATE '2017-08-14') FROM \`${PROJECT_ID}.${DATASET_ID}.station_multivariate_input\`),
(SELECT COUNTIF(trip_date > DATE '2017-08-14' AND daily_trips IS NULL AND avg_trip_duration_sec IS NULL AND subscriber_share IS NULL) FROM \`${PROJECT_ID}.${DATASET_ID}.station_multivariate_input\`),
(SELECT COUNTIF(trip_date > DATE '2017-08-14' AND is_weekend IS NOT NULL AND is_us_holiday IS NOT NULL AND is_promo_window IS NOT NULL) FROM \`${PROJECT_ID}.${DATASET_ID}.station_multivariate_input\`),
(SELECT COUNT(*) FROM \`${PROJECT_ID}.${DATASET_ID}.station_causal_input\`))" | tail -n 1 | tr -d '"'
Confirm that the output matches:
raw=1582,stations=7,days=226,raw_nulls=0,flat=1,mv_total=1440,mv_fut=84,mv_fut_null=84,mv_fut_cov=84,causal=1356
In this section, you materialized the curated NYC Citi Bike station demand tables in BigQuery and verified their row counts. Next, you forecast 14 days of demand across every station and evaluate holdout accuracy.
4. Forecast demand and evaluate accuracy
With the curated station tables materialized in BigQuery, you can forecast demand for every location in one SQL query without per-series training. In this step, you run two SQL scripts. First, you forecast 14 days of demand across all six active stations with multivariate AI.FORECAST (Preview). Next, you evaluate forecast accuracy on a 14-day holdout window with AI.EVALUATE.
Multivariate AI.FORECAST predicts correlated targets (daily_trips and avg_trip_duration_sec) simultaneously using covariates—external explanatory features, some known only historically (past_covariate_cols => ['subscriber_share']) and others known in advance (future_covariate_cols => ['is_weekend', 'is_us_holiday', 'is_promo_window']). For future horizon dates, the input table leaves target columns and past covariates as NULL and populates only the known future covariates:

Multivariate AI.FORECAST outputs one row per (station_name, forecast timestamp). Each target column is a STRUCT with fields value, prediction_interval_lower_bound, and prediction_interval_upper_bound.
Run multivariate zero-shot forecasting with AI.FORECAST
Create and execute forecast_multivariate.sql to materialize station_multivariate_forecasts (6 stations × 14 future days = 84 rows) with 95% prediction intervals:
cat << 'EOF' > forecast_multivariate.sql
-- Copyright 2026 Google LLC
-- SPDX-License-Identifier: Apache-2.0
CREATE OR REPLACE TABLE `__PROJECT_ID__.__DATASET_ID__.station_multivariate_forecasts`
AS
SELECT *
FROM
AI.FORECAST(
TABLE `__PROJECT_ID__.__DATASET_ID__.station_multivariate_input`,
timestamp_col => 'trip_date',
target_cols => ['daily_trips', 'avg_trip_duration_sec'],
id_cols => ['station_name'],
past_covariate_cols => ['subscriber_share'],
future_covariate_cols => ['is_weekend', 'is_us_holiday', 'is_promo_window'],
model => '__TIMESFM_MV__',
horizon => 14,
confidence_level => 0.95,
context_window => 192,
output_historical_time_series => FALSE);
EOF
sed -i "s/__PROJECT_ID__/${PROJECT_ID}/g; s/__DATASET_ID__/${DATASET_ID}/g; s/__TIMESFM_MV__/${TIMESFM_MULTIVARIATE_MODEL}/g" forecast_multivariate.sql
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false < forecast_multivariate.sql
Inspect all 14 forecasted days for the busiest promoted station (station_rank = 1), unpacking each target STRUCT's point forecast (.value), 95% prediction interval bounds, and calendar/promotion flags:
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false \
"SELECT
f.station_name,
DATE(f.trip_date) AS trip_date,
i.is_weekend,
i.is_promo_window,
ROUND(f.daily_trips.value, 1) AS forecast_trips,
ROUND(f.daily_trips.prediction_interval_lower_bound, 1) AS lower_95,
ROUND(f.daily_trips.prediction_interval_upper_bound, 1) AS upper_95,
ROUND(f.avg_trip_duration_sec.value, 0) AS forecast_duration_sec
FROM \`${PROJECT_ID}.${DATASET_ID}.station_multivariate_forecasts\` AS f
INNER JOIN \`${PROJECT_ID}.${DATASET_ID}.station_multivariate_input\` AS i
ON f.station_name = i.station_name AND DATE(f.trip_date) = i.trip_date
WHERE i.station_rank = 1
ORDER BY trip_date ASC"
The output is similar to the following:
+-----------------------+------------+------------+-----------------+----------------+----------+----------+-----------------------+
| station_name | trip_date | is_weekend | is_promo_window | forecast_trips | lower_95 | upper_95 | forecast_duration_sec |
+-----------------------+------------+------------+-----------------+----------------+----------+----------+-----------------------+
| Pershing Square North | 2017-08-15 | 0 | 0 | 1041.2 | 737.0 | 1416.4 | 823.0 |
| Pershing Square North | 2017-08-16 | 0 | 0 | 1025.6 | 706.1 | 1438.2 | 810.0 |
| Pershing Square North | 2017-08-17 | 0 | 0 | 973.9 | 645.2 | 1414.2 | 808.0 |
| Pershing Square North | 2017-08-18 | 0 | 0 | 862.3 | 513.2 | 1347.2 | 818.0 |
| Pershing Square North | 2017-08-19 | 1 | 0 | 360.4 | 71.1 | 800.2 | 1052.0 |
| Pershing Square North | 2017-08-20 | 1 | 0 | 351.9 | 53.2 | 808.5 | 1085.0 |
| Pershing Square North | 2017-08-21 | 0 | 1 | 868.4 | 468.6 | 1423.9 | 797.0 |
| Pershing Square North | 2017-08-22 | 0 | 1 | 1021.1 | 629.3 | 1578.3 | 799.0 |
| Pershing Square North | 2017-08-23 | 0 | 1 | 1008.8 | 608.6 | 1579.4 | 801.0 |
| Pershing Square North | 2017-08-24 | 0 | 1 | 1011.1 | 615.8 | 1590.4 | 795.0 |
| Pershing Square North | 2017-08-25 | 0 | 1 | 872.1 | 451.5 | 1489.9 | 811.0 |
| Pershing Square North | 2017-08-26 | 1 | 1 | 417.5 | 56.1 | 991.1 | 1047.0 |
| Pershing Square North | 2017-08-27 | 1 | 1 | 376.0 | -17.5 | 993.8 | 1058.0 |
| Pershing Square North | 2017-08-28 | 0 | 0 | 846.1 | 353.9 | 1581.7 | 803.0 |
+-----------------------+------------+------------+-----------------+----------------+----------+----------+-----------------------+
Plotted alongside the preceding 45 days of actual demand, the chart shows the historical August 1–14 promotional step-up followed by the 14-day forecast. The forecast captures the weekday-versus-weekend commuter rhythm and widens the 95% upper prediction bound during the planned August 21–27 promotion:

Notice three operational signals in the returned rows and chart:
- Simultaneous targets: Every row forecasts
daily_tripsandavg_trip_duration_secin one pass. Predicted durations lengthen on weekends (~1,050 sleisure rides) as trip counts drop (~360trips), while commuter weekdays reverse both patterns. - Uncertainty bounds (
lower_95toupper_95): Use the upper bound (peaking at1,590.4trips on August 24) for staffing and dock-capacity buffers. On low-demand horizon days with slightly negative floor bounds (-17.5on August 27), clamp values at0withGREATEST(lower_95, 0). - Covariate responsiveness: Compare the non-promo weekend (
August 19–20:360.4and351.9predicted trips) with the planned promo weekend (August 26–27:417.5and376.0). Settingis_promo_window = 1shifts predicted demand upward and widens the upper band.
Evaluate forecast accuracy on a 14-day holdout with AI.EVALUATE
Before trusting a zero-shot forecast in production, measure how closely it tracks demand on held-out history. Notice that AI.EVALUATE operates on a univariate data_col (unlike multivariate AI.FORECAST, which uses target_cols).
Create and execute evaluate_forecast.sql to evaluate the Preview TimesFM model on station_causal_input with context_window => 128. The query reads station_causal_input (clean pre-August history without the May promo, flatline sensor, or future NULL rows) and passes 212 pre-August days—from which TimesFM reads the most recent 128—to score the 2017-08-01 through 2017-08-14 holdout window (unmodified counts on control stations and simulated lift on treated stations):
cat << 'EOF' > evaluate_forecast.sql
-- Copyright 2026 Google LLC
-- SPDX-License-Identifier: Apache-2.0
CREATE OR REPLACE TABLE `__PROJECT_ID__.__DATASET_ID__.station_forecast_eval`
AS
SELECT
station_name,
mean_absolute_error,
mean_squared_error,
root_mean_squared_error,
mean_absolute_percentage_error,
symmetric_mean_absolute_percentage_error,
mean_absolute_scaled_error,
ai_evaluate_status
FROM
AI.EVALUATE(
(
SELECT station_name, trip_date, daily_trips
FROM `__PROJECT_ID__.__DATASET_ID__.station_causal_input`
WHERE trip_date < DATE '2017-08-01'
),
(
SELECT station_name, trip_date, daily_trips
FROM `__PROJECT_ID__.__DATASET_ID__.station_causal_input`
WHERE trip_date BETWEEN DATE '2017-08-01' AND DATE '2017-08-14'
),
data_col => 'daily_trips',
timestamp_col => 'trip_date',
id_cols => ['station_name'],
model => '__TIMESFM_MV__',
horizon => 14,
context_window => 128);
EOF
sed -i "s/__PROJECT_ID__/${PROJECT_ID}/g; s/__DATASET_ID__/${DATASET_ID}/g; s/__TIMESFM_MV__/${TIMESFM_MULTIVARIATE_MODEL}/g" evaluate_forecast.sql
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false < evaluate_forecast.sql
Inspect the per-station holdout accuracy metrics across all six stations:
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false \
"SELECT
e.station_name,
s.cohort,
ROUND(e.mean_absolute_error, 2) AS mae,
ROUND(e.root_mean_squared_error, 2) AS rmse,
ROUND(e.symmetric_mean_absolute_percentage_error, 2) AS smape_pct,
ROUND(e.mean_absolute_scaled_error, 3) AS mase
FROM \`${PROJECT_ID}.${DATASET_ID}.station_forecast_eval\` AS e
INNER JOIN (
SELECT DISTINCT station_rank, station_name, cohort
FROM \`${PROJECT_ID}.${DATASET_ID}.station_causal_input\`
) AS s
ON e.station_name = s.station_name
ORDER BY s.station_rank ASC"
The output is similar to the following:
+-----------------------+-----------------+--------+--------+-----------+-------+
| station_name | cohort | mae | rmse | smape_pct | mase |
+-----------------------+-----------------+--------+--------+-----------+-------+
| Pershing Square North | PROMO_TREATED | 247.45 | 270.56 | 42.83 | 2.023 |
| West St & Chambers St | PROMO_TREATED | 268.51 | 277.05 | 45.34 | 2.018 |
| E 17 St & Broadway | PROMO_TREATED | 272.26 | 297.89 | 51.45 | 2.951 |
| Broadway & E 22 St | CONTROL_PLACEBO | 51.48 | 94.1 | 16.06 | 0.499 |
| W 21 St & 6 Ave | CONTROL_PLACEBO | 34.64 | 65.26 | 10.91 | 0.441 |
| 12 Ave & W 40 St | CONTROL_PLACEBO | 76.29 | 100.87 | 23.4 | 0.593 |
+-----------------------+-----------------+--------+--------+-----------+-------+
AI.EVALUATE returns those six aggregate metric rows. Plotting the corresponding univariate holdout forecasts against observed holdout demand over the August 1–14 window shows both zero-shot accuracy on unmodified control stations and the simulated promotion gap on treated stations:

Read the holdout metrics as follows: MAE is average daily trip error, RMSE penalizes large misses, sMAPE is symmetric percentage error, and MASE compares error against a naive "repeat yesterday" baseline (< 1.0 beats the naive forecast):
- Unpromoted control stations (
CONTROL_PLACEBO, unmodified NYC Citi Bike data):MAEstays between35and76trips/day, andMASEstays between0.44and0.59. Values well below1.0beat the naive persistence baseline and confirm close alignment with actual daily trips. - Promoted stations (
PROMO_TREATED, real baseline + simulated August lift): Because univariateAI.EVALUATEcannot readis_promo_window, promoted demand rises above the forecast andMAEclimbs to247–272trips/day. This gap shows why planned campaigns require multivariateAI.FORECASTwithfuture_covariate_cols.
Verification
Verify the exact multivariate forecast count (84 rows), zero forecast errors, positive predicted trips, and AI.EVALUATE holdout rows (6 rows with zero errors and non-null MAE/RMSE):
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false --format=csv \
"SELECT FORMAT('fc_rows=%d,fc_err=%d,fc_pos=%d,ev_rows=%d,ev_err=%d,ev_nonnull=%d',
(SELECT COUNT(*) FROM \`${PROJECT_ID}.${DATASET_ID}.station_multivariate_forecasts\`),
(SELECT COUNTIF(COALESCE(ai_forecast_status, '') != '') FROM \`${PROJECT_ID}.${DATASET_ID}.station_multivariate_forecasts\`),
(SELECT COUNTIF(daily_trips.value > 0) FROM \`${PROJECT_ID}.${DATASET_ID}.station_multivariate_forecasts\`),
(SELECT COUNT(*) FROM \`${PROJECT_ID}.${DATASET_ID}.station_forecast_eval\`),
(SELECT COUNTIF(COALESCE(ai_evaluate_status, '') != '') FROM \`${PROJECT_ID}.${DATASET_ID}.station_forecast_eval\`),
(SELECT COUNTIF(mean_absolute_error IS NOT NULL AND root_mean_squared_error IS NOT NULL) FROM \`${PROJECT_ID}.${DATASET_ID}.station_forecast_eval\`))" | tail -n 1 | tr -d '"'
Confirm that the output matches:
fc_rows=84,fc_err=0,fc_pos=84,ev_rows=6,ev_err=0,ev_nonnull=6
In this section, you ran multivariate zero-shot forecasts with past and future covariates, inspected predicted demand and 95% prediction intervals, and evaluated 14-day holdout accuracy. Next, you protect the pipeline from flatlined sensors and detect unexpected demand incidents.
5. Quarantine broken feeds and detect anomalies
Forecasts tell planners what to expect next, but operations teams also need to catch broken data feeds and unexpected demand drops today. Before calling AI.DETECT_ANOMALIES (GA, using BigQuery's default TimesFM model automatically), you pass all seven station series through two SQL guardrails:
- Variance guardrail (population standard deviation
STDDEV_POP > 0andCOUNT(*) >= 3): Quarantines degenerate zero-variance (constant-value) series such as'Station_Maintenance_Flatline'intostation_series_health(whileCOUNT(*) >= 3ensures enough history to score), preventing collapsed intervals or per-series failures during anomaly scoring. - Promotion filter (
is_promo_window = 0): Excludes known promotion days from anomaly scoring. A planned promotion is expected demand, not an unexpected incident, so scoring it would bury genuine operational anomalies under promotion spikes. You measure the promotions' causal effect separately in Measure promotion lift and generate the executive brief. Because every day in the August 1–14 scoring window is a promotion day for the three promoted stations, anomaly scoring runs on the three unpromoted stations—unmodified NYC Citi Bike counts.

Build the SQL variance guardrail and inspect quarantined series
Create and execute guardrail_series.sql to classify every station over the 212-day pre-August baseline window (2017-01-01 through 2017-07-31) in station_series_health and materialize only healthy series into station_daily_guarded:
cat << 'EOF' > guardrail_series.sql
-- Copyright 2026 Google LLC
-- SPDX-License-Identifier: Apache-2.0
CREATE OR REPLACE TABLE `__PROJECT_ID__.__DATASET_ID__.station_series_health`
AS
SELECT
station_name,
COUNT(*) AS point_count,
ROUND(COALESCE(STDDEV_POP(daily_trips), 0.0), 4) AS stddev_trips,
(COUNT(*) >= 3 AND COALESCE(STDDEV_POP(daily_trips), 0.0) > 0.0) AS is_eligible,
CASE
WHEN COUNT(*) < 3 THEN 'INSUFFICIENT_HISTORY'
WHEN COALESCE(STDDEV_POP(daily_trips), 0.0) = 0.0 THEN 'ZERO_VARIANCE_DEGENERATE'
ELSE 'ELIGIBLE'
END AS quarantine_reason
FROM `__PROJECT_ID__.__DATASET_ID__.station_daily_raw`
WHERE trip_date < DATE '2017-08-01'
GROUP BY station_name;
CREATE OR REPLACE TABLE `__PROJECT_ID__.__DATASET_ID__.station_daily_guarded`
AS
SELECT r.*
FROM `__PROJECT_ID__.__DATASET_ID__.station_daily_raw` AS r
INNER JOIN `__PROJECT_ID__.__DATASET_ID__.station_series_health` AS h
ON r.station_name = h.station_name
WHERE h.is_eligible IS TRUE;
EOF
sed -i "s/__PROJECT_ID__/${PROJECT_ID}/g; s/__DATASET_ID__/${DATASET_ID}/g" guardrail_series.sql
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false < guardrail_series.sql
Inspect station_series_health to confirm that 'Station_Maintenance_Flatline' is quarantined with zero variance while all six active stations remain eligible:
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false \
"SELECT
station_name,
point_count,
stddev_trips,
is_eligible,
quarantine_reason
FROM \`${PROJECT_ID}.${DATASET_ID}.station_series_health\`
ORDER BY is_eligible ASC, station_name ASC"
The output is similar to the following:
+------------------------------+-------------+--------------+-------------+--------------------------+
| station_name | point_count | stddev_trips | is_eligible | quarantine_reason |
+------------------------------+-------------+--------------+-------------+--------------------------+
| Station_Maintenance_Flatline | 212 | 0.0 | false | ZERO_VARIANCE_DEGENERATE |
| 12 Ave & W 40 St | 212 | 192.2301 | true | ELIGIBLE |
| Broadway & E 22 St | 212 | 200.794 | true | ELIGIBLE |
| E 17 St & Broadway | 212 | 198.5823 | true | ELIGIBLE |
| Pershing Square North | 212 | 313.3181 | true | ELIGIBLE |
| W 21 St & 6 Ave | 212 | 173.5493 | true | ELIGIBLE |
| West St & Chambers St | 212 | 224.254 | true | ELIGIBLE |
+------------------------------+-------------+--------------+-------------+--------------------------+
Detect unexpected ridership anomalies with AI.DETECT_ANOMALIES
Create and execute detect_anomalies.sql to score the August window (2017-08-01 through 2017-08-14) on healthy, non-promotion series at a 0.95 anomaly probability threshold:
cat << 'EOF' > detect_anomalies.sql
-- Copyright 2026 Google LLC
-- SPDX-License-Identifier: Apache-2.0
CREATE OR REPLACE TABLE `__PROJECT_ID__.__DATASET_ID__.station_anomalies`
AS
SELECT *
FROM
AI.DETECT_ANOMALIES(
(
SELECT station_name, trip_date, daily_trips
FROM `__PROJECT_ID__.__DATASET_ID__.station_daily_guarded`
WHERE
trip_date < DATE '2017-08-01'
AND station_name IN (
SELECT station_name
FROM `__PROJECT_ID__.__DATASET_ID__.station_daily_guarded`
WHERE trip_date BETWEEN DATE '2017-08-01' AND DATE '2017-08-14' AND is_promo_window = 0
)
),
(
SELECT station_name, trip_date, daily_trips
FROM `__PROJECT_ID__.__DATASET_ID__.station_daily_guarded`
WHERE trip_date BETWEEN DATE '2017-08-01' AND DATE '2017-08-14' AND is_promo_window = 0
),
data_col => 'daily_trips',
timestamp_col => 'trip_date',
id_cols => ['station_name'],
anomaly_prob_threshold => 0.95);
EOF
sed -i "s/__PROJECT_ID__/${PROJECT_ID}/g; s/__DATASET_ID__/${DATASET_ID}/g" detect_anomalies.sql
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false < detect_anomalies.sql
Inspect every flagged row in station_anomalies to see how observed demand compares against the model's expected lower_bound and upper_bound:
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false \
"SELECT
station_name,
DATE(time_series_timestamp) AS trip_date,
ROUND(time_series_data, 1) AS observed_trips,
ROUND(lower_bound, 1) AS lower_bound,
ROUND(upper_bound, 1) AS upper_bound,
ROUND(anomaly_probability, 4) AS anomaly_prob
FROM \`${PROJECT_ID}.${DATASET_ID}.station_anomalies\`
WHERE is_anomaly IS TRUE
ORDER BY trip_date ASC, station_name ASC"
The output is similar to the following:
+--------------------+------------+----------------+-------------+-------------+--------------+
| station_name | trip_date | observed_trips | lower_bound | upper_bound | anomaly_prob |
+--------------------+------------+----------------+-------------+-------------+--------------+
| 12 Ave & W 40 St | 2017-08-07 | 79.0 | 101.7 | 647.6 | 0.9661 |
| Broadway & E 22 St | 2017-08-07 | 116.0 | 183.8 | 580.4 | 0.9895 |
| W 21 St & 6 Ave | 2017-08-07 | 156.0 | 201.4 | 496.8 | 0.9861 |
+--------------------+------------+----------------+-------------+-------------+--------------+
Plotting observed trips against the model's 95% expected interval highlights the August 7 ridership drop across all three unpromoted stations:

AI.DETECT_ANOMALIES separates this real citywide disruption from normal weekday variation: on Monday 2017-08-07, observed demand falls below the expected lower bound (anomaly_prob from 0.966 to 0.990), while every other day in the 14-day window stays within bounds.
Verification
Verify that the guardrail quarantined 'Station_Maintenance_Flatline' (1 row), AI.DETECT_ANOMALIES returned zero status errors, and anomaly detection flagged the real 2017-08-07 citywide drop across all three unpromoted stations:
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false --format=csv \
"SELECT FORMAT('quar=%d,quar_flat=%d,anom_err=%d,anom_aug7=%d',
(SELECT COUNTIF(is_eligible IS FALSE) FROM \`${PROJECT_ID}.${DATASET_ID}.station_series_health\`),
(SELECT COUNTIF(station_name = 'Station_Maintenance_Flatline' AND is_eligible IS FALSE) FROM \`${PROJECT_ID}.${DATASET_ID}.station_series_health\`),
(SELECT COUNTIF(COALESCE(ai_detect_anomalies_status, '') != '') FROM \`${PROJECT_ID}.${DATASET_ID}.station_anomalies\`),
(SELECT COUNTIF(is_anomaly IS TRUE AND DATE(time_series_timestamp) = DATE '2017-08-07') FROM \`${PROJECT_ID}.${DATASET_ID}.station_anomalies\`))" | tail -n 1 | tr -d '"'
Confirm that the output matches (anom_aug7 >= 3):
quar=1,quar_flat=1,anom_err=0,anom_aug7=3
In this section, you quarantined a zero-variance sensor feed with a SQL guardrail, filtered out planned promotions, and flagged an authentic citywide ridership anomaly across all three unpromoted stations with AI.DETECT_ANOMALIES. Next, you lock down who can invoke Gemini models before generating executive briefs.
6. Isolate Gemini access with least-privilege IAM
Forecasting and anomaly detection run on BigQuery's built-in TimesFM models and don't call Gemini. The executive brief in the next step does, so before you call Gemini from SQL, you lock down who can.
When you omit connection_id in AI.GENERATE, BigQuery sends the inference call to Gemini Enterprise Agent Platform using the caller's own end-user credentials (EUC). Disabling aiplatform.googleapis.com is not a viable governance control because it blocks both direct calls and governed batch pipelines. Instead, you keep aiplatform.googleapis.com enabled, withhold roles/aiplatform.user from your analyst identity, and grant roles/aiplatform.user solely to a BigQuery Cloud Resource connection, which automatically provisions a Google-managed service account for external AI calls. Because the bq CLI cannot assign connection-level IAM bindings, you grant roles/bigquery.connectionUser to the analyst strictly on that single connection resource through the BigQuery Connection REST API.
Create the restricted analyst service account and approved connection
Create bq-analyst-restricted with only roles/bigquery.jobUser (to run queries) and roles/bigquery.dataViewer (to read tables and views—never roles/aiplatform.user). In production, scope roles/bigquery.dataViewer to the target dataset or view rather than the entire project. A newly created service account can take up to a minute to become visible to IAM, so the role grants retry every 10 seconds until they succeed. Next, grant yourself roles/iam.serviceAccountTokenCreator to impersonate bq-analyst-restricted via --impersonate-service-account. Then create the BigQuery Cloud Resource connection, grant roles/aiplatform.user to the connection's service account (CONN_SA_EMAIL), and add roles/bigquery.connectionUser for the analyst on that single connection. The policy update reads the connection's current IAM policy, merges in the new binding, and writes it back with the same etag (optimistic-concurrency version token) to preserve existing bindings:
if ! gcloud iam service-accounts describe "${ANALYST_SA_EMAIL}" --project="${PROJECT_ID}" >/dev/null 2>&1; then
gcloud iam service-accounts create "${ANALYST_SA_NAME}" \
--display-name="Restricted BigQuery Analyst" \
--project="${PROJECT_ID}"
fi
for ROLE in roles/bigquery.jobUser roles/bigquery.dataViewer; do
for attempt in $(seq 1 12); do
if gcloud projects add-iam-policy-binding "${PROJECT_ID}" \
--member="serviceAccount:${ANALYST_SA_EMAIL}" \
--role="${ROLE}" \
--condition=None \
--format=none; then
echo "Granted ${ROLE} on attempt ${attempt}."
break
fi
echo "Service account not visible to IAM yet; retrying ${ROLE} in 10 seconds (attempt ${attempt})."
sleep 10
done
done
ANALYST_ROLE_COUNT=$(gcloud projects get-iam-policy "${PROJECT_ID}" \
--flatten="bindings[].members" \
--filter="bindings.members=serviceAccount:${ANALYST_SA_EMAIL} AND bindings.role:(roles/bigquery.jobUser OR roles/bigquery.dataViewer)" \
--format="value(bindings.role)" | wc -l | tr -d ' ')
test "${ANALYST_ROLE_COUNT}" -eq 2
gcloud iam service-accounts add-iam-policy-binding "${ANALYST_SA_EMAIL}" \
--member="${CALLER_MEMBER}" \
--role="roles/iam.serviceAccountTokenCreator" \
--project="${PROJECT_ID}"
if ! bq show --connection "${PROJECT_ID}.${BQ_LOCATION}.${CONNECTION_ID}" >/dev/null 2>&1; then
bq mk --connection \
--location="${BQ_LOCATION}" \
--project_id="${PROJECT_ID}" \
--connection_type=CLOUD_RESOURCE \
"${CONNECTION_ID}"
fi
export CONN_SA_EMAIL="$(bq show --connection --format=json "${PROJECT_ID}.${BQ_LOCATION}.${CONNECTION_ID}" | jq -r '.cloudResource.serviceAccountId')"
echo "Connection service account: ${CONN_SA_EMAIL}"
for attempt in $(seq 1 12); do
if gcloud projects add-iam-policy-binding "${PROJECT_ID}" \
--member="serviceAccount:${CONN_SA_EMAIL}" \
--role="roles/aiplatform.user" \
--condition=None \
--format=none; then
echo "Granted roles/aiplatform.user to connection SA on attempt ${attempt}."
break
fi
echo "Connection service account not visible to IAM yet; retrying in 10 seconds (attempt ${attempt})."
sleep 10
done
CONN_AI_ROLE_COUNT=$(gcloud projects get-iam-policy "${PROJECT_ID}" \
--flatten="bindings[].members" \
--filter="bindings.members=serviceAccount:${CONN_SA_EMAIL} AND bindings.role=roles/aiplatform.user" \
--format="value(bindings.role)" | wc -l | tr -d ' ')
test "${CONN_AI_ROLE_COUNT}" -eq 1
curl -sS -f -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-H "x-goog-user-project: ${PROJECT_ID}" \
"${CONN_URL}:getIamPolicy" \
-d '{}' > /tmp/conn_policy.json
jq --arg member "serviceAccount:${ANALYST_SA_EMAIL}" '
(.bindings // []) as $b
| {policy: (. + {bindings: (
if any($b[]; .role == "roles/bigquery.connectionUser")
then [$b[] | if .role == "roles/bigquery.connectionUser"
then .members = ((.members + [$member]) | unique)
else . end]
else $b + [{role: "roles/bigquery.connectionUser", members: [$member]}]
end)})}' /tmp/conn_policy.json > /tmp/conn_policy_new.json
curl -sS -f -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-H "x-goog-user-project: ${PROJECT_ID}" \
"${CONN_URL}:setIamPolicy" \
-d @/tmp/conn_policy_new.json
Prove EUC denial and governed connection access
Because the bq CLI does not natively support --impersonate-service-account, you mint an impersonated access token with gcloud and submit non-mutating BigQuery REST v2 jobs.query requests ("timeoutMs": 60000) via curl. Wait for IAM token-minting and roles/bigquery.jobUser propagation by polling SELECT 1 as ANALYST_SA_EMAIL, then run two impersonated tests using Gemini Flash:
- Negative test (
connection_idomitted): Verifies that BigQuery rejects implicit EUC calls even whileaiplatform.googleapis.comstays enabled. The API returns HTTP 400 with "The user does not have the permission to access or use the endpoint. Please grant the ‘Agent Platform User' role..." because the endpoint call requiresaiplatform.endpoints.predict. - Positive test (
connection_idspecified): Proves the identical SQL prompt succeeds when routed through the approved Cloud Resource connection service account.
READY_OK="false"
for attempt in $(seq 1 12); do
if ANALYST_TOKEN="$(gcloud auth print-access-token --impersonate-service-account="${ANALYST_SA_EMAIL}" 2>/dev/null)" && [[ -n "${ANALYST_TOKEN}" ]]; then
export ANALYST_TOKEN
READY_CODE="$(curl -sS -o /tmp/ready_resp.json -w "%{http_code}" -X POST \
-H "Authorization: Bearer ${ANALYST_TOKEN}" \
-H "Content-Type: application/json" \
"https://bigquery.googleapis.com/bigquery/v2/projects/${PROJECT_ID}/queries" \
-d '{"query":"SELECT 1 AS ready","useLegacySql":false,"location":"'"${BQ_LOCATION}"'","timeoutMs":60000}')"
if [[ "${READY_CODE}" == "200" ]]; then
READY_OK="true"
echo "Analyst SA impersonation and BigQuery jobUser ready on attempt ${attempt}."
break
fi
fi
sleep 10
done
test "${READY_OK}" = "true"
export EUC_HTTP_CODE="$(curl -sS -o /tmp/euc_deny_resp.json -w "%{http_code}" -X POST \
-H "Authorization: Bearer ${ANALYST_TOKEN}" \
-H "Content-Type: application/json" \
"https://bigquery.googleapis.com/bigquery/v2/projects/${PROJECT_ID}/queries" \
-d '{
"query": "SELECT r.result, COALESCE(r.status, \"\") AS status FROM (SELECT AI.GENERATE(\"Summarize NYC station congestion risk in one sentence.\", endpoint => \"'"${GEMINI_MODEL}"'\") AS r)",
"useLegacySql": false,
"location": "'"${BQ_LOCATION}"'",
"timeoutMs": 60000
}')"
echo "Implicit EUC HTTP status: ${EUC_HTTP_CODE}"
jq '.' /tmp/euc_deny_resp.json
CONN_OK="false"
for attempt in $(seq 1 6); do
export CONN_HTTP_CODE="$(curl -sS -o /tmp/conn_allow_resp.json -w "%{http_code}" -X POST \
-H "Authorization: Bearer ${ANALYST_TOKEN}" \
-H "Content-Type: application/json" \
"https://bigquery.googleapis.com/bigquery/v2/projects/${PROJECT_ID}/queries" \
-d '{
"query": "SELECT r.result, COALESCE(r.status, \"\") AS status FROM (SELECT AI.GENERATE(\"Summarize NYC station congestion risk in one sentence.\", endpoint => \"'"${GEMINI_MODEL}"'\", connection_id => \"'"${PROJECT_ID}.${BQ_LOCATION}.${CONNECTION_ID}"'\") AS r)",
"useLegacySql": false,
"location": "'"${BQ_LOCATION}"'",
"timeoutMs": 60000
}')"
if [[ "${CONN_HTTP_CODE}" == "200" ]] && jq -e '.jobComplete == true and ((.rows[0].f[0].v // "") | length > 0) and ((.rows[0].f[1].v // "") == "")' /tmp/conn_allow_resp.json >/dev/null; then
CONN_OK="true"
echo "Governed Connection AI.GENERATE succeeded on attempt ${attempt}."
break
fi
sleep 10
done
test "${CONN_OK}" = "true"
echo "Governed Connection HTTP status: ${CONN_HTTP_CODE}"
jq '.' /tmp/conn_allow_resp.json
Audit per-principal job attribution in INFORMATION_SCHEMA.JOBS
Audit which principal ran each job, including the impersonated analyst calls you made, in INFORMATION_SCHEMA.JOBS. Always filter statement_type != 'SCRIPT' to prevent double-counting (multi-statement scripts log both a parent SCRIPT job and child jobs for each statement). Inspecting other principals such as ANALYST_SA_EMAIL requires roles/bigquery.resourceViewer (bigquery.jobs.listAll, already included in roles/owner):
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false \
"SELECT job_id, user_email, statement_type, total_bytes_billed, total_slot_ms, error_result
FROM \`region-${BQ_LOCATION}\`.INFORMATION_SCHEMA.JOBS
WHERE creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR)
AND statement_type != 'SCRIPT'
ORDER BY creation_time DESC
LIMIT 25"
The query returns rows attributed to ANALYST_SA_EMAIL, showing a populated error_result on the blocked implicit EUC call and NULL on the governed-connection call.
Verification
Verify that aiplatform.googleapis.com stays enabled, the restricted analyst lacks roles/aiplatform.user, and SELECT 1 succeeded. Confirm that the implicit EUC call failed with the endpoint-permission error and that the connection-routed call returned a non-empty result with an empty status. Finally, verify that INFORMATION_SCHEMA.JOBS attributes at least one job to the analyst service account:
ENABLED_AI=$(gcloud services list --enabled --project="${PROJECT_ID}" --filter="config.name:aiplatform.googleapis.com" --format="value(config.name)")
ANALYST_AI_ROLES=$(gcloud projects get-iam-policy "${PROJECT_ID}" \
--flatten="bindings[].members" \
--filter="bindings.role=roles/aiplatform.user AND bindings.members=serviceAccount:${ANALYST_SA_EMAIL}" \
--format="value(bindings.role)" | wc -l | tr -d ' ')
EUC_HAS_DENIAL=$(jq -r '[.error.message // "", .rows[0].f[1].v // ""] | join(" ")' /tmp/euc_deny_resp.json | grep -c -E "permission to access or use the endpoint|aiplatform.endpoints.predict")
CONN_RESULT_LEN=$(jq -r '(.rows[0].f[0].v // "") | length' /tmp/conn_allow_resp.json)
CONN_STATUS=$(jq -r '.rows[0].f[1].v // ""' /tmp/conn_allow_resp.json)
CONN_COMPLETE=$(jq -r '.jobComplete' /tmp/conn_allow_resp.json)
jq -e '.jobComplete == true' /tmp/ready_resp.json >/dev/null
bq show --connection "${PROJECT_ID}.${BQ_LOCATION}.${CONNECTION_ID}" >/dev/null
JOBS_SA=$(bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false --format=csv \
"SELECT COUNT(*) AS n FROM \`region-${BQ_LOCATION}\`.INFORMATION_SCHEMA.JOBS WHERE creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 2 HOUR) AND statement_type != 'SCRIPT' AND user_email = '${ANALYST_SA_EMAIL}'" | tail -n 1)
echo "api=${ENABLED_AI},analyst_ai_roles=${ANALYST_AI_ROLES},euc_denied=${EUC_HAS_DENIAL},conn_complete=${CONN_COMPLETE},conn_status_len=${#CONN_STATUS},conn_result_gt0=$((CONN_RESULT_LEN > 0)),jobs_sa_gt0=$((JOBS_SA > 0))"
Confirm that the output matches:
api=aiplatform.googleapis.com,analyst_ai_roles=0,euc_denied=1,conn_complete=true,conn_status_len=0,conn_result_gt0=1,jobs_sa_gt0=1
In this section, you isolated BigQuery AI.GENERATE behind a Cloud Resource connection with connection-scoped IAM. Using --impersonate-service-account, you verified that implicit EUC calls fail while connection-routed calls succeed with aiplatform.googleapis.com active, and audited per-principal jobs in INFORMATION_SCHEMA.JOBS. Next, you measure promotion lift and generate the executive brief as the restricted analyst.
7. Measure promotion lift and generate the executive brief
With Gemini access locked behind the approved connection, you measure whether the August promotion lifted demand and have the restricted analyst summarize all operational signals. BigQuery AI.CAUSAL_EFFECT (Preview) estimates the causal effect of a timestamped intervention by fitting an independent univariate ARIMA_PLUS counterfactual model—BigQuery ML's built-in time-series model—for each id_cols series. Passing the three untreated stations alongside the three promotional stations evaluates both cohorts in parallel so the untreated hubs act as negative-control placebo sanity checks.
In Prepare the demand tables, you injected a known August 1–14 lift (35% plus 80 trips/day) into the three promoted stations so you can verify that AI.CAUSAL_EFFECT recovers it. With your own data the true effect is unknown, which is why the unpromoted control stations matter: they should show no significant lift.
You then unify all detected anomalies, quarantined flatline sensors, and causal lift metrics into a single operational view. Building the causal table and the view is data engineering work, so you run it as yourself.
The executive brief is analyst work. Impersonating bq-analyst-restricted from Isolate Gemini access with least-privilege IAM, you run a read-only SELECT that calls AI.AGG (GA) through the governed connection_id using Gemini Flash and a typed output_schema (NOT NULL fields). Unlike row-level AI.GENERATE, AI.AGG aggregates all signal rows in each GROUP BY signal_category into one typed STRUCT brief. Because the analyst holds only roles/bigquery.jobUser, roles/bigquery.dataViewer, and connection-scoped roles/bigquery.connectionUser, it can read the view and call Gemini through that connection but cannot create tables.
Build the causal results and the operational signals view
Create and execute causal_and_signals.sql:
cat << 'EOF' > causal_and_signals.sql
-- Copyright 2026 Google LLC
-- SPDX-License-Identifier: Apache-2.0
CREATE OR REPLACE TABLE `__PROJECT_ID__.__DATASET_ID__.station_causal_results`
AS
WITH
causal AS (
SELECT *
FROM
AI.CAUSAL_EFFECT(
TABLE `__PROJECT_ID__.__DATASET_ID__.station_causal_input`,
data_col => 'daily_trips',
timestamp_col => 'trip_date',
intervention_timestamp => '2017-08-01',
id_cols => ['station_name'],
confidence_level => 0.95,
output_time_series => FALSE,
num_post_intervention_points => 14)
),
cohorts AS (
SELECT DISTINCT station_name, cohort
FROM `__PROJECT_ID__.__DATASET_ID__.station_causal_input`
)
SELECT
c.station_name,
co.cohort,
c.p_value,
c.prob_causal_effect,
c.absolute_effect,
c.relative_effect,
c.status
FROM causal AS c
INNER JOIN cohorts AS co
ON c.station_name = co.station_name
ORDER BY c.station_name ASC;
CREATE OR REPLACE VIEW `__PROJECT_ID__.__DATASET_ID__.station_ops_signals`
AS
SELECT
'ANOMALY_ALERTS' AS signal_category,
FORMAT(
'Station %s flagged on %s: observed %.0f trips (expected interval %.0f to %.0f, probability %.3f).',
station_name,
CAST(DATE(time_series_timestamp) AS STRING),
time_series_data,
lower_bound,
upper_bound,
anomaly_probability) AS incident_summary
FROM `__PROJECT_ID__.__DATASET_ID__.station_anomalies`
WHERE is_anomaly IS TRUE
UNION ALL
SELECT
'SENSOR_QUARANTINE' AS signal_category,
FORMAT(
'Station %s quarantined before anomaly scoring: reason=%s, points=%d, stddev=%.4f.',
station_name,
quarantine_reason,
point_count,
stddev_trips) AS incident_summary
FROM `__PROJECT_ID__.__DATASET_ID__.station_series_health`
WHERE is_eligible IS FALSE
UNION ALL
SELECT
'PROMO_CAUSAL_LIFT' AS signal_category,
FORMAT(
'Station %s (%s): prob_causal=%.3f, p_value=%.4f, abs_effect=%.1f trips, rel_lift=%.1f%%.',
station_name,
cohort,
COALESCE(prob_causal_effect, 0.0),
COALESCE(p_value, 1.0),
COALESCE(absolute_effect, 0.0),
COALESCE(relative_effect, 0.0) * 100.0) AS incident_summary
FROM `__PROJECT_ID__.__DATASET_ID__.station_causal_results`;
EOF
sed -i "s/__PROJECT_ID__/${PROJECT_ID}/g; s/__DATASET_ID__/${DATASET_ID}/g" causal_and_signals.sql
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false < causal_and_signals.sql
Inspect station_causal_results to compare the three promoted hubs (PROMO_TREATED) against the three unpromoted negative-control hubs (CONTROL_PLACEBO):
bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false \
"SELECT
station_name,
cohort,
ROUND(prob_causal_effect, 3) AS prob_causal,
ROUND(p_value, 4) AS p_value,
ROUND(absolute_effect, 1) AS abs_effect_trips,
ROUND(relative_effect * 100, 1) AS rel_lift_pct
FROM \`${PROJECT_ID}.${DATASET_ID}.station_causal_results\`
ORDER BY cohort DESC, station_name ASC"
The output is similar to the following:
+-----------------------+-----------------+-------------+---------+------------------+--------------+
| station_name | cohort | prob_causal | p_value | abs_effect_trips | rel_lift_pct |
+-----------------------+-----------------+-------------+---------+------------------+--------------+
| E 17 St & Broadway | PROMO_TREATED | 1.0 | 0.0 | 3482.2 | 63.2 |
| Pershing Square North | PROMO_TREATED | 1.0 | 0.0 | 2331.7 | 28.7 |
| West St & Chambers St | PROMO_TREATED | 1.0 | 2.0E-4 | 3015.3 | 43.4 |
| 12 Ave & W 40 St | CONTROL_PLACEBO | 0.145 | 0.8551 | -152.3 | -2.6 |
| Broadway & E 22 St | CONTROL_PLACEBO | 0.254 | 0.7462 | -267.7 | -5.0 |
| W 21 St & 6 Ave | CONTROL_PLACEBO | 0.439 | 0.5611 | -455.9 | -8.4 |
+-----------------------+-----------------+-------------+---------+------------------+--------------+
Plotting relative lift and causal probability side by side confirms that the promotion—not background seasonality—drove the August surge:

Notice the sharp separation between cohorts. Here, abs_effect_trips is the 14-day cumulative total over August 1–14, prob_causal is the probability of a genuine causal effect, and a low p_value (< 0.05) indicates the shift is unlikely due to chance. All three PROMO_TREATED hubs report statistically significant cumulative lift (+28.7% to +63.2%, prob_causal >= 0.9998, p_value <= 0.0002), while all three CONTROL_PLACEBO hubs remain statistically indistinguishable from zero (p_value >= 0.56).
Generate the executive brief as the restricted analyst
Create brief.sql, mint a fresh analyst token, and submit the brief through the BigQuery REST v2 jobs.query method. If the response reports jobComplete: false, poll jobs.getQueryResults until the job finishes:
cat << 'EOF' > brief.sql
-- Copyright 2026 Google LLC
-- SPDX-License-Identifier: Apache-2.0
SELECT
signal_category,
executive_brief.severity AS severity,
executive_brief.executive_summary AS executive_summary,
executive_brief.top_action AS top_action
FROM
(
SELECT
signal_category,
AI.AGG(
incident_summary,
'Synthesize these station operational signals into a concise executive action brief. Set severity strictly to uppercase HIGH, MEDIUM, or LOW.',
connection_id => '__PROJECT_ID__.__BQ_LOCATION__.__CONNECTION_ID__',
endpoint => '__GEMINI_MODEL__',
max_error_ratio => 0.05,
output_schema =>
'severity STRING NOT NULL OPTIONS(description="Uppercase severity: HIGH, MEDIUM, or LOW"), executive_summary STRING NOT NULL, top_action STRING NOT NULL')
AS executive_brief
FROM `__PROJECT_ID__.__DATASET_ID__.station_ops_signals`
GROUP BY signal_category
)
ORDER BY signal_category ASC
EOF
sed -i "s/__PROJECT_ID__/${PROJECT_ID}/g; s/__DATASET_ID__/${DATASET_ID}/g; s/__BQ_LOCATION__/${BQ_LOCATION}/g; s/__CONNECTION_ID__/${CONNECTION_ID}/g; s/__GEMINI_MODEL__/${GEMINI_MODEL}/g" brief.sql
ANALYST_TOKEN="$(gcloud auth print-access-token --impersonate-service-account="${ANALYST_SA_EMAIL}")"
export ANALYST_TOKEN
test -n "${ANALYST_TOKEN}"
jq -n --rawfile query brief.sql --arg location "${BQ_LOCATION}" \
'{query: $query, useLegacySql: false, location: $location, timeoutMs: 60000}' > /tmp/brief_req.json
BRIEF_HTTP_CODE="$(curl -sS -o /tmp/brief_resp.json -w "%{http_code}" -X POST \
-H "Authorization: Bearer ${ANALYST_TOKEN}" \
-H "Content-Type: application/json" \
"https://bigquery.googleapis.com/bigquery/v2/projects/${PROJECT_ID}/queries" \
-d @/tmp/brief_req.json)"
echo "Analyst brief HTTP status: ${BRIEF_HTTP_CODE}"
test "${BRIEF_HTTP_CODE}" = "200"
export BRIEF_JOB_ID="$(jq -r '.jobReference.jobId' /tmp/brief_resp.json)"
for attempt in $(seq 1 12); do
if jq -e '.jobComplete == true' /tmp/brief_resp.json >/dev/null; then
break
fi
sleep 10
curl -sS -f -o /tmp/brief_resp.json \
-H "Authorization: Bearer ${ANALYST_TOKEN}" \
"https://bigquery.googleapis.com/bigquery/v2/projects/${PROJECT_ID}/queries/${BRIEF_JOB_ID}?location=${BQ_LOCATION}&timeoutMs=60000"
done
jq -e '.jobComplete == true' /tmp/brief_resp.json >/dev/null
jq -r '.rows[] | [.f[].v] | @tsv' /tmp/brief_resp.json
The output is similar to the following (exact wording varies across Gemini runs):
ANOMALY_ALERTS MEDIUM On 2017-08-07, three key stations (12 Ave & W 40 St, Broadway & E 22 St, and W 21 St & 6 Ave) exhibited statistically significant underperformance, with trip volumes falling well below their expected lower bounds. Investigate potential localized disruptions, service outages, or docking station blockages at these three central locations to restore normal trip volumes.
PROMO_CAUSAL_LIFT HIGH The promotional campaign demonstrated exceptional success, driving highly significant trip increases at all treated stations: E 17 St & Broadway (+63.2% lift, +3,482 trips), West St & Chambers St (+43.4% lift, +3,015 trips), and Pershing Square North (+28.7% lift, +2,332 trips), all with 100% causal probability. Control stations showed no statistically significant changes, confirming the lift was directly caused by the promotion. Expand the promotional campaign to additional target stations and immediately increase fleet rebalancing and dock capacity at the highly impacted treated stations to support the sustained surge in demand.
SENSOR_QUARANTINE MEDIUM Station_Maintenance_Flatline has been quarantined due to a zero-variance degenerate signal across 212 data points, indicating a frozen sensor or data transmission failure. Dispatch a maintenance technician to inspect and reboot the sensor or telemetry equipment at Station_Maintenance_Flatline.
Verification
Verify that AI.CAUSAL_EFFECT returned 6 error-free rows with statistically significant lift on promotional hubs (prob_causal_effect >= 0.90 and relative_effect > 0.15). Also confirm that INFORMATION_SCHEMA.JOBS attributes the brief job to the restricted analyst and that every brief row has non-empty fields and a valid severity:
CAUSAL_COUNTS=$(bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false --format=csv \
"SELECT FORMAT('causal_rows=%d,causal_err=%d,sig_treated=%d,brief_by_analyst=%d',
(SELECT COUNT(*) FROM \`${PROJECT_ID}.${DATASET_ID}.station_causal_results\`),
(SELECT COUNTIF(COALESCE(status, '') != '') FROM \`${PROJECT_ID}.${DATASET_ID}.station_causal_results\`),
(SELECT COUNTIF(cohort = 'PROMO_TREATED' AND prob_causal_effect >= 0.90 AND relative_effect > 0.15) FROM \`${PROJECT_ID}.${DATASET_ID}.station_causal_results\`),
(SELECT COUNT(*) FROM \`region-${BQ_LOCATION}\`.INFORMATION_SCHEMA.JOBS WHERE creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 2 HOUR) AND statement_type != 'SCRIPT' AND job_id = '${BRIEF_JOB_ID}' AND user_email = '${ANALYST_SA_EMAIL}'))" | tail -n 1 | tr -d '"')
PLACEBO_SIG=$(bq query --project_id="${PROJECT_ID}" --location="${BQ_LOCATION}" --use_legacy_sql=false --format=csv \
"SELECT COUNTIF(cohort = 'CONTROL_PLACEBO' AND prob_causal_effect >= 0.90 AND relative_effect > 0.15) AS n FROM \`${PROJECT_ID}.${DATASET_ID}.station_causal_results\`" | tail -n 1)
BRIEF_ROWS=$(jq '.rows | length' /tmp/brief_resp.json)
BRIEF_NULLS=$(jq '[.rows[] | select(any(.f[1:][]; (.v // "") | test("\\S") | not))] | length' /tmp/brief_resp.json)
BAD_SEV=$(jq '[.rows[] | select(((.f[1].v // "") | ascii_upcase) as $s | ["HIGH", "MEDIUM", "LOW"] | index($s) | not)] | length' /tmp/brief_resp.json)
echo "${CAUSAL_COUNTS},brief_rows=${BRIEF_ROWS},brief_nulls=${BRIEF_NULLS},bad_sev=${BAD_SEV},placebo_sig=${PLACEBO_SIG}"
Confirm that the output satisfies causal_rows=6, causal_err=0, sig_treated >= 2, brief_by_analyst=1, brief_rows >= 2, brief_nulls=0, bad_sev=0, and placebo_sig=0 (no unpromoted control station shows significant lift):
causal_rows=6,causal_err=0,sig_treated=3,brief_by_analyst=1,brief_rows=3,brief_nulls=0,bad_sev=0,placebo_sig=0
In this section, you measured promotional intervention lift alongside placebo hubs using AI.CAUSAL_EFFECT, then generated typed executive action briefs with AI.AGG as the restricted analyst through the governed Cloud Resource connection only. Next, you remove all cloud resources and IAM bindings created during this lab.
8. Clean up
To avoid ongoing charges and leave your project clean, delete the dataset, connection, service account, and IAM bindings created in this lab.
Remove cloud resources and IAM bindings
Remove the project-level IAM bindings before deleting the Cloud Resource connection so you can still read CONN_SA_EMAIL from the connection metadata. Then delete the BigQuery dataset, Cloud Resource connection, and restricted analyst service account (deleting the service account and connection automatically removes their resource-level roles/iam.serviceAccountTokenCreator and roles/bigquery.connectionUser bindings):
if bq show --connection "${PROJECT_ID}.${BQ_LOCATION}.${CONNECTION_ID}" >/dev/null 2>&1; then
export CONN_SA_EMAIL="$(bq show --connection --format=json "${PROJECT_ID}.${BQ_LOCATION}.${CONNECTION_ID}" | jq -r '.cloudResource.serviceAccountId')"
if gcloud projects get-iam-policy "${PROJECT_ID}" \
--flatten="bindings[].members" \
--filter="bindings.role=roles/aiplatform.user AND bindings.members=serviceAccount:${CONN_SA_EMAIL}" \
--format="value(bindings.role)" | grep -qx "roles/aiplatform.user"; then
gcloud projects remove-iam-policy-binding "${PROJECT_ID}" \
--member="serviceAccount:${CONN_SA_EMAIL}" \
--role="roles/aiplatform.user" \
--condition=None \
--format=none
fi
bq rm -f --connection "${PROJECT_ID}.${BQ_LOCATION}.${CONNECTION_ID}"
fi
for ROLE in roles/bigquery.jobUser roles/bigquery.dataViewer; do
if gcloud projects get-iam-policy "${PROJECT_ID}" \
--flatten="bindings[].members" \
--filter="bindings.role=${ROLE} AND bindings.members=serviceAccount:${ANALYST_SA_EMAIL}" \
--format="value(bindings.role)" | grep -qx "${ROLE}"; then
gcloud projects remove-iam-policy-binding "${PROJECT_ID}" \
--member="serviceAccount:${ANALYST_SA_EMAIL}" \
--role="${ROLE}" \
--condition=None \
--format=none
fi
done
if bq show --dataset "${PROJECT_ID}:${DATASET_ID}" >/dev/null 2>&1; then
bq rm -r -f -d "${PROJECT_ID}:${DATASET_ID}"
fi
if gcloud iam service-accounts describe "${ANALYST_SA_EMAIL}" --project="${PROJECT_ID}" >/dev/null 2>&1; then
gcloud iam service-accounts delete "${ANALYST_SA_EMAIL}" --project="${PROJECT_ID}" --quiet
fi
The cleanup commands don't delete local files. The SQL scripts in ${WORK_DIR} (setup_tables.sql, forecast_multivariate.sql, evaluate_forecast.sql, guardrail_series.sql, detect_anomalies.sql, causal_and_signals.sql, and brief.sql) persist in your Cloud Shell home directory; the temporary API requests and responses under /tmp live on ephemeral Cloud Shell VM storage. Review and remove ${WORK_DIR} when you no longer need it.
Verification
Confirm that cleanup removed the dataset, Cloud Resource connection, restricted service account, and project IAM bindings for both service accounts. Because the connection check matches the service account email as a substring, it still catches stale deleted:serviceAccount:... bindings after connection deletion:
LEFTOVERS=""
if bq show --dataset "${PROJECT_ID}:${DATASET_ID}" >/dev/null 2>&1; then LEFTOVERS="${LEFTOVERS} dataset"; fi
if bq show --connection "${PROJECT_ID}.${BQ_LOCATION}.${CONNECTION_ID}" >/dev/null 2>&1; then LEFTOVERS="${LEFTOVERS} connection"; fi
if gcloud iam service-accounts describe "${ANALYST_SA_EMAIL}" --project="${PROJECT_ID}" >/dev/null 2>&1; then LEFTOVERS="${LEFTOVERS} service-account"; fi
REMAINING_SA_ROLES=$(gcloud projects get-iam-policy "${PROJECT_ID}" \
--flatten="bindings[].members" \
--filter="bindings.members=serviceAccount:${ANALYST_SA_EMAIL} AND bindings.role:(roles/bigquery.jobUser OR roles/bigquery.dataViewer)" \
--format="value(bindings.role)" | wc -l | tr -d ' ')
if [[ -n "${CONN_SA_EMAIL:-}" ]]; then
REMAINING_CONN_ROLES=$(gcloud projects get-iam-policy "${PROJECT_ID}" \
--flatten="bindings[].members" \
--filter="bindings.role=roles/aiplatform.user" \
--format="value(bindings.members)" | awk -v sa="${CONN_SA_EMAIL}" 'index($0, sa) {n++} END {print n + 0}')
else
REMAINING_CONN_ROLES=skipped
fi
LEFTOVERS="${LEFTOVERS# }"
LEFTOVERS="${LEFTOVERS// /,}"
echo "leftovers=${LEFTOVERS:-none} remaining_sa_roles=${REMAINING_SA_ROLES} remaining_conn_roles=${REMAINING_CONN_ROLES}"
Confirm that the output matches:
leftovers=none remaining_sa_roles=0 remaining_conn_roles=0
leftovers lists any resource that still exists. If you run this check in a new shell after the connection is deleted, remaining_conn_roles shows skipped, because the connection's service account email is no longer available.
In this section, you removed the project IAM bindings created by this lab, deleted the BigQuery dataset, Cloud Resource connection, and restricted service account, and confirmed zero residual cloud resources remain.
9. Congratulations
You built and verified a fine-grained demand forecasting solution in BigQuery SQL: per-location zero-shot forecasts, a holdout accuracy evaluation, anomaly guardrails, measured promotion lift, and an executive brief. Every step ran inside the warehouse without granting analysts direct Gemini Enterprise Agent Platform access.
Production considerations
- Token-based TimesFM billing governance: Because
TimesFM 3.0adds model-token charges alongside slot/byte billing starting December 1, 2026, budget forecasting jobs by token volume as well as compute. Track per-job attribution inINFORMATION_SCHEMA.JOBSwithstatement_type != 'SCRIPT', and size slot reservations for the non-model query work. - BigQuery ML vs. online endpoints: Keep batch SQL forecasting, anomaly scoring, and structured
AI.AGGsummarization inside BigQuery via Cloud Resource connections, and monitor jobs inINFORMATION_SCHEMA.JOBS. Export BigQuery ML models to Gemini Enterprise Agent Platform online endpoints only when your workload needs synchronous millisecond serving. - Continuous Queries boundary: BigQuery continuous queries (streaming SQL queries) do not support
AI.FORECASTorAI.DETECT_ANOMALIES; schedule zero-shot forecasting and anomaly jobs on intervals, and reserve continuous queries for row-level streamingAI.GENERATEenrichment or event routing. - Hybrid search and VPC Service Controls: Pair structured SQL tables with
CREATE AI INDEX(Preview) andAI.SEARCH(semantic vector search) when you need semantic document retrieval. For multi-project production workloads, place BigQuery datasets andaiplatform.googleapis.cominside a shared VPC Service Controls perimeter (network-level data-exfiltration boundary).
10. Related codelabs
Explore related BigQuery AI and forecasting codelabs to build on these patterns:
- BigQuery AI functions at scale: zero-shot forecasting and cost guardrails: zero-shot TimesFM forecasting with
AI.FORECAST, batchAI.GENERATEinference, and cost guardrails. This codelab goes further into per-location multivariate forecasts with covariates, holdout evaluation, anomaly guardrails, and causal promotion lift. - Multimodal analytics and zero-shot forecasting with Google Cloud: an introduction to zero-shot forecasting joined with unstructured data analysis in BigQuery.
- Semantic Analysis in BigQuery with managed AI functions and SQL:
AI.SCORE,AI.CLASSIFY,AI.IF, andAI.AGGfor semantic analysis directly in SQL, including theAI.AGGfunction used for the executive brief here.