Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install bigquery-troubleshooting@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin bigquery-troubleshooting v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install bigquery-troubleshooting

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/bigquery-troubleshooting/

Extract the ZIP to .github/skills/ in your repo. The folder name must match bigquery-troubleshooting for Copilot to auto-discover it.

Skill Files (8)

SKILL.md 11.3 KB
---
name: bigquery-troubleshooting
metadata:
  version: "1.1.2"
  category: BigDataAndAnalytics
  publisher: google
description: >-
  Provides diagnostic workflows and step-by-step root-cause analysis
  procedures for actively broken, failing, or slow BigQuery jobs, execution
  graph and query plan stage bottlenecks, system performance issues, or
  unexpectedly expensive workloads. Use when interpreting symptoms, isolating
  bottlenecks, diagnosing cost spikes (on-demand query spend, capacity slot
  autoscaling, storage growth), execution graph stages or substep variables,
  identifying root causes, and determining remediation steps. Don't use for
  writing or optimizing SQL, proactive capacity planning, or storage layout
  design (use bigquery-optimization), or when the user already knows which
  telemetry they want and just needs the query (use bigquery-observability).
---

# BigQuery Troubleshooting

## Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-troubleshooting)"`
and append `agent-skills/1.0 (skill:bigquery-troubleshooting)` to `User-Agent` headers.

## Prerequisites & Environment Setup

Before running diagnostic queries or investigating incident telemetry:

1.  **Google Cloud SDK**: Ensure the
    [Google Cloud SDK](https://cloud.google.com/sdk/docs/install) is installed
    and configured.
2.  **Project Selection**: Set the active Google Cloud project:

    ```bash
    gcloud config set project {project_id}
    ```

3.  **API Enablement**: Ensure BigQuery and Cloud Monitoring APIs are enabled:

    ```bash
    gcloud services enable bigquery.googleapis.com monitoring.googleapis.com
    ```

4.  **Authentication**: Authenticate the environment:
    *   CLI commands (`bq show -j`): `gcloud auth login`
    *   SDKs and automated diagnostic scripts:
        `gcloud auth application-default login`
    *   Service accounts: Set
        `GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"`

5.  **Billing & IAM Roles**:
    *   Verify an active Google Cloud Billing account is attached to
        `{project_id}`.
    *   Ensure appropriate IAM roles:
        *   `roles/bigquery.jobUser`: Executing diagnostic queries and
            inspecting your own jobs via CLI (`bq show -j`, `bq ls -j`);
            pair with read roles below to query `INFORMATION_SCHEMA`.
        *   `roles/bigquery.user`: Querying user-scoped job telemetry
            (`JOBS_BY_USER`, `JOBS_TIMELINE_BY_USER`) and executing
            diagnostic queries (supersedes `roles/bigquery.jobUser`).
        *   `roles/bigquery.metadataViewer`: Inspecting table, dataset,
            and storage metadata (`TABLE_STORAGE`,
            `TABLE_STORAGE_USAGE_TIMELINE`, `TABLES`,
            `SCHEMATA_OPTIONS`).
        *   `roles/bigquery.resourceViewer` or `roles/bigquery.admin`:
            Inspecting any user's job (`bq show -j`), project-, folder-,
            or organization-level jobs at the matching resource scope,
            and reservation, capacity commitment, and assignment
            telemetry on the reservations administration project.
            Enabling `TABLE_STORAGE` opt-in via `ALTER PROJECT` requires
            `roles/bigquery.admin`.
        *   `roles/monitoring.viewer`: Reading Cloud Monitoring metrics.
        *   `roles/billing.viewer` (on the Cloud Billing account):
            Viewing Cloud Billing reports and SKU cost attribution.

6.  **Companion Skills Installation**:
    This skill is part of a 3-pillar operations suite (`bigquery-observability`,
    `bigquery-optimization`, `bigquery-troubleshooting`). If any companion skill
    is not yet installed in your environment, install the full suite:

    ```bash
    npx skills add google/skills --skill bigquery-observability --skill bigquery-optimization --skill bigquery-troubleshooting
    ```

    *(If `bigquery-observability` is not installed, use the self-contained
    baseline formulas and query templates provided directly in the reference
    sections below).*

## Workflow

1.  **Scope & Symptom Identification:** Identify the primary symptom, target
    `project_id`, `region`, `reservation_id`, or `job_id`, and domain
    (Performance, Compute Cost, or Storage Cost). If the request falls outside
    incident diagnosis or asks for a sibling domain, follow **Routing
    Boundaries** below.
2.  **Telemetry Tool Selection:** Follow the tool-selection guidance in the
    [BigQuery observability skill](../bigquery-observability)
    (`bigquery_observability`) to select the appropriate telemetry interface
    (REST API `bq show --location={location} -j {project_id}:{job_id}` for
    single-job stage bottlenecks vs. `INFORMATION_SCHEMA` for system-wide
    factors). Diagnostic workflows, symptom-to-cause mappings, key
    tables/fields, CLI triage commands, and remediation levers are fully defined
    in this skill. For pre-composed SQL query templates and full schema
    dictionaries, consult `bigquery-observability`.
3.  **Open-Ended Triage (Stage 1 Baseline Scan & Conversational Gate):** When
    the user inquiry is open-ended or vague (e.g. *"Why is BigQuery slow
    today?"* or *"Why did my bill spike?"*), execute a bounded high-level
    baseline scan to isolate the affected domain before drilling into deep-dive
    diagnostics:
    *   **Bounded Initial Scan:** Follow the baseline scan guidance in the
        corresponding domain reference under **Domain References**. Ensure
        initial queries are strictly bounded (e.g. 7-day Period-over-Period with
        partition and job-type filters; for unspecified cost spikes, scan the 3
        primary vectors: On-Demand TiB, Capacity slot-hours, and Storage GiB) to
        keep diagnostic telemetry overhead minimal.
    *   **Conversational Gate:** Factually summarize high-level baseline
        findings first and propose 2–3 focused drill-down options rather than
        dumping downstream sub-vector queries unsolicited.
4.  **Domain Deep Dive & Comparative Analysis:** Execute the step-by-step
    diagnostic workflow defined in the corresponding domain reference file
    listed under **Domain References** below, then run the corresponding query
    from the [BigQuery observability skill](../bigquery-observability) following
    its `INFORMATION_SCHEMA` best practices to isolate the root cause via
    comparative analysis against a normal baseline.

## Performance Context: The Relativity of "Slow"

Performance is relative. Always approach performance troubleshooting as a
comparative exercise: identify a comparable past execution, compare the
statistics, and isolate which dimension shifted between a fast baseline and the
slow execution:

-   **Data Processed:** Data volume increase, partition/cluster pruning changes,
    data skew, input record amplification.
-   **Underlying Definitions:** View changes, schema modifications.
-   **System Contention:** Noisy neighbors, saturated capacity (>95% slot
    utilization), idle slot availability, concurrent query spikes.
-   **Configuration Changes:** Slot capacity/autoscale max slots changes,
    expired capacity commitments, idle slot setting changes, or reservation
    reassignments.

## Cost Context: The 4-Step Diagnostic Funnel

Cost troubleshooting requires tracing physical resource consumption (Slot-Hours,
TiB Billed, GiB Stored) rather than fluctuating contract rates:

1.  **Gather:** Determine scope and pull 7-day PoP (or explicit MoM / 180-day)
    baseline metrics.
2.  **Isolate:** Pinpoint whether spend surged from query volume, a single
    "Bully Query", BQML 50x multipliers, uncovered PAYG baselines, autoscaling
    bursts, 90-day storage timer resets, or physical Fail-Safe retention drain.
3.  **Explain:** Correlate with administrative events
    (`INFORMATION_SCHEMA.RESERVATION_CHANGES`,
    `INFORMATION_SCHEMA.CAPACITY_COMMITMENT_CHANGES_BY_PROJECT`,
    `INFORMATION_SCHEMA.SCHEMATA_OPTIONS`, or actor `user_email` /
    `query_hash`).
4.  **Remediate:** Deliver actionable levers (partition filter enforcement,
    query caps, commitment purchases, or Time Travel reduction).

## Domain References

### Performance Troubleshooting

-   **Resource Contention & Performance Slowness**
    (`references/performance_resource_contention.md`): Diagnostic workflows for
    isolating single-job stage bottlenecks (`slot_contention`, `spill_to_disk`),
    cohort baseline comparisons (`normalized_literals`), incident window
    discovery, 1-second reservation slot saturation, timeframe contention
    comparisons, fleet performance variance, and table-level concurrency.
-   **Capacity & Configuration Changes**
    (`references/performance_config_changed.md`): Diagnostic workflows for
    auditing reservation `slot_capacity` and `autoscale.max_slots` edits,
    tracking active capacity commitment timelines, diagnosing reservation
    assignment modifications, and evaluating autoscaling headroom saturation.
-   **Execution Graph & Query Plan Troubleshooting**
    (`references/query_plan_execution_graph.md`): Diagnostic workflows for
    investigating single-job stage bottlenecks (`bq show` point-lookups),
    isolating slowest stages (`end_ms - start_ms`), diagnosing join explosions
    (`records_written >> records_read`, `high_cardinality_joins`), shuffle
    spills (`shuffle_output_bytes_spilled`), and partition skew, substep
    intermediate variable disambiguation (`$1`, `$2`), mandatory bytes scanned
    vs records read corrections, and UI execution graph grounding concepts.

### Cost Troubleshooting

-   **On-Demand Compute Costs** (`references/cost_compute_ondemand.md`):
    Diagnostic workflows for unpartitioned runaway scans (the "Bully Query"),
    hidden Row-Level Security (RLS) redaction gaps, BigQuery ML (BQML) 50x model
    training rate multipliers, and user/service account query quotas.
-   **Capacity (Editions) Compute Costs**
    (`references/cost_compute_capacity.md`): Diagnostic workflows for uncovered
    baseline slot penalties (baseline > commitments), reservation baseline
    reductions triggering autoscale surges (`RESERVATION_BASELINE_CHANGED`),
    autoscaler thrashing from batch cron spikes, and serverless Apache Spark
    stored procedure slot-hours.
-   **Storage Footprint & Retention Costs** (`references/cost_storage.md`):
    Diagnostic workflows for historical partition 90-day timer resets (the DML
    trap), unpartitioned table active data traps, physical Time Travel and
    Fail-Safe churn on daily overwrites, and dropped table Fail-Safe drain
    periods.

## Routing Boundaries

If a user request shifts outside incident diagnosis during troubleshooting,
execute the corresponding handoff:

*   **SQL Query Optimizations:** When the user asks to optimize the SQL query
    (e.g., rewriting joins or eliminating `SELECT *`), hand off to
    `bigquery-optimization`.
*   **Raw Telemetry & Schema Retrieval:** When the user asks for standalone
    `INFORMATION_SCHEMA` queries without an active performance regression or
    incident (e.g. general telemetry queries), hand off to
    `bigquery-observability`.
*   **Proactive Capacity & Storage Planning:** When the user requests future
    reservation sizing, commitment purchasing, or storage billing model
    evaluations, hand off to `bigquery-optimization`.
references/
attribution.md 1.9 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand, with the metrics environment variable. Set it inline on each
    command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-troubleshooting)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage.

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
    server, include `agent-skills/1.0 (skill:bigquery-troubleshooting)` in the `User-Agent`
    header. If a `User-Agent` header is already specified, append this string to
    the end of it rather than overwriting existing `User-Agent` data — the
    collection pipeline parses the `agent-skills/<version>` and `skill:<name>`
    tokens, so any rewording breaks attribution:

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:bigquery-troubleshooting)
    ```

-   **Constraint for Generated Code**: The tracking prefix is strictly for
    commands you execute directly in the terminal. Do NOT include this tracking
    prefix in generated scripts, Terraform templates, or code provided to the
    user for their own repositories.

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
cost_compute_capacity.md 16.2 KB
# BigQuery Troubleshooting: Capacity (Editions) Cost & Slot Allocation

This reference guide provides root-cause mapping and remediation strategies for
BigQuery Editions and capacity compute cost spikes (slot-hour usage, uncovered
baseline penalties, and autoscaler surges). It focuses strictly on
Capacity-based compute billable usage (Editions, Commitments, Baseline, and
Autoscaling slot-hours). Each section connects the observed symptom to potential
root causes and points to the corresponding audit query in
`bigquery-observability`.

## Table of Contents

-   [1. 4-Step Diagnostic Funnel](#1-4-step-diagnostic-funnel) (Lines 27-127)
-   [2. Diagnostic Workflows by Symptom & Root Cause](#2-diagnostic-workflows-by-symptom-root-cause)
    (Lines 129-259)
    -   [Scenario 1: Uncovered Baseline Slots Penalty & Commitment Expiration](#scenario-1-uncovered-baseline-slots-penalty-commitment-expiration)
        (Lines 131-168)
    -   [Scenario 2: Baseline Reduction Triggering Autoscale Surge](#scenario-2-baseline-reduction-triggering-autoscale-surge)
        (Lines 170-190)
    -   [Scenario 3: Reservation Autoscaler Thrashing & Concurrency Spikes](#scenario-3-reservation-autoscaler-thrashing-concurrency-spikes)
        (Lines 192-218)
    -   [Scenario 4: Unexpected "BigQuery Reservation API" Charges (Serverless & Managed Features)](#scenario-4-unexpected-bigquery-reservation-api-charges-serverless-managed-features)
        (Lines 220-259)
-   [3. Telemetry & Data Retrieval Reference](#3-telemetry-data-retrieval-reference)
    (Lines 261-278)

## 1. 4-Step Diagnostic Funnel

When investigating capacity / Edition cost questions (e.g., *"Why did my Edition
bill increase?"*, *"What is driving my reservation autoscale spend?"*, or
Month-over-Month comparisons):

1.  **Step 1: Context Resolution & Baseline Scan (Gather)**

    *   **Scope Resolution & Target Project:** Identify the target project,
        `region`, `edition` (Standard, Enterprise, Enterprise Plus), and
        analysis timeframe.
    *   **Time Window & Baseline:** Default to a standard **7-day
        Period-over-Period (PoP)** window comparing the last 7 days against the
        preceding 7 days (`CURRENT_DATE() - 7` to `CURRENT_DATE() - 14`) if
        unspecified; otherwise evaluate the user's requested timeframe against
        its corresponding prior baseline period
        (`INFORMATION_SCHEMA.RESERVATIONS_TIMELINE` and
        `INFORMATION_SCHEMA.CAPACITY_COMMITMENT_CHANGES_BY_PROJECT` retain 180
        days).
    *   **Baseline Scan:** Query `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE` for
        total billed slot-hours across reservations.
    *   **Admin Project Resolution & Zero-Row Test:**
        *   If the user explicitly provided the `admin_project_id` (or if the
            project owns the reservations), execute capacity queries directly
            scoped to that admin project.
        *   If the baseline query returns 0 rows, STOP. Do not compute
            aggregates over an empty set. Execute the following triage:
            1.  *Query Running Project Check:* In BigQuery Editions,
                reservations and commitments are owned by an **Admin Project**,
                while queries run in separate **Assignee / Query Running
                Projects**. Check `reservation_id` in `INFORMATION_SCHEMA.JOBS`
                (formatted as
                `{admin_project_id}:{location}.{reservation_name}`) to resolve
                the true admin project, then re-run the scan scoped to
                `{admin_project_id}`.
            2.  *Compute Model Check:* If `reservation_id IS NULL` in
                `INFORMATION_SCHEMA.JOBS`, the project runs on On-Demand compute
                --> route to `references/cost_compute_ondemand.md`.
            3.  *Region & Scope Verification:* If unassigned, prompt the user to
                confirm the admin project ID and region.
    *   **Report Factually:** State the baseline vs. current slot-hour volume
        and percentage growth before diagnosing root causes.

2.  **Step 2: Vector Decomposition & Anomaly Isolation (Isolate)**

    *   Deconstruct capacity spend across the two reporting levels
        (Edition-Level Invoice Reconciliation vs. Reservation-Level Workload
        Breakdown):
        *   **Edition-Level Spend Attribution (Invoice Reconciliation):**
            Capacity commitments are purchased at the Edition tier (admin
            project) and pooled across all reservations in that Edition. Only at
            the Edition level can we reconcile invoice charges and attribute:
            *   *1-Year Committed Slot-Hours:* Slot capacity purchased under
                1-Year commitments, billed 24/7 at fixed discounted rates.
            *   *3-Year Committed Slot-Hours:* Slot capacity purchased under
                3-Year commitments, billed 24/7 at fixed discounted rates.
            *   *Uncovered Pay-As-You-Go (PAYG) Baseline Slot-Hours:* Configured
                baseline capacity across all reservations in the Edition that
                exceeds active commitments, billed 24/7 at variable hourly PAYG
                rates.
            *   *Autoscaled PAYG Slot-Hours:* Dynamic autoscaling slot-seconds
                aggregated across all reservations, billed at variable hourly
                PAYG rates.
        *   **Reservation-Level Workload Breakdown (Workload Attribution):**
            Individual reservations track query workload consumption without
            commitment attribution. Because commitments are pooled across the
            Edition, an individual reservation cannot determine whether its
            baseline is satisfied by commitments or PAYG:
            *   *Billable Baseline Slot-Hours:* Configured baseline capacity
                (`(slot_capacity * 60) / 3600.0` in the creation region where
                `is_creation_region = TRUE`).
            *   *Autoscaled Slot-Hours (PAYG):* Dynamic autoscaling consumed by
                queries (`period_autoscale_slot_seconds / 3600.0`), billed at
                hourly PAYG rates.

3.  **Step 3: Event & Configuration Correlation (Explain Root Cause)**

    *   Correlate the isolated sub-vector with chronological configuration
        events:
        *   Query `INFORMATION_SCHEMA.RESERVATION_CHANGES` for `action =
            'UPDATE'` (e.g. `slot_capacity` manually reduced, forcing workloads
            into autoscale), `autoscale.max_slots` modifications, or assignment
            changes.
        *   Query `INFORMATION_SCHEMA.CAPACITY_COMMITMENT_CHANGES_BY_PROJECT`
            for commitment expirations (`action = 'DELETE'`, `state =
            'DELETED'`), creations, or non-renewal (`renewal_plan = 'NONE'`).
        *   **Disaster Recovery (DR) Regional Impact:** Under BigQuery Managed
            DR (Enterprise Plus), standby baseline compute capacity in the
            secondary region is provided at **no additional charge**; baseline
            compute capacity is billed strictly in the creation region
            (`is_creation_region = TRUE`). In
            `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE`, `slots_assigned` shifts
            to the secondary region during a failover event, but the billable
            baseline is always derived from `IF(is_creation_region,
            slot_capacity, 0)` regardless of failover.

4.  **Step 4: Actionable Remediation & Customer Levers (Remediate)**

    *   Deliver concrete, immediate mitigation levers (commitment purchases to
        cover steady baseline, autoscaler parameter adjustments, or workload
        isolation) as detailed in the matching scenario below.

## 2. Diagnostic Workflows by Symptom & Root Cause

### Scenario 1: Uncovered Baseline Slots Penalty & Commitment Expiration

*   **When to Use / Symptoms:** Configured reservation baseline capacity exceeds
    active purchased commitments, or a sudden capacity cost spike occurs with
    zero workload changes after a commitment expires or lapses auto-renewal.
*   **Potential Root Causes:**
    *   *Trigger 1 (Over-provisioned Baseline):* Baseline slots were increased
        in a reservation without purchasing matching 1-Year or 3-Year
        commitments at the Edition tier in the admin project.
    *   *Trigger 2 (Commitment Expiration / Lapsed Renewal):* An existing
        commitment expired (`renewal_plan = 'NONE'`). Because reservation
        `slot_capacity` (baseline slots) remained allocated, the slots silently
        reverted from discounted commitment pricing to 24/7 PAYG baseline
        billing.
*   **Key Telemetry & Tables:**
    *   **Baseline Slots View:** `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE`
        (`slot_capacity`, `is_creation_region`, `period_start`, `edition`).
    *   **Commitment Changes View:**
        `INFORMATION_SCHEMA.CAPACITY_COMMITMENT_CHANGES_BY_PROJECT`
        (`slot_count`, `commitment_plan`, `renewal_plan`, `action`, `state`,
        `change_timestamp`).
*   **Diagnostic Procedure & Telemetry:** Query
    `INFORMATION_SCHEMA.CAPACITY_COMMITMENT_CHANGES_BY_PROJECT` for `action =
    'DELETE'`, `state = 'DELETED'`, or `renewal_plan = 'NONE'`, correlating
    `change_timestamp` with the spike date. See **Telemetry & Data Retrieval
    Reference** below to join
    `INFORMATION_SCHEMA.CAPACITY_COMMITMENT_CHANGES_BY_PROJECT` and
    `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE`, reconcile baseline allocations
    against active commitments, and calculate uncovered baseline PAYG
    slot-hours.
*   **Remediation & Actions:**
    *   **Continuous 24/7 Workloads:** Purchase 1-Year or 3-Year Capacity
        Commitments (or re-enable auto-renewal) to cover 100% of baseline slots,
        capturing the 33%–50% discount. Manage commitments in the
        [Cloud Console Reservations Page](https://console.cloud.google.com/bigquery/admin/reservations?project={project_id}&region={region}).
    *   **Variable / Burst Workloads:** Reduce `slot_capacity` (baseline) to `0`
        and rely on **Autoscaling Slots** (`autoscale.max_slots`), which only
        incur charges when actively running queries.

### Scenario 2: Baseline Reduction Triggering Autoscale Surge

*   **When to Use / Symptoms:** Total billed slot-hours increase significantly
    after an administrator reduces reservation baseline capacity.
*   **Potential Root Causes:** Baseline slots were lowered (e.g. from 1,000 to
    200 slots via an `UPDATE` on `slot_capacity`), but steady ETL demand forced
    queries into Autoscaling Slots billed at variable PAYG rates, exceeding the
    original committed baseline cost.
*   **Key Telemetry & Tables:**
    *   **Tables:** `INFORMATION_SCHEMA.RESERVATION_CHANGES`,
        `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE`.
    *   **Key Fields:** `action`, `slot_capacity`,
        `period_autoscale_slot_seconds`, `change_timestamp`.
*   **Diagnostic Procedure & Telemetry:** Query
    `INFORMATION_SCHEMA.RESERVATION_CHANGES` for `action = 'UPDATE'` to identify
    when `slot_capacity` was reduced. See **Telemetry & Data Retrieval
    Reference** below to correlate the drop in baseline capacity with surging
    autoscale slot-hours (`period_autoscale_slot_seconds`).
*   **Remediation & Actions:**
    *   Restore `slot_capacity` to cover predictable, steady ETL demand and
        cover the baseline with 1-Year or 3-Year commitments.

### Scenario 3: Reservation Autoscaler Thrashing & Concurrency Spikes

*   **When to Use / Symptoms:** High autoscaling slot-hour spend driven by
    short, frequent bursts of query concurrency.
*   **Potential Root Causes:** Bursty scheduled queries or concurrent BI
    refreshes cause the autoscaler to scale up to `autoscale.max_slots` (in
    increments of 50 slots). By default, autoscaled capacity is billed
    per-second with a 1-minute minimum duration (and a 60-second scale-down
    window), causing frequent short bursts to accumulate high slot-hour spend
    unless fluid scaling is enabled.
*   **Key Telemetry & Tables:**
    *   **Tables:** `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE`,
        `INFORMATION_SCHEMA.JOBS`.
    *   **Key Fields:** `period_autoscale_slot_seconds`, `timeline`,
        `statement_type`, `creation_time`, `start_time`.
*   **Diagnostic Procedure & Telemetry:** Analyze hourly autoscaled slot-second
    distribution in `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE` and correlate
    peak slot periods with `INFORMATION_SCHEMA.JOBS` concurrency to isolate
    top-of-the-hour batch arrivals (following guidance in **Telemetry & Data
    Retrieval Reference** below).
*   **Remediation & Actions:**
    *   Separate interactive BI dashboards from scheduled batch pipelines into
        dedicated reservations with tailored `autoscale.max_slots` caps.
    *   Stagger top-of-the-hour cron schedules to smooth out slot demand spikes.
    *   Evaluate opting into **fluid scaling** at the reservation level to
        enable true per-second billing with no minimum duration for bursty
        workloads.

### Scenario 4: Unexpected "BigQuery Reservation API" Charges (Serverless & Managed Features)

*   **When to Use / Symptoms:** A project with no active reservations (or on
    On-Demand) incurs charges under the service **"BigQuery Reservation API"**
    (billed as Standard or Enterprise Edition PAYG slot-hours).
*   **Potential Root Causes:** Serverless and managed BigQuery features
    provision dynamic compute capacity behind the scenes:
    1.  **BigQuery Studio / Colab Enterprise Notebooks:** Interactive Python/SQL
        sessions and cell executions run on managed runtimes billed as Standard
        or Enterprise Edition PAYG slot-hours.
    2.  **Stored Procedures for Apache Spark:** PySpark and Spark SQL procedures
        execute on serverless compute billed as Enterprise Edition PAYG
        slot-hours based on vCPU and RAM allocation.
    3.  **BigQuery Data Transfer Service (DTS):** Scheduled data ingestion
        pipelines utilize managed compute billed under the Reservation API
        service.
    4.  **BigLake Managed Tables (Apache Iceberg):** Automated background table
        maintenance (compaction, clustering, snapshot expiration) is billed at
        Enterprise Edition slot-hour rates.
*   **Key Telemetry & Procedures:**
    *   **Google Cloud Console Billing Isolation:**
        1.  Navigate to **Billing > Reports** in Google Cloud Console.
        2.  Set **Service** filter to `BigQuery Reservation API`.
        3.  Group by **Label**: `goog-bq-feature-type`.
        4.  Identify the exact driver by label value:
            *   `BQ_STUDIO_NOTEBOOK`: Interactive BigQuery Studio / Colab
                Enterprise notebook runtimes.
            *   `SPARK_PROCEDURE`: Stored procedures for Apache Spark.
            *   `DATA_TRANSFER_SERVICE`: BigQuery Data Transfer Service ingest
                pipelines.
            *   `BIGLAKE_ICEBERG`: Automated BigLake Iceberg table maintenance.
*   **Remediation & Actions:**
    *   **Cap Dynamic Compute:** Create a dedicated capacity reservation with an
        explicit `autoscale.max_slots` limit and assign the project/workloads to
        it to bound maximum hourly PAYG spend.
    *   **Configure Notebook Idle Timeouts:** Shorten the idle shutdown timeout
        in BigQuery Studio / Colab Enterprise settings to terminate inactive
        interactive runtimes.
    *   **Stagger Data Transfer Schedules:** Stagger DTS transfer runs to avoid
        accumulating simultaneous compute slot-hours during peak business hours.

## 3. Telemetry & Data Retrieval Reference

If the `bigquery-observability` skill is available in your workspace, refer to
its shared telemetry references for canonical query templates and schema
dictionaries. All essential diagnostic workflows, formulas, and remediation
levers are self-contained within this guide.

*   **Edition Invoicing & Commitments Reconciliation:** See the
    `bigquery-observability` skill (`references/compute_capacity_billable.md`,
    section "Edition Billable Slots Timeline") for canonical queries reconciling
    Edition-level commitments against `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE`
    and breaking down per-reservation slot-hours.
*   **Capacity & Reservation View Schemas:** See the `bigquery-observability`
    skill (`references/schema_compute.md`, section "2. Capacity, Reservations &
    Commitments Views") for `INFORMATION_SCHEMA.RESERVATIONS`,
    `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE`,
    `INFORMATION_SCHEMA.RESERVATION_CHANGES`, and
    `INFORMATION_SCHEMA.CAPACITY_COMMITMENTS` schemas.
cost_compute_ondemand.md 16.8 KB
# BigQuery Troubleshooting: On-Demand Compute Spend & Query Scans

This reference guide provides root-cause mapping and remediation strategies for
BigQuery On-Demand compute cost spikes, query scan volume growth, and runaway
queries. It focuses strictly on On-Demand compute billable usage
(`total_bytes_billed` converted to TiB in `INFORMATION_SCHEMA.JOBS`). Each
section connects the observed symptom to potential root causes and points to the
corresponding query in `bigquery-observability`.

## Table of Contents

-   [1. 4-Step Diagnostic Funnel](#1-4-step-diagnostic-funnel) (Lines 28-81)
-   [2. Diagnostic Workflows by Symptom & Root Cause](#2-diagnostic-workflows-by-symptom-root-cause)
    (Lines 83-269)
    -   [Scenario 1: The Bully Query (Unpartitioned Runaway Scan)](#scenario-1-the-bully-query-unpartitioned-runaway-scan)
        (Lines 85-146)
    -   [Scenario 2: Hidden RLS Redacted Costs](#scenario-2-hidden-rls-redacted-costs)
        (Lines 148-183)
    -   [Scenario 3: BQML Model Training Rates](#scenario-3-bqml-model-training-rates)
        (Lines 185-211)
    -   [Scenario 4: User / Service Account Bursting & Missing Quotas](#scenario-4-user-service-account-bursting-missing-quotas)
        (Lines 213-237)
    -   [Scenario 5: Querying Very Small Tables (10 MiB Minimum Billed Data Floor)](#scenario-5-querying-very-small-tables-10-mib-minimum-billed-data-floor)
        (Lines 239-269)
-   [3. Telemetry & Data Retrieval Reference](#3-telemetry-data-retrieval-reference)
    (Lines 271-294)

## 1. 4-Step Diagnostic Funnel

When investigating on-demand compute cost questions (e.g., *"Why did our
on-demand query bill spike?"*, *"Who scanned the most data last week?"*, or
Month-over-Month comparisons):

1.  **Step 1: Context Resolution & Baseline Scan (Gather)**

    *   **Scope Resolution:** Identify the target `project_id`, `region`, and
        requested analysis timeframe.
    *   **Time Window & Baseline:** Default to a standard **7-day
        Period-over-Period (PoP)** window comparing the last 7 days against the
        preceding 7 days (`CURRENT_DATE() - 7` to `CURRENT_DATE() - 14`) if
        unspecified; otherwise evaluate the user's requested timeframe against
        its corresponding prior baseline period (`INFORMATION_SCHEMA.JOBS`
        retains 180 days).
    *   **Baseline Scan:** Query `INFORMATION_SCHEMA.JOBS` for total billed TiB
        aligned to Pacific Time (`PST8PDT`).
    *   **Compute Model Check & Zero-Row Test:** If the baseline query returns 0
        rows, STOP. Do not compute aggregates over an empty set. Automatically
        check if the project runs on Capacity/Editions (inspect `reservation_id`
        in `INFORMATION_SCHEMA.JOBS` or check `INFORMATION_SCHEMA.ASSIGNMENTS`).
        If assigned to a reservation, route to
        `references/cost_compute_capacity.md`. Otherwise, prompt the user to
        confirm the active region and project scope before proceeding.
    *   **Report Factually:** State the percentage increase and the exact TiB
        volume movement before diagnosing root causes.

2.  **Step 2: Vector Decomposition & Anomaly Isolation (Isolate)**

    *   Deconstruct total billed bytes across:
        *   **Query Frequency / Volume:** An increase in total executed jobs
            across automated pipelines.
        *   **The Bully Query:** A single expensive query scanning terabytes or
            petabytes unconstrained.
        *   **BQML Model Training:** `CREATE MODEL` operations under On-Demand
            pricing that bill processed bytes at specialized model training
            rates.
        *   **Hidden RLS Redactions:** Queries against Row-Level Security tables
            returning `NULL` in `total_bytes_billed`.

3.  **Step 3: Event & Query Correlation (Explain Root Cause)**

    *   Group `INFORMATION_SCHEMA.JOBS` by `user_email`,
        `query_info.query_hashes.normalized_literals`, and `statement_type` (and
        include `project_id` when querying organization or folder views).
    *   Identify the top contributing queries, executing actors (user or service
        account), and execution timestamps.

4.  **Step 4: Actionable Remediation & Customer Levers (Remediate)**

    *   Deliver concrete, immediate mitigation levers (enforcing partition
        filters, setting query billing caps, and optimizing query syntax) as
        detailed in the matching scenario below.

## 2. Diagnostic Workflows by Symptom & Root Cause

### Scenario 1: The Bully Query (Unpartitioned Runaway Scan)

*   **When to Use / Symptoms:** A sudden spike in daily On-Demand billed bytes
    attributable to a few single massive queries scanning large volumes of data
    unconstrained.
*   **Potential Root Causes:** Sub-optimal query design in general, including
    missing partition pruning predicates (`WHERE _PARTITIONDATE >= ...`),
    missing cluster filters, unconstrained `SELECT *` scans, non-selective or
    cross joins, or repeated full-table scans across multi-terabyte tables.
*   **Key Telemetry & Tables:**
    *   **Table:** `INFORMATION_SCHEMA.JOBS_BY_PROJECT` (or
        `INFORMATION_SCHEMA.JOBS`), `INFORMATION_SCHEMA.COLUMNS`,
        `INFORMATION_SCHEMA.TABLE_OPTIONS`.
    *   **Filters:** `job_type = 'QUERY'`, `statement_type != 'SCRIPT'`,
        `creation_time >= TIMESTAMP_SUB(...)`.
    *   **Key Fields:** `project_id` (crucial for org/folder-level views),
        `job_id`, `user_email`, `total_bytes_billed`, `total_bytes_processed`,
        `referenced_tables`, `statement_type`,
        `query_info.query_hashes.normalized_literals` (in `JOBS_BY_PROJECT`);
        `table_name`, `column_name`, `data_type`, `is_partitioning_column`,
        `clustering_ordinal_position` (in `COLUMNS`); `option_name =
        'require_partition_filter'`, `option_value` (in `TABLE_OPTIONS`).
*   **Diagnostic Procedure & Telemetry:** See **Telemetry & Data Retrieval
    Reference** below to calculate canonical billed TiB, account for BQML
    multipliers, and sort by spend descending:
    1.  **Query-Template Spend Attribution:** Group `JOBS_BY_PROJECT` by
        `query_info.query_hashes.normalized_literals` to sum job-level
        `total_bytes_billed` and `total_bytes_processed` (and project
        `ANY_VALUE(referenced_tables)`) without double-counting multi-table
        joins.
    2.  **Candidate Table Discovery & Partitioning Audit:** Unnest
        `referenced_tables` to identify which tables those high-scan queries
        touch (do not sum job-level bytes across joined tables; cross-check
        actual table size via `total_logical_bytes` in
        `INFORMATION_SCHEMA.TABLE_STORAGE`), then query
        `INFORMATION_SCHEMA.COLUMNS` and `INFORMATION_SCHEMA.TABLE_OPTIONS` to
        verify whether each referenced table has `DATE`, `TIMESTAMP`,
        `DATETIME`, or `INT64` integer-range partitioning, clustering columns,
        and `require_partition_filter = 'true'`.
*   **Remediation & Actions:**
    *   **Partition & Cluster Unpartitioned Tables:** Unpartitioned tables
        cannot be converted in place or replaced via `OR REPLACE` with a
        different kind of partitioning; use `CREATE TABLE ... PARTITION BY ...
        CLUSTER BY ... AS SELECT * FROM ...` (CTAS) to create a new partitioned
        and clustered table (or `DROP` and recreate it). For table partitioning
        and clustering design, refer to the `bigquery-optimization` skill.
    *   **Enforce Partition Filtering:** Require partition filters on large
        partitioned tables:
        *   *DDL:* `ALTER TABLE {dataset_id}.{table_id} SET OPTIONS
            (require_partition_filter = true);`
        *   *CLI:* `bq update --require_partition_filter=true
            {project_id}:{dataset_id}.{table_id}`
    *   **Set Query Billing Caps:** Set a maximum byte limit to prevent rogue
        scans:
        *   *CLI:* `bq query --use_legacy_sql=false
            --maximum_bytes_billed=107374182400 "{sql_query}"` (e.g., 100 GB
            cap).
        *   *Client Libraries:* Set `job_config.maximum_bytes_billed =
            107374182400` in `QueryJobConfig`.
    *   **Optimize Query Syntax:** Add partition pruning filters, filter or
        aggregate by clustered columns (such as high-cardinality columns), and
        select only required columns instead of `SELECT *`.

### Scenario 2: Hidden RLS Redacted Costs

*   **When to Use / Symptoms:** Queries return `NULL` in `total_bytes_billed` in
    `INFORMATION_SCHEMA.JOBS`, causing standard sum queries to undercount spend
    and creating an apparent discrepancy with the Cloud Billing invoice.
*   **Potential Root Causes:** Row-Level Security (RLS) policies are active on
    the scanned tables. BigQuery hides sensitive statistics
    (`total_bytes_billed`, `total_bytes_processed`, partitions processed, and
    `job_stages`) on all queries against tables with row-level access policies
    to prevent side-channel inference.
*   **Key Telemetry & Tables:**
    *   **Tables:** `INFORMATION_SCHEMA.JOBS` (audit active row access policies
        and filter predicates via `INFORMATION_SCHEMA.ROW_ACCESS_POLICIES` —
        note that Analytics Hub linked datasets return zero rows without error,
        so check the publisher source dataset instead — or list policies and
        grantees with `bq ls --row_access_policies {dataset_id}.{table_id}`).
    *   **Filters:** `job_type = 'QUERY'`, `total_bytes_billed IS NULL`,
        `(error_result IS NULL OR error_result.reason = 'stopped')`.
    *   **Key Fields:** `project_id` (for org/folder-level views), `job_id`,
        `user_email`, `referenced_tables` (`total_bytes_processed` is also
        `NULL` in `INFORMATION_SCHEMA.JOBS` when RLS is active).
*   **Diagnostic Procedure & Telemetry:** Count the volume of redacted queries
    in `INFORMATION_SCHEMA.JOBS` where `total_bytes_billed IS NULL` and
    `(error_result IS NULL OR error_result.reason = 'stopped')`. See **Telemetry
    & Data Retrieval Reference** below to audit active row access policies on
    referenced tables.
*   **Remediation & Actions:**
    *   **Audit Logs or Separate Base Tables:** No IAM permission or role
        unmasks `total_bytes_billed` in `INFORMATION_SCHEMA.JOBS` when a
        referenced table has row-level access policies. Project Owners can view
        bytes processed in Cloud Audit Logs, or route trusted full-table ETL/BI
        pipelines to separate raw base tables that have no row-level access
        policies.
    *   **Reconcile with Billing Reports:** Use Google Cloud Billing Reports
        grouped by SKU (`Analysis`) to track complete financial invoice amounts
        including RLS-redacted queries.

### Scenario 3: BQML Model Training Rates

*   **When to Use / Symptoms:** Billed bytes or invoice costs are significantly
    higher than scanned bytes for specific queries due to machine learning
    training workloads.
*   **Potential Root Causes:** In On-Demand pricing, `CREATE MODEL` operations
    for certain built-in ML algorithms (such as Deep Neural Networks, Matrix
    Factorization, or AutoML) are billed at specialized rates on processed
    bytes.
*   **Key Telemetry & Tables:**
    *   **Table:** `INFORMATION_SCHEMA.JOBS`.
    *   **Filters:** `statement_type = 'CREATE_MODEL'`.
    *   **Key Fields:** `project_id` (for org/folder-level views), `job_id`,
        `user_email`, `total_bytes_processed`, `total_bytes_billed`,
        `statement_type`.
*   **Diagnostic Procedure & Telemetry:** Filter `INFORMATION_SCHEMA.JOBS` for
    `statement_type = 'CREATE_MODEL'` (following guidance in **Telemetry & Data
    Retrieval Reference** below) to evaluate model training byte volume and
    isolate top model training queries.
*   **Remediation & Actions:**
    *   **Pre-materialize Training Sets:** Filter and materialize feature
        datasets into intermediate tables to minimize repeated full table scans
        during iterative training.
    *   **Evaluate Capacity Model:** For frequent or heavy ML model training,
        evaluate whether running workloads under BigQuery Editions (where model
        training consumes slot capacity rather than on-demand byte multipliers)
        is more cost-effective.

### Scenario 4: User / Service Account Bursting & Missing Quotas

*   **When to Use / Symptoms:** A sudden day-over-day spike in total billed
    bytes spread across hundreds or thousands of automated queries from a
    specific identity.
*   **Potential Root Causes:** Newly deployed CI/CD pipeline, unthrottled
    notebook, or automated script executing high-concurrency unpruned queries.
*   **Key Telemetry & Tables:**
    *   **Table:** `INFORMATION_SCHEMA.JOBS`.
    *   **Key Fields:** `project_id`, `user_email`, `creation_time`,
        `total_bytes_billed`, `query_info.query_hashes.normalized_literals`.
*   **Diagnostic Procedure & Telemetry:** Group `INFORMATION_SCHEMA.JOBS` by
    `user_email` and daily date partition to isolate the identity driving the
    surge (following guidance in **Telemetry & Data Retrieval Reference**
    below). Group by `query_info.query_hashes.normalized_literals` for that user
    to identify the specific bursting script.
*   **Remediation & Actions:**
    *   **Configure Cloud Quotas:** Set custom daily query usage limits in the
        Google Cloud Console under **IAM & Admin** > **Quotas & System
        Limits** > **BigQuery API**:
        *   `Query usage per day` (project-level cap).
        *   `Query usage per day per user` (prevents a single rogue script from
            exhausting the budget).
    *   **Project Workload Isolation:** Separate automated pipelines from ad-hoc
        analytical users into separate GCP projects with distinct quota limits.

### Scenario 5: Querying Very Small Tables (10 MiB Minimum Billed Data Floor)

*   **When to Use / Symptoms:** Queries against very small tables (even
    kilobyte-sized reference or status tables) result in disproportionately high
    on-demand compute charges.
*   **Potential Root Causes:** Under BigQuery On-Demand pricing, the minimum
    billed processed data per referenced table in a query is **10 MiB**,
    regardless of actual table size. Likewise, the minimum billed processed data
    per query is **10 MiB**. Automated loops, health probes, or ETL scripts
    querying tiny lookup tables hundreds of times per hour accumulate billable
    bytes rapidly (e.g. 10,000 queries = ~100 GB billed).
*   **Key Telemetry & Tables:**
    *   **Tables:** `INFORMATION_SCHEMA.JOBS`, `INFORMATION_SCHEMA.TABLES`.
    *   **Key Fields:** `project_id`, `job_id`, `user_email`,
        `total_bytes_billed`, `total_bytes_processed`, `referenced_tables`.
*   **Diagnostic Procedure & Telemetry:** Filter `INFORMATION_SCHEMA.JOBS` for
    queries where `total_bytes_billed = 10485760` (10 MiB) or where
    `total_bytes_processed < 10485760` but `total_bytes_billed = 10485760`
    (following guidance in **Telemetry & Data Retrieval Reference** below).
    Count the frequency of these small queries and inspect `referenced_tables`
    to isolate the target lookup tables.
*   **Remediation & Actions:**
    *   **Application-Side Caching:** Cache lookup or configuration tables in
        application memory or Memorystore rather than querying BigQuery
        repeatedly.
    *   **Batch Invocations:** Consolidate frequent individual lookups into
        batched queries using `IN (...)` or joins.
    *   **Evaluate BigQuery Editions:** For workloads that require
        high-frequency lightweight lookups, route the project to BigQuery
        Editions, where compute is billed by slot capacity rather than per-query
        10 MiB minimums.

## 3. Telemetry & Data Retrieval Reference

If the `bigquery-observability` skill is available in your workspace, refer to
its shared telemetry references for canonical query templates and schema
dictionaries. All essential diagnostic workflows, formulas, and remediation
levers are self-contained within this guide.

*   **On-Demand Billed Bytes & Daily Spend:** See the `bigquery-observability`
    skill (`references/compute_ondemand_billable.md`, section "CORE RULE: The
    Golden Base CTE (bytes_billed_cte)") for the canonical bytes billed CTE with
    BQML multipliers and timezone alignment.
*   **Table Partitioning, Clustering & Filter Enforcement Audit:** See the
    `bigquery-observability` skill (`references/storage_footprints.md`, section
    "Table Partitioning, Clustering & Filter Enforcement Audit") to inspect
    `INFORMATION_SCHEMA.COLUMNS` and `INFORMATION_SCHEMA.TABLE_OPTIONS` for
    partitioning columns, clustering columns, and `require_partition_filter`.
*   **Job Metadata:** See the `bigquery-observability` skill
    (`references/schema_compute.md`, section "1. Jobs & Compute Telemetry
    Views") for `INFORMATION_SCHEMA.JOBS` view schema.
*   **Security & Access Policies:** See the `bigquery-observability` skill
    (`references/schema_others.md`, section
    "`INFORMATION_SCHEMA.ROW_ACCESS_POLICIES`") for auditing active row-level
    access policies and filter predicates via SQL, or inspecting grantees with
    `bq ls --row_access_policies` / `rowAccessPolicies.getIamPolicy`.
cost_storage.md 17.9 KB
# BigQuery Troubleshooting: Storage Footprint & Billing Models

This reference guide provides root-cause mapping and remediation strategies for
BigQuery storage cost increases, dataset footprint growth, and billing model
transitions. It focuses strictly on BigQuery Managed Storage billable usage
(Logical vs. Physical storage billing models, native tables, partitions, Time
Travel, and Fail-Safe; external data sources and Cloud Storage buckets are
excluded). Each section connects the observed symptom to potential root causes
and points to the corresponding query in `bigquery-observability`.

## Table of Contents

-   [1. 4-Step Diagnostic Funnel](#1-4-step-diagnostic-funnel) (Lines 31-107)
-   [2. Diagnostic Workflows by Symptom & Root Cause](#2-diagnostic-workflows-by-symptom-root-cause)
    (Lines 109-251)
    -   [Scenario 1: Historical Partition Timer Reset (The DML Trap)](#scenario-1-historical-partition-timer-reset-the-dml-trap)
        (Lines 111-138)
    -   [Scenario 2: The Unpartitioned Table Active Trap](#scenario-2-the-unpartitioned-table-active-trap)
        (Lines 140-163)
    -   [Scenario 3: Time Travel & Fail-Safe Churn on Physical Billing](#scenario-3-time-travel-fail-safe-churn-on-physical-billing)
        (Lines 165-191)
    -   [Scenario 4: Deleted Table / Dataset "Phantom Spend" & Long-Term Promotion](#scenario-4-deleted-table-dataset-phantom-spend-long-term-promotion)
        (Lines 193-233)
    -   [Scenario 5: Table Clones and Snapshots Overestimation](#scenario-5-table-clones-and-snapshots-overestimation)
        (Lines 235-251)
-   [3. Execution Limitations & Footguns](#3-execution-limitations-footguns)
    (Lines 253-289)
-   [4. Telemetry & Data Retrieval Reference](#4-telemetry-data-retrieval-reference)
    (Lines 291-308)

## 1. 4-Step Diagnostic Funnel

When investigating storage cost questions (e.g., *"Why did my storage bill
increase?"*, *"Why is storage spend higher than expected?"*):

1.  **Step 1: Context Resolution & Baseline Scan (Gather)**

    *   **Scope Resolution:** Identify the target `project_id`, `region`, and
        dataset scope.
    *   **Time Window & Baseline:** Default to a standard **7-day
        Period-over-Period (PoP)** window comparing the last 7 days against the
        preceding 7 days (`CURRENT_DATE() - 7` to `CURRENT_DATE() - 14`) if
        unspecified; otherwise evaluate the user's requested timeframe against
        its corresponding prior baseline period
        (`INFORMATION_SCHEMA.TABLE_STORAGE_USAGE_TIMELINE` retains 90 days).
    *   **Baseline Scan (Historical Trend vs. Current Snapshot):**
        *   **Billing Trend & Invoice Audit:** Query
            `INFORMATION_SCHEMA.TABLE_STORAGE_USAGE_TIMELINE` as the absolute
            source of truth for historical 7-day PoP / 30-day billing trends
            (calculates daily average GiB across Active vs. Long-Term tiers;
            note that physical Time Travel and Fail-Safe are integrated into
            total active physical usage).
        *   **Physical Breakdown Snapshot:** Query
            `INFORMATION_SCHEMA.TABLE_STORAGE` for a real-time point-in-time
            snapshot providing the detailed breakdown of physical storage
            components (`current_physical_bytes`, `time_travel_physical_bytes`,
            `fail_safe_physical_bytes`, and `deleted` table drain).
    *   **Zero-Row Test & Opt-In Status Check:** If the baseline query returns 0
        rows or fails with an enablement error, STOP. Do not compute aggregates
        over an empty set. Check whether the project has enabled storage
        collection by checking `enable_info_schema_storage` in
        `INFORMATION_SCHEMA.EFFECTIVE_PROJECT_OPTIONS` (see **Telemetry & Data
        Retrieval Reference** below for schema and field definitions):
        *   **If Enabled (`option_value = 'true'`):** Opt-in is active. If 0
            rows returned from `INFORMATION_SCHEMA.TABLE_STORAGE`, verify the
            target region and confirm that datasets exist in that location.
        *   **If Not Enabled (0 rows returned or `option_value != 'true'`):**
            Storage metrics collection is disabled. Inform the user to enable it
            by setting the DDL option
            `region-{location}.enable_info_schema_storage = TRUE` (via `ALTER
            PROJECT` or `ALTER ORGANIZATION`).
        *   **Zero-Opt-In Fallback:** Because full historical
            `INFORMATION_SCHEMA.TABLE_STORAGE` data takes ~24 hours to populate
            post-enablement, conduct immediate triage using
            `INFORMATION_SCHEMA.PARTITIONS` and
            `INFORMATION_SCHEMA.SCHEMATA_OPTIONS` (which report partition byte
            sizes and dataset billing models without requiring
            `enable_info_schema_storage` opt-in).
    *   **Report Factually:** State the baseline vs. current storage volume and
        percentage growth before diagnosing root causes.

2.  **Step 2: Vector Decomposition & Anomaly Isolation (Isolate)**

    *   Determine if growth stems from:
        *   **Active Logical Growth:** Mature data failing to reach 90 unmutated
            days (unpartitioned table trap or unscoped DML timer resets).
        *   **Physical Retention Churn:** Time Travel and Fail-Safe blocks
            accumulating from daily `WRITE_TRUNCATE` or batch overwrites.
        *   **Dropped Table Fail-Safe Drain:** Deleted tables continuing to
            incur physical Fail-Safe charges during the 7-day drain period.

3.  **Step 3: Event & Configuration Correlation (Explain Root Cause)**

    *   Correlate the isolated sub-vector with lifecycle and DDL events:
        *   Query `INFORMATION_SCHEMA.SCHEMATA_OPTIONS` for billing model
            switches (between `LOGICAL` and `PHYSICAL`) or TTL changes.
        *   Query `INFORMATION_SCHEMA.PARTITIONS` for recent
            `last_modified_time` updates on historical partitions.
        *   Query `INFORMATION_SCHEMA.TABLE_STORAGE` with `WHERE deleted = TRUE`
            to inspect deleted tables actively draining Fail-Safe bytes.

4.  **Step 4: Actionable Remediation & Customer Levers (Remediate)**

    *   Deliver concrete, immediate mitigation levers (e.g. reducing Time Travel
        to 48 hours, partitioning unpartitioned tables, isolating mutable
        columns, or switching billing models) as detailed in the matching
        scenario below.

## 2. Diagnostic Workflows by Symptom & Root Cause

### Scenario 1: Historical Partition Timer Reset (The DML Trap)

*   **When to Use / Symptoms:** An abrupt doubling of storage spend on
    historical tables with zero data volume additions.
*   **Potential Root Causes:** BigQuery automatically discounts storage by 50%
    (Long-Term pricing) when a partition has not been modified for 90
    consecutive days. If an unscoped `UPDATE`, `DELETE`, or `MERGE` query
    touches even a single row in an old partition, that partition's
    `last_modified_time` updates to current timestamp, instantly resetting the
    90-day timer back to day zero and reverting to full-price Active storage.
*   **Key Telemetry & Tables:**
    *   **Table:** `INFORMATION_SCHEMA.PARTITIONS`.
    *   **Filters:** `table_name = 'TARGET_TABLE'`, `last_modified_time >=
        TIMESTAMP_SUB(...)`.
    *   **Key Fields:** `partition_id`, `last_modified_time`,
        `total_logical_bytes`, `storage_tier` (`ACTIVE`, `LONG_TERM`).
*   **Diagnostic Procedure & Telemetry:** Inspect
    `INFORMATION_SCHEMA.PARTITIONS` for partitions older than 90 days where
    `last_modified_time` was updated within the last 7 days (following guidance
    in **Telemetry & Data Retrieval Reference** below). Sort by
    `total_logical_bytes` descending to isolate high-impact tables.
*   **Remediation & Actions:**
    *   Add partition pruning predicates (e.g., `WHERE _PARTITIONDATE >=
        DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY)`) to all recurring ETL
        pipelines.
    *   Isolate frequently mutated columns (e.g., `status`, `updated_at`) into a
        separate unpartitioned lookup table so historical fact partitions remain
        unmutated.

### Scenario 2: The Unpartitioned Table Active Trap

*   **When to Use / Symptoms:** Multi-year-old historical datasets remain billed
    at 100% Active rates with 0% Long-Term discount.
*   **Potential Root Causes:** Unpartitioned tables track a single table-level
    `last_modified_time`. When daily ETL appends or inserts new rows, BigQuery
    updates the timestamp for the entire table. As a result, no historical data
    ever reaches 90 unmutated days.
*   **Key Telemetry & Tables:**
    *   **Table:** `INFORMATION_SCHEMA.TABLE_STORAGE`.
    *   **Filters:** `creation_time < TIMESTAMP_SUB(CURRENT_TIMESTAMP(),
        INTERVAL 90 DAY)`.
    *   **Key Fields:** `table_name`, `active_logical_bytes`,
        `long_term_logical_bytes`.
*   **Diagnostic Procedure & Telemetry:** Inspect
    `INFORMATION_SCHEMA.TABLE_STORAGE` for mature tables where `creation_time`
    is >90 days old (following guidance in **Telemetry & Data Retrieval
    Reference** below). Flag tables where `long_term_logical_bytes = 0` and
    `active_logical_bytes > 0`.
*   **Remediation & Actions:**
    *   Partition the table by ingestion time or date/timestamp (`CREATE TABLE
        ... PARTITION BY DATE(event_timestamp)`).
    *   Once partitioned, all partitions older than 90 days immediately drop to
        the 50% discounted Long-Term rate.

### Scenario 3: Time Travel & Fail-Safe Churn on Physical Billing

*   **When to Use / Symptoms:** Physical storage costs are significantly higher
    than logical storage despite good data compression.
*   **Potential Root Causes:** Under Physical storage billing, billable storage
    includes active data plus **Time Travel** (2–7 days) and **Fail-Safe** (7
    days non-configurable). If the workload runs daily `WRITE_TRUNCATE`,
    `CREATE OR REPLACE TABLE`, or heavy batch updates, replaced physical blocks
    accumulate in Time Travel and Fail-Safe billed at active physical rates.
*   **Key Telemetry & Tables:**
    *   **Table:** `INFORMATION_SCHEMA.TABLE_STORAGE`.
    *   **Key Fields:** `active_physical_bytes`, `time_travel_physical_bytes`,
        `fail_safe_physical_bytes`.
*   **Diagnostic Procedure & Telemetry:** See **Telemetry & Data Retrieval
    Reference** below to compare active physical bytes against total restorable
    churn (`time_travel_physical_bytes + fail_safe_physical_bytes`) and flag
    datasets where the churn ratio `(time_travel + fail_safe) / active` exceeds
    1.0.
*   **Remediation & Actions:**
    *   Reduce dataset Time Travel to 2 days (`ALTER SCHEMA {dataset_id} SET
        OPTIONS (max_time_travel_hours = 48);`).
    *   Avoid full-table truncates; use partition-level drops (`DROP PARTITION`)
        or incremental merges.
    *   If churn remains >1.0 and compression is below 2x, switch the dataset
        back to `LOGICAL` billing in the
        [Cloud Console Dataset Details Page](https://console.cloud.google.com/bigquery?project={project_id}&p={project_id}&d={dataset_id}&page=dataset)
        (after the 14-day lock-in expires).

### Scenario 4: Deleted Table / Dataset "Phantom Spend" & Long-Term Promotion

*   **When to Use / Symptoms:** A user deletes a large table or dataset in a
    physical storage billing dataset, but storage charges continue or even
    increase on the Cloud Billing invoice.
*   **Potential Root Causes:**
    *   *Time Travel & Fail-Safe Retention:* In physical billing, deleted data
        is retained for the duration of the configured Time Travel window (2–7
        days) plus an additional 7 days for Fail-Safe recovery. During this
        entire retention window, deleted blocks contribute to billable active
        physical storage even though the table no longer appears in the console
        or `INFORMATION_SCHEMA.TABLES` (it remains visible in
        `INFORMATION_SCHEMA.TABLE_STORAGE` with `deleted = TRUE`).
    *   *Long-Term to Active Promotion:* If the deleted data was in long-term
        physical storage, deletion causes this data to move into active physical
        storage during the Time Travel and Fail-Safe windows. Because active
        physical storage costs approximately 2 times more than long-term
        physical storage, deleting a dataset or table in physical billing model
        can cause a temporary spike in daily storage charges.
    *   *Logical Billing Contrast:* Under logical storage billing, dropped
        tables never incur charges for Time Travel or Fail-Safe; billable
        logical storage drops to 0 immediately upon deletion.
*   **Key Telemetry & Tables:**
    *   **Tables:** `INFORMATION_SCHEMA.SCHEMATA_OPTIONS`,
        `INFORMATION_SCHEMA.TABLE_STORAGE`.
    *   **Filters:** `deleted = TRUE`.
    *   **Key Fields:** `table_name`, `table_deletion_time`,
        `fail_safe_physical_bytes`, `time_travel_physical_bytes`.
*   **Diagnostic Procedure & Telemetry:** Check
    `INFORMATION_SCHEMA.SCHEMATA_OPTIONS` for `storage_billing_model`. If
    `PHYSICAL`, query `INFORMATION_SCHEMA.TABLE_STORAGE` with `WHERE deleted =
    TRUE` to view all deleted tables currently draining Time Travel and
    Fail-Safe bytes (see **Telemetry & Data Retrieval Reference** below). Query
    `INFORMATION_SCHEMA.JOBS` with `statement_type IN ('DROP_TABLE',
    'DROP_SCHEMA')` to confirm drop execution timestamp and actor.
*   **Remediation & Actions:**
    *   Explain the 9–14 day drain window factually to the user; charges will
        terminate once the Time Travel plus 7-day Fail-Safe window elapses.
    *   To minimize deletion costs for physical billing model datasets in the
        future, lower the dataset Time Travel window to 2 days
        (`max_time_travel_hours = 48`) before deleting large tables.

### Scenario 5: Table Clones and Snapshots Overestimation

*   **When to Use / Symptoms:** Raw table size queries report massive storage
    volumes that do not match the lower billed amount on the invoice.
*   **Potential Root Causes:** Table clones and snapshots report storage bytes
    equal to the full base table size in `INFORMATION_SCHEMA.TABLE_STORAGE`.
    However, BigQuery **only bills for modified or added delta blocks**.
*   **Key Telemetry & Tables:**
    *   **Tables:** `INFORMATION_SCHEMA.TABLE_STORAGE_USAGE_TIMELINE`,
        `INFORMATION_SCHEMA.TABLE_SNAPSHOTS`.
    *   **Key Fields:** `billable_total_logical_usage`, `base_table_name`.
*   **Diagnostic Procedure & Telemetry:** See **Telemetry & Data Retrieval
    Reference** below to query true billed storage deltas in
    `INFORMATION_SCHEMA.TABLE_STORAGE_USAGE_TIMELINE`, and check
    `INFORMATION_SCHEMA.TABLE_SNAPSHOTS` to verify base table lineage.
*   **Remediation & Actions:**
    *   Reassure the customer that unmutated cloned blocks are free of charge.

## 3. Execution Limitations & Footguns

*   **Timeline View Delay (48–72h):**
    `INFORMATION_SCHEMA.TABLE_STORAGE_USAGE_TIMELINE` has a 48–72 hour
    settlement lag. Use `INFORMATION_SCHEMA.TABLE_STORAGE` for real-time
    investigation, and use `INFORMATION_SCHEMA.TABLE_STORAGE_USAGE_TIMELINE` for
    historical 30-day billing reconciliation (ignoring the last 3 days).
*   **14-Day Cooldown (Hard Lock-in):** Once a dataset's storage billing model
    is changed between `LOGICAL` and `PHYSICAL`, it **cannot be changed again
    for 14 days**. Always verify compression ratios and churn rates over a full
    7-day cycle before switching.
*   **Opt-In & Access Requirements:** Querying
    `INFORMATION_SCHEMA.TABLE_STORAGE` requires `bigquery.tables.get` and
    `bigquery.tables.list` (`roles/bigquery.metadataViewer`). On
    non-grandfathered projects/orgs, data collection also requires opt-in via
    ``ALTER PROJECT `{project_id}` SET OPTIONS
    (`region-{region}.enable_info_schema_storage` = TRUE)`` (or
    `ALTER ORGANIZATION`), which requires `bigquery.config.update`
    (`roles/bigquery.admin`, not `roles/bigquery.resourceAdmin`). Historical
    data takes ~24 hours to populate post-enablement. For immediate triage
    without waiting for backfill, use `INFORMATION_SCHEMA.PARTITIONS` and
    `INFORMATION_SCHEMA.SCHEMATA_OPTIONS`, which do not require opt-in.
*   **BigLake Managed Storage:** BigLake Apache Iceberg table metadata appears
    in `INFORMATION_SCHEMA.TABLE_STORAGE` with `table_type = 'BASE TABLE'`, but
    actual file storage resides in customer Cloud Storage buckets and is
    excluded from BigQuery billable storage usage. To strictly isolate native
    BigQuery billable storage, filter
    `WHERE managed_table_type IS NULL OR managed_table_type = 'NATIVE'` directly
    on `INFORMATION_SCHEMA.TABLE_STORAGE`.
*   **Monthly Proration & Short Month Effect (February Daily Spikes):** BigQuery
    storage is priced at a fixed monthly rate per GiB. Google Cloud Billing
    calculates daily charges by prorating the monthly rate over the exact number
    of days in that calendar month (`daily_rate = monthly_rate /
    days_in_month`). For constant storage volume, daily billed spend appears
    ~10.7% higher in a 28-day February than in 31-day months. Always inspect
    underlying storage byte volume in `INFORMATION_SCHEMA` before diagnosing an
    apparent daily cost jump.

## 4. Telemetry & Data Retrieval Reference

If the `bigquery-observability` skill is available in your workspace, refer to
its shared telemetry references for canonical query templates and schema
dictionaries. All essential diagnostic workflows, formulas, and remediation
levers are self-contained within this guide.

*   **Table, Storage & Dataset Schemas:** See the `bigquery-observability` skill
    (`references/schema_storage.md`, section "3. Storage Footprint, Partitions &
    Table Metadata Views" and section "4. Datasets, Replication & Sharing
    Views") for `INFORMATION_SCHEMA.TABLE_STORAGE`,
    `INFORMATION_SCHEMA.TABLE_STORAGE_USAGE_TIMELINE`,
    `INFORMATION_SCHEMA.PARTITIONS`, and `INFORMATION_SCHEMA.SCHEMATA_OPTIONS`
    schemas.
*   **Project Option Schemas:** See the `bigquery-observability` skill
    (`references/schema_others.md`, section "10. Project & Organization
    Configuration Views") for `INFORMATION_SCHEMA.EFFECTIVE_PROJECT_OPTIONS`
    field definitions.
performance_config_changed.md 6.1 KB
# BigQuery Troubleshooting: Performance & Configuration Changes

This reference guide provides root-cause mapping and remediation strategies for
performance degradation caused by reservation, commitment, or assignment
changes. Each section connects the observed symptom to potential root causes and
points to the corresponding audit query in `bigquery-observability`.

## Table of Contents

-   [Diagnostic Workflows by Symptom & Root Cause](#diagnostic-workflows-by-symptom-root-cause)
    (Lines 23-105)
    -   [1. Reservation Baseline & Autoscale Modifications](#1-reservation-baseline-autoscale-modifications)
        (Lines 25-45)
    -   [2. Active Capacity Commitment Timeline & Expiration](#2-active-capacity-commitment-timeline-expiration)
        (Lines 47-68)
    -   [3. Reservation Assignment Reconfigurations](#3-reservation-assignment-reconfigurations)
        (Lines 70-86)
    -   [4. Autoscaling Headroom Saturation & Capacity Ceilings](#4-autoscaling-headroom-saturation-capacity-ceilings)
        (Lines 88-105)
-   [Remediation & Recommendations](#remediation-recommendations) (Lines
    107-117)

## Diagnostic Workflows by Symptom & Root Cause

### 1. Reservation Baseline & Autoscale Modifications

-   **When to Use / Symptoms**: Sudden query queueing or slowness starting at a
    specific timestamp, and you suspect an uncoordinated or accidental
    reservation capacity reduction.
-   **Potential Root Causes**: `slot_capacity` lowered, `autoscale.max_slots`
    cap decreased, or reservation idle slot setting changed.
-   **Key Telemetry & Tables**:
    -   **Table**: `INFORMATION_SCHEMA.RESERVATION_CHANGES_BY_PROJECT` (in the
        reservation admin project and region).
    -   **Filters**: `reservation_name = 'RESERVATION_NAME'`,
        `change_timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30
        DAY)`.
    -   **Key Fields**: `change_timestamp`, `action`, `reservation_name`,
        `slot_capacity` (new baseline slots), `autoscale.max_slots` (new
        autoscale cap), `user_email`.
-   **Diagnostic Procedure & Telemetry**: See the `bigquery-observability` skill
    (`references/capacity_and_configuration_queries.md`, section "Auditing
    Reservation & Assignment Configuration Changes", querying
    `RESERVATION_CHANGES_BY_PROJECT`) to audit modification timestamps, new slot
    capacities, and user emails.

### 2. Active Capacity Commitment Timeline & Expiration

-   **When to Use / Symptoms**: Reservation total slot capacity dropped suddenly
    without explicit edits to reservation objects, causing widespread job
    queueing.
-   **Potential Root Causes**: Annual or multi-year capacity commitment expired,
    was deleted, or failed to auto-renew.
-   **Key Telemetry & Tables**:
    -   **Table & CLI**:
        `INFORMATION_SCHEMA.CAPACITY_COMMITMENT_CHANGES_BY_PROJECT` or CLI
        command `bq show --capacity_commitment=true --location={location}
        {commitment_id}`.
    -   **Filters**: `change_timestamp >= TIMESTAMP_SUB(...)`,
        `capacity_commitment_id`.
    -   **Key Fields**: `change_timestamp`, `action`, `slot_count`,
        `commitment_plan` (e.g., `ANNUAL`, `THREE_YEAR`), `renewal_plan`,
        `user_email`.
-   **Diagnostic Procedure & Telemetry**: See the `bigquery-observability` skill
    (`references/capacity_and_configuration_queries.md`, section "Auditing
    Reservation & Assignment Configuration Changes", querying
    `CAPACITY_COMMITMENT_CHANGES_BY_PROJECT`) or inspect active commitments via
    REST CLI (`bq show --capacity_commitment`).

### 3. Reservation Assignment Reconfigurations

-   **When to Use / Symptoms**: Workload in a specific project or folder
    experiences degraded performance after administrative reorganization or
    migration.
-   **Potential Root Causes**: Project assignment moved to a different
    reservation with lower capacity.
-   **Key Telemetry & Tables**:
    -   **Table**: `INFORMATION_SCHEMA.ASSIGNMENT_CHANGES_BY_PROJECT`.
    -   **Filters**: `assignee_id = 'PROJECT_OR_FOLDER_ID'`,
        `change_timestamp >= TIMESTAMP_SUB(...)`.
    -   **Key Fields**: `change_timestamp`, `action`, `assignee_id`, `job_type`,
        `reservation_name`, `user_email`.
-   **Diagnostic Procedure & Telemetry**: See the `bigquery-observability` skill
    (`references/capacity_and_configuration_queries.md`, section "Auditing
    Reservation & Assignment Configuration Changes", querying
    `ASSIGNMENT_CHANGES_BY_PROJECT` filtered by `assignee_id`).

### 4. Autoscaling Headroom Saturation & Capacity Ceilings

-   **When to Use / Symptoms**: Bursty or concurrent queries experience
    unexpected throttling or queueing despite autoscaling being active.
-   **Potential Root Causes**: Workload demand exceeded the configured
    `autoscale.max_slots` ceiling, or slot borrowing was disabled
    (`ignore_idle_slots = TRUE`).
-   **Key Telemetry & Tables**:
    -   **Table**: `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE_BY_PROJECT`.
    -   **Filters**: `period_start >= TIMESTAMP_SUB(...)`, `reservation_name =
        'RESERVATION_NAME'`.
    -   **Key Fields**: `slots_assigned` (baseline slots), `max_slots` (scaling
        cap), `autoscale.current_slots`, `autoscale.max_slots`,
        `per_second_details`, `scaling_mode` (`ALL_SLOTS`, `AUTOSCALE_ONLY`),
        `is_creation_region` (primary vs failover).
-   **Diagnostic Procedure & Telemetry**: See the `bigquery-observability` skill
    (`references/capacity_and_configuration_queries.md`, section "Reservation
    Slot Capacity & Autoscaling Saturation Timeline (1-Second Resolution)").

## Remediation & Recommendations

-   **Restore Autoscale Max Slot Limits**: Increase `autoscale.max_slots` on the
    reservation to accommodate peak bursty query traffic without queueing.
-   **Manage Commitment Auto-Renewal**: Ensure auto-renew is enabled on active
    capacity commitments to prevent unexpected capacity drop-offs.
-   **Isolate Critical Workloads**: Move latency-sensitive production queries to
    a dedicated reservation with guaranteed baseline slots and separate
    autoscale headroom.
-   **Enable Idle Slot Sharing**: Ensure `ignore_idle_slots` is set to `FALSE`
    unless strict multi-tenant isolation is required.
performance_resource_contention.md 11.1 KB
# BigQuery Troubleshooting: Resource Contention & Performance Slowness

This reference guide provides root-cause mapping and remediation strategies for
BigQuery job and workload slowness. Each section connects the observed symptom
to potential root causes and points to the corresponding query in
`bigquery-observability`.

## Table of Contents

-   [Diagnostic Workflows by Symptom & Root Cause](#diagnostic-workflows-by-symptom-root-cause)
    (Lines 29-182)
    -   [1. Single-Job Stage Bottleneck Diagnosis & REST API Triage](#1-single-job-stage-bottleneck-diagnosis-rest-api-triage)
        (Lines 31-64)
    -   [2. Cohort Baseline Comparison (`normalized_literals`)](#2-cohort-baseline-comparison-normalized_literals)
        (Lines 66-84)
    -   [3. Incident Window Discovery & Timeline Degradation](#3-incident-window-discovery-timeline-degradation)
        (Lines 86-104)
    -   [4. Reservation Slot Saturation (1-Second Resolution)](#4-reservation-slot-saturation-1-second-resolution)
        (Lines 106-124)
    -   [5. Target vs. Baseline Timeframe Comparison](#5-target-vs-baseline-timeframe-comparison)
        (Lines 126-145)
    -   [6. Fleet Performance Variance & Outlier Discovery](#6-fleet-performance-variance-outlier-discovery)
        (Lines 147-164)
    -   [7. Table-Level Activity & Lock Contention](#7-table-level-activity-lock-contention)
        (Lines 166-182)
-   [Remediation & Optimization Strategies](#remediation-optimization-strategies)
    (Lines 184-198)

## Diagnostic Workflows by Symptom & Root Cause

### 1. Single-Job Stage Bottleneck Diagnosis & REST API Triage

-   **When to Use / Symptoms**: A specific query is slow or stalled, and you
    need to isolate whether delay occurred in pending queueing or during active
    stage execution.
-   **Potential Root Causes**: Slot starvation during execution stages, join row
    explosions (`records_written >> records_read` from cross joins or non-unique
    keys on both sides of a join), shuffle memory exhaustion
    (`shuffleOutputBytesSpilled`), unpruned input scans, or stage skew.
-   **Key Telemetry & Tables**:
    -   **CLI Triage**: `bq show --location={location} --format=prettyjson -j
        {project_id}:{job_id}` to inspect `statistics.query.timeline` for
        `activeUnits` vs `pendingUnits`, and `statistics.query.queryPlan` for
        stage-level compute and shuffle skew.
    -   **Table**: `INFORMATION_SCHEMA.JOBS_BY_PROJECT` (or
        `JOBS_BY_ORGANIZATION`).
    -   **Filters**: `job_id = 'JOB_ID'`, `project_id = 'PROJECT_ID'`,
        `creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 DAY)`.
    -   **Key Fields**: `total_slot_ms`, `total_bytes_billed`,
        `total_bytes_processed`, `job_stages` (`records_read`,
        `records_written`, `shuffle_output_bytes_spilled`, `slot_ms`,
        `wait_ratio_avg`, `wait_ratio_max`, `wait_ms_avg`, `wait_ms_max`,
        `read_ratio_avg`, `compute_ratio_avg`, `write_ratio_avg`),
        `query_info.performance_insights.stage_performance_standalone_insights`,
        `query_info.resource_warning_details`.
-   **Diagnostic Procedure & Telemetry**: See the `bigquery-observability` skill
    (`references/job_performance_queries.md`, section "REST API Single-Job
    Point-Lookup & Stage Bottlenecks") for fast CLI triage (`bq show -j`), the
    section "Single Job Performance & Stage Bottleneck Flags" for single-job SQL
    bottleneck analysis, and the section "Stage Row Expansion, Shuffle Spill &
    Join Insights" for multi-job `UNNEST(job_stages)` analysis. For
    execution-plan stage diagnosis of join explosions, shuffle spills, and
    partition skew, see
    [query_plan_execution_graph.md](query_plan_execution_graph.md#3-join-explosion-shuffle-spill-partition-skew-diagnosis).

### 2. Cohort Baseline Comparison (`normalized_literals`)

-   **When to Use / Symptoms**: A recurring scheduled query suddenly took 5x-10x
    longer than usual, and you need to compare it against healthy historical
    runs.
-   **Potential Root Causes**: Data volume growth, partition/cluster pruning
    regressions, schema/view definition updates, or multi-tenant system
    contention.
-   **Key Telemetry & Tables**:
    -   **Table**: `INFORMATION_SCHEMA.JOBS_BY_PROJECT`.
    -   **Filters**: `query_info.query_hashes.normalized_literals =
        'TARGET_NORMALIZED_LITERALS'`, `creation_time >=
        TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 14 DAY)`.
    -   **Key Fields**: `start_time`, `end_time`, `total_slot_ms`,
        `total_bytes_processed`, `total_bytes_billed`, `error_result`,
        `query_info.query_hashes.normalized_literals`.
-   **Diagnostic Procedure & Telemetry**: See the `bigquery-observability` skill
    (`references/job_performance_queries.md`, section "Finding Comparable
    Jobs").

### 3. Incident Window Discovery & Timeline Degradation

-   **When to Use / Symptoms**: Multiple users report slowness or queueing
    across a project/reservation, but the exact onset timeframe is unknown.
-   **Potential Root Causes**: Sudden query concurrency surges, batch pipeline
    arrivals, or unannounced capacity changes.
-   **Key Telemetry & Tables**:
    -   **Table**: `INFORMATION_SCHEMA.JOBS_TIMELINE_BY_PROJECT`.
    -   **Filters**: `period_start BETWEEN 'TARGET_START' AND 'TARGET_END'`,
        `job_creation_time BETWEEN TIMESTAMP_SUB('TARGET_START', INTERVAL 2 DAY)
        AND 'TARGET_END'`, `(statement_type != 'SCRIPT' OR statement_type IS
        NULL)`.
    -   **Key Fields**: `window_minute` (`TIMESTAMP_TRUNC(period_start,
        MINUTE)`), `slot_usage` (`ROUND(SUM(period_slot_ms) / 1000.0 / 60.0,
        1)`), `job_concurrency` (`ROUND(COUNT(*) / 60.0, 1)`),
        `project_queue_length` (`ROUND(COUNTIF(state = 'PENDING') / 60.0, 1)`).
-   **Diagnostic Procedure & Telemetry**: See the `bigquery-observability` skill
    (`references/resource_contention_queries.md`, section "Per-Minute Project
    Slot Usage, Concurrency & Queue Timeline").

### 4. Reservation Slot Saturation (1-Second Resolution)

-   **When to Use / Symptoms**: Queries spend excessive time in `PENDING` state
    or experience degraded execution times in a shared reservation.
-   **Potential Root Causes**: Multi-tenant reservation saturation, noisy
    neighbor workloads consuming capacity, or insufficient idle slot borrowing.
-   **Key Telemetry & Tables**:
    -   **Table**: `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE_BY_PROJECT` joined
        with `JOBS_TIMELINE_BY_PROJECT`.
    -   **Filters**: `period_start BETWEEN 'TARGET_START' AND 'TARGET_END'`,
        `admin_project_id = 'ADMIN_PROJECT_ID'`, `reservation_id =
        'RESERVATION_ID'`.
    -   **Key Fields**: `is_autoscale_saturated`,
        `pct_time_autoscale_saturated`, `avg_baseline_slots`,
        `avg_autoscale_slots`, `avg_total_max_capacity`,
        `avg_borrowed_idle_slots`.
-   **Diagnostic Procedure & Telemetry**: See the `bigquery-observability` skill
    (`references/resource_contention_queries.md`, section "Reservation Maximum
    Utilization & Slot Saturation Timeline (1-Second Resolution)").

### 5. Target vs. Baseline Timeframe Comparison

-   **When to Use / Symptoms**: Systematic performance degradation across an
    entire reservation during a known incident window.
-   **Potential Root Causes**: Macro-level compute demand growth, fleet-wide
    data increases, or reduced idle slot availability from neighboring
    reservations.
-   **Key Telemetry & Tables**:
    -   **Table**: `INFORMATION_SCHEMA.JOBS_TIMELINE_BY_PROJECT`.
    -   **Parameters**: Compare Target timeframe (`TARGET_START` to
        `TARGET_END`) against Baseline timeframe (`BASELINE_START` to
        `BASELINE_END`, e.g., same hours on prior day or prior week).
    -   **Key Metrics**: Compare aggregated `total_slot_ms`,
        `total_bytes_processed`, `job_concurrency`, and `queue_length`.
-   **Diagnostic Procedure & Telemetry**: Compare total compute consumed, data
    volume scanned, and job counts between the degraded Target timeframe and a
    healthy Baseline timeframe (e.g., same hours on the prior day or week) using
    the query in the `bigquery-observability` skill
    (`references/resource_contention_queries.md`, section "Per-Minute Project
    Slot Usage, Concurrency & Queue Timeline").

### 6. Fleet Performance Variance & Outlier Discovery

-   **When to Use / Symptoms**: Need to identify which specific queries
    experienced the highest relative slowdown or locate high-slot "bully"
    queries.
-   **Potential Root Causes**: Unoptimized ad-hoc queries consuming unfair slot
    shares, or queries with high data skew.
-   **Key Telemetry & Tables**:
    -   **Table**: `INFORMATION_SCHEMA.JOBS_BY_PROJECT`.
    -   **Filters**: `creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(),
        INTERVAL 1 DAY)`, `(statement_type != 'SCRIPT' OR statement_type IS
        NULL)`.
    -   **Key Fields**: Grouped by `query_info.query_hashes.normalized_literals`
        to compute `job_count`, `avg_duration_ms`, `p90_duration_ms`,
        `stddev_duration_ms`, `max_duration_ms`, `avg_slot_ms`, `max_slot_ms`.
-   **Diagnostic Procedure & Telemetry**: See the `bigquery-observability` skill
    (`references/job_performance_queries.md`, section "Query Performance
    Variance & Outlier Discovery").

### 7. Table-Level Activity & Lock Contention

-   **When to Use / Symptoms**: Queries accessing a specific table or dataset
    stop responding, queue, or run slowly.
-   **Potential Root Causes**: Concurrent DML/DDL write lock serialization,
    frequent partition modifications, or read amplification.
-   **Key Telemetry & Tables**:
    -   **Table**: `INFORMATION_SCHEMA.JOBS_BY_PROJECT`.
    -   **Filters**: `destination_table.table_id = 'TARGET_TABLE'` OR `EXISTS
        (SELECT 1 FROM UNNEST(referenced_tables) rt WHERE rt.table_id =
        'TARGET_TABLE')`, `state IN ('RUNNING', 'PENDING')`.
    -   **Key Fields**: `job_id`, `statement_type` (`MERGE`, `UPDATE`, `INSERT`,
        `DELETE`), `start_time`, `state`, `user_email`, `query`.
-   **Diagnostic Procedure & Telemetry**: Filter `JOBS_BY_PROJECT` on
    `referenced_tables` or `destination_table` (following best practices in the
    `bigquery-observability` skill) to inspect concurrent write operations
    (`MERGE`, `UPDATE`, `INSERT`) competing for table locks.

## Remediation & Optimization Strategies

-   **Slot Contention & Saturation**: Increase `autoscale.max_slots` on the
    reservation, configure reservation priority, or isolate heavy batch queries
    into a dedicated reservation.
-   **Stage Bottlenecks & Shuffle Spill**: Check join conditions to avoid
    unintentional `CROSS JOIN`s or non-unique keys on both sides of a join, use
    a `GROUP BY` clause to pre-aggregate join inputs before joining, optimize
    join ordering (broadcast smaller tables with `HASH` joins), partition or
    cluster large tables to prune shuffle volume, and eliminate unneeded columns
    (see
    [query_plan_execution_graph.md](query_plan_execution_graph.md#3-join-explosion-shuffle-spill-partition-skew-diagnosis)).
-   **Queueing / Pending Slowness**: Increase reservation baseline capacity,
    adjust target job concurrency, or stagger scheduled query start times to
    avoid top-of-the-hour arrival spikes.
query_plan_execution_graph.md 10.4 KB
# BigQuery Troubleshooting: Execution Graph & Query Plan

This reference guide provides diagnostic workflows and grounding concepts for
investigating single-job performance bottlenecks, execution graphs, stage-level
operations, and query plan metrics in BigQuery.

## Table of Contents

-   [Diagnostic Workflows](#diagnostic-workflows) (Lines 21-112)
    -   [1. Single-Job Stage Bottleneck Triage & REST API Lookup](#1-single-job-stage-bottleneck-triage-rest-api-lookup)
        (Lines 23-43)
    -   [2. General Telemetry & Stage Metrics Cross-Reference](#2-general-telemetry-stage-metrics-cross-reference)
        (Lines 45-54)
    -   [3. Join Explosion, Shuffle Spill & Partition Skew Diagnosis](#3-join-explosion-shuffle-spill-partition-skew-diagnosis)
        (Lines 56-112)
-   [Execution Graph & UI Grounding Concepts](#execution-graph-ui-grounding-concepts)
    (Lines 114-160)
-   [Strict Disambiguation Invariants](#strict-disambiguation-invariants) (Lines
    162-183)

## Diagnostic Workflows

### 1. Single-Job Stage Bottleneck Triage & REST API Lookup

-   **When to Use / Symptoms**: A query is slow or stalled, and you need to
    isolate whether delay occurred during pending/queueing or within a specific
    execution stage.
-   **Diagnostic Procedure**:
    -   Use the REST API single-job point-lookup via `bq show
        --location={location} --format=prettyjson -j {project_id}:{job_id}` to
        retrieve detailed per-stage execution metrics, timeline events, and
        performance insights. See the `bigquery-observability` skill
        (`references/job_performance_queries.md`, section "REST API Single-Job
        Point-Lookup & Stage Bottlenecks") for the CLI command and field
        definitions.
    -   Inspect `statistics.query.queryPlan` for stage-level compute, input,
        output, and shuffle skew.
    -   **Bottleneck Determination**: Calculate stage duration as `duration =
        end_ms - start_ms`.
    -   **Optimization Target**: Clarify whether the user is optimizing for
        **Slot Time** (Reservations / Flat-rate / Editions) or **Bytes
        Processed** (On-demand pricing) to prioritize the corresponding
        bottleneck stages.

### 2. General Telemetry & Stage Metrics Cross-Reference

For full SQL schema dictionaries, physical units, and column definitions (such
as `records_read`, `records_written`, `shuffle_output_bytes_spilled`, and
`slot_ms` across `job_stages` and `INFORMATION_SCHEMA.JOBS`), see the
`bigquery-observability` skill:

-   `references/schema_compute.md` for raw telemetry metrics and column types.
-   `references/job_performance_queries.md` for SQL-based stage bottleneck
    analysis and historical baseline comparisons.

### 3. Join Explosion, Shuffle Spill & Partition Skew Diagnosis

-   **When to Use / Symptoms**: A query consumes excessive slot-hours, runs out
    of shuffle resources, or stalls in a `Join` or `Aggregate` stage due to
    unintentional `CROSS JOIN`s, missing or non-selective `ON` conditions,
    many-to-many row multiplication (`records_written >> records_read`), disk
    spill (`shuffle_output_bytes_spilled > 0`), or worker skew.
-   **Diagnostic Procedure**:
    -   Unnest `job_stages` and
        `query_info.performance_insights.stage_performance_standalone_insights`
        in `INFORMATION_SCHEMA.JOBS_BY_PROJECT` (see the
        `bigquery-observability` skill, `references/job_performance_queries.md`,
        section "Stage Row Expansion, Shuffle Spill & Join Insights") or inspect
        `statistics.query.queryPlan` and `statistics.query.performanceInsights`
        via `bq show --location={location} --format=prettyjson -j
        {project_id}:{job_id}`.
    -   **Row Expansion Check (`records_written` vs. `records_read`)**: Compare
        `stage.records_written` to `stage.records_read`
        (`SAFE_DIVIDE(stage.records_written, NULLIF(stage.records_read, 0))`)
        and inspect `insight.high_cardinality_joins` (`left_rows`, `right_rows`,
        `output_rows`, `step_index`) to identify stages where output rows
        drastically exceed input rows.
    -   **Join Condition & `CROSS JOIN` Check**: Inspect the query's `JOIN`
        conditions and the `JOIN` step details in the query plan (join pattern
        and join columns) for unintentional `CROSS JOIN`s (or comma cross
        joins), missing `ON` conditions, or non-selective/non-unique join keys
        on both sides of the join. Confirm a Cartesian product by counting rows
        per join key (`GROUP BY` the join key) on each side of the `JOIN`.
    -   **Shuffle Spill & Quota Check**: Check `stage.shuffle_output_bytes`,
        `stage.shuffle_output_bytes_spilled > 0`, and
        `insight.insufficient_shuffle_quota = TRUE` to identify stages spilling
        intermediate data to disk or starving for shuffle quota.
    -   **Wait vs. Skew Check**: Compare `stage.wait_ratio_avg` (`wait_ms_avg`)
        and `stage.wait_ratio_max` (`wait_ms_max`)—and check whether
        `wait_ms_max >> compute_ms_max` (`waitMsMax >> computeMsMax` in
        `queryPlan`)—to detect worker slot starvation and shard scheduling wait
        (`insight.slot_contention = TRUE`), and compare
        `stage.compute_ratio_max` (`compute_ms_max` / `computeMsMax`) against
        `stage.compute_ratio_avg` (`compute_ms_avg` / `computeMsAvg`) alongside
        `insight.partition_skew.skew_sources` (`stage_id`) to isolate hot keys
        overloading a single worker shard.
-   **Remediation & Actions**:
    -   **Eliminate Unintentional `CROSS JOIN`s & Use Selective Join Keys**:
        Ensure every `JOIN` specifies explicit `ON` conditions using selective
        join keys rather than an unintentional `CROSS JOIN` (or replace cross
        joins and self-joins with window functions where applicable).
    -   **Pre-Aggregate Join Inputs Before Joining**: Use a `GROUP BY` clause in
        a CTE to pre-aggregate data on the join key before the `JOIN` (or
        deduplicate non-unique keys) so non-unique keys on both sides do not
        multiply rows, and filter out `NULL` or skewed dummy keys (e.g., `WHERE
        customer_id IS NOT NULL AND customer_id != 'GUEST'`) before joining.
    -   **Filter Early & Order Joins Largest-First**: Push selective `WHERE`
        filters into each table before the `JOIN`, and place the largest table
        first (leftmost) and the smallest table second (rightmost) so BigQuery
        broadcasts the small table (`JOIN EACH WITH ALL`) instead of shuffling
        both inputs (`JOIN EACH WITH EACH`). For SQL rewrite patterns, refer to
        the `bigquery-optimization` skill.

## Execution Graph & UI Grounding Concepts

Base all terminology explanations and console visualization guidance on the
official definitions below:

-   **execution graph**: The visual representation of the query plan stages and
    steps in the BigQuery Console (see the
    [execution graph documentation][execution-graph-docs]).
-   **query plan**: The series of stages and steps BigQuery generates and
    executes to run a query (see the
    [query plan explanation documentation][query-plan-docs]).
-   **stage**: A single execution unit in a query plan containing multiple
    operations/steps executed by worker slots (see the
    [stage overview documentation][stage-overview-docs]).
-   **step**: An individual operation within a stage (such as `READ`, `WRITE`,
    `AGGREGATE`, `JOIN`, or `FILTER`; see the
    [per-stage step information documentation][step-info-docs]).
-   **substep / substep variables**: Intermediate sub-operations within a stage
    step passing data via intermediate variables (such as `$1`, `$2`). These
    variables are unique to that stage and pass expressions or intermediate
    aggregations between operations (see the
    [per-stage step information documentation][step-info-docs]).
-   **slowest stage / bottleneck**: The stage causing the highest latency or
    consuming the largest share of slot resources. Calculate duration as
    `end_ms - start_ms` (see the
    [stage overview documentation][stage-overview-docs]).
-   **summary panel**: Top-level summary panel in BigQuery Console displaying
    overall job duration, bytes processed, and slot usage (see the
    [query plan explanation documentation][query-plan-docs]).
-   **stage details panel**: Side panel in BigQuery Console displaying granular
    stage metrics, worker compute/wait breakdown, and operations (see the
    [execution graph navigation documentation][navigating-graph-docs]).
-   **input stage**: The predecessor stage that provides input data to the
    current stage (see the
    [execution graph documentation][execution-graph-docs]).
-   **output stage**: The successor stage that consumes data produced by the
    current stage (see the
    [execution graph documentation][execution-graph-docs]).
-   **parallel inputs**: The number of workers concurrently processing input
    partitions within a stage (see the
    [stage overview documentation][stage-overview-docs]).
-   **completed parallel inputs**: The number of worker tasks that have finished
    execution within a stage (see the
    [stage overview documentation][stage-overview-docs]).
-   **cache hit**: Indicates whether the query result was served from BigQuery
    cached results (0 bytes billed; see the
    [query plan explanation documentation][query-plan-docs]).

## Strict Disambiguation Invariants

-   **Mandatory Correction (Bytes Scanned in Stage)**: BigQuery **does NOT**
    track *Bytes Scanned* per individual stage. When asked, issue the
    correction:

    > ⚠️ **Correction**: BigQuery does not track *Bytes Scanned* per individual
    > stage. Instead, it tracks **Records Read** (the volume of input rows
    > processed by the stage).

-   **Substep Variables (`$1`, `$2`)**: When asked why steps contain `$` signs,
    clarify that these represent intermediate **substep variables** unique to
    that stage passing data between operations.

-   **Citation Requirement**: Always cite the official documentation link for
    every execution graph concept or metric discussed.

[execution-graph-docs]: https://cloud.google.com/bigquery/docs/query-plan-explanation#understand_the_execution_graph
[navigating-graph-docs]: https://cloud.google.com/bigquery/docs/query-plan-explanation#navigating_the_execution_graph
[query-plan-docs]: https://cloud.google.com/bigquery/docs/query-plan-explanation
[stage-overview-docs]: https://cloud.google.com/bigquery/docs/query-plan-explanation#stage-overview
[step-info-docs]: https://cloud.google.com/bigquery/docs/query-plan-explanation#per-stage_step_information

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE