Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install cloud-monitoring-alert-configuration@skills-hub

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

Install with the gh extension
gh skills-hub install cloud-monitoring-alert-configuration

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

Download and extract to your repository:

.github/skills/cloud-monitoring-alert-configuration/

Extract the ZIP to .github/skills/ in your repo. The folder name must match cloud-monitoring-alert-configuration for Copilot to auto-discover it.

Skill Files (41)

SKILL.md 11.0 KB
---
name: cloud-monitoring-alert-configuration
metadata:
  version: "1.0.4"
  category: CloudObservabilityAndMonitoring
  support_tier: team
  tags: "cloud-monitoring, alerting, terraform, promql, observability"
  comment: >-
    Consolidated from Cloud Monitoring alerting policy best practices across
    Cloud Run, Google Kubernetes Engine, Compute Engine, and Vertex AI Agent
    Engine.
  canonical_source: https://docs.cloud.google.com/monitoring/alerts.md.txt
description: >-
  Configures Cloud Monitoring alerting policies using Terraform and
  PromQL across Cloud Run, Google Kubernetes Engine (GKE), Compute Engine, AI
  Hypercomputer reservations, Vertex AI Agent Engine, and generic Google Cloud
  resources. Use when creating, reviewing, migrating, or deduplicating Terraform
  alerting policies for latency, traffic, error rates, saturation, host or
  reservation maintenance, GPU XID insights, or AI agent telemetry. Don't use
  for standalone PromQL query authoring without alerting, log querying, or
  billing cost audits.
---

# Configure Cloud Monitoring Alerts

Configure high-signal alerting policies in Cloud Monitoring using
Terraform (`google_monitoring_alert_policy`) and PromQL
(`condition_prometheus_query_language`).

## Usage Attribution

For all `gcloud` CLI, REST API, and MCP attribution requirements when executing
commands with this skill, follow the instructions in
[Usage Attribution](references/attribution.md).

## Enforce Core Alerting Rules

1.  **Apply the Four Golden Signals**: Cover latency, traffic, errors, and
    saturation for the target workload.
2.  **Use Dynamic Grouping**: Aggregate metrics by resource labels and
    parameterize thresholds with Terraform variables. Never hardcode ephemeral
    pod or instance identifiers.
3.  **Default to PromQL**: Use Prometheus Query Language (PromQL) for metric
    conditions, and use log-based alerts
    (`condition_matched_log` or `google_logging_metric`) for lifecycle and
    audit events.
4.  **Attach Skill Attribution Labels**: Always include `user_labels` with
    `created-with-google-skill = "cloud-monitoring-alert-configuration"` on
    every generated `google_monitoring_alert_policy` resource.
5.  **Require User Confirmation Before Mutating Resources**: Never execute
    commands that modify infrastructure, enable telemetry, create online
    monitors, or apply Terraform without waiting for explicit user confirmation.
6.  **Prompt for Notification Channels**: Alerting policies without notification
    channels incur charges without notifying anyone during an incident. Whenever
    notification channels are not specified in the user prompt across any
    workflow, explicitly inform the user that no notification channels are
    attached to the alerting policies, advise them to configure and attach
    notification channels before deploying, and ask at the end of your response
    if they want to configure notification channels.

## Route by Target Resource Type

Identify the target resource type and read only the matching reference file
directly. Never run directory listings or workspace file searches to look for
queries or `.tf` files unless the prompt
explicitly provides a file path. If a user asks to fix or validate a PromQL
query without providing the query text or a file path, construct a
representative broken-and-corrected query example directly.

### Configure Cloud Run Alerts

*   **HTTP Services**:
    [cloud_run_services.md](references/cloud_run_services.md)
*   **Batch Jobs**:
    [cloud_run_jobs.md](references/cloud_run_jobs.md)
*   **Worker Pools**:
    [cloud_run_worker_pools.md](references/cloud_run_worker_pools.md)

### Configure Google Kubernetes Engine Alerts

*   **PromQL Queries and Golden Signals**:
    [GKE PromQL Queries](references/kubernetes_promql_queries.md)
*   **Metrics Catalog and Open-Source Alerts**:
    [GKE Metrics](references/kubernetes_metrics_and_alerts_catalog.md)
*   **Prerequisites and Setup**:
    [GKE Setup](references/kubernetes_gke_configuration_prerequisites.md)

### Configure AI Agent Alerts

*   **Reliability**:
    [Reliability](references/agent_platform_reliability_alert_policies.md)
*   **Quality**:
    [Quality](references/agent_platform_quality_alert_policies.md)
*   **Cost**:
    [Cost](references/agent_platform_cost_alert_policies.md)
*   **Safety**:
    [Safety](references/agent_platform_safety_alert_policies.md)
*   **Security**:
    [Security](references/agent_platform_security_alert_policies.md)
*   **Telemetry Enablement**:
    [Telemetry](references/agent_platform_telemetry_enablement.md)
*   **Traffic Profiles**:
    [Historical](references/agent_platform_has_historical_traffic_data.md)
    and
    [No History](references/agent_platform_no_historical_traffic_data.md)

### Configure Compute Engine and AI Hypercomputer Alerts

*   **Compute Engine VMs, MIGs, GPU XID Insights, Host or Reservation
    Maintenance (`type=scheduled`, `unscheduled`, or `multiple`), and Machine
    or Domain Health**:
    [compute_engine_alerts.md](references/compute_engine_alerts.md)

### Configure Generic Resource Alerts

*   **Generic Workloads, Custom Metrics, MQL Migration, and HCL Deduplication**:
    [generic_alert_policies.md](references/generic_alert_policies.md)

### Delegate Service Level Objective Alerts

**Delegate to the `google-cloud-slo-alert-configuration` skill.** That skill
owns the SLO setup wizard, the burn-rate PromQL templates
(`references/promql_templates.md`), the SLI metric mapping
(`references/service_metrics.md`), and the App Hub scoping labels
(`references/app_hub_labels.md`). Do **NOT** duplicate those templates here or
claim that this skill owns its own SLO PromQL template library.

Delegate whenever the user asks for an **availability or latency SLO**, an
**error budget or burn-rate alert**, or a **Service Level Objective** on any
resource. When SLOs are only one part of a broader request (for example, a full
production alerting suite for a Cloud Run service), delegate the SLO policies
and continue generating the remaining golden-signal policies from the
resource-specific reference in the same response.

Every resource reference carries a **Context to hand off** list naming the SLI
metric, its good or bad filter, and the grouping labels — under a `## Delegate
Service Level Objective Alerts` heading for Cloud Run and generic resources, and
inside the SLO section itself for GKE and Agent Platform. Read it and pass that
context on, so the SLO skill does not repeat discovery you have already done.
When delegating, you MUST also:

1.  State the SLO target and window explicitly if the user gave them, or let the
    SLO skill apply its SRE defaults (99.9% over a rolling 28 days) if they did
    not.
2.  Require the returned policies to carry `user_labels` with
    `created-with-google-skill = "cloud-monitoring-alert-configuration"` so
    attribution stays consistent with the rest of the generated suite. This
    literal value does **NOT** change when you delegate: the label records the
    entry-point skill, not whichever skill supplied the template. Do **NOT**
    set `created-with-google-skill = "google-cloud-slo-alert-configuration"` on
    policies generated through this delegation.
3.  Preserve the burn-rate duration contract, which
    `google-cloud-slo-alert-configuration` does not specify: Fast Burn (`1h` and
    `5m` windows, factor `14.4`) carries `duration = "300s"`, and Slow Burn
    (`[3d]` and `[6h]` lookback, factor `1.0`) **omits the `duration` field
    entirely** — do not emit `duration = "0s"` in its place. Cloud Monitoring
    rejects a non-zero retest buffer when the lookback window exceeds 25 hours.
4.  When no notification channels are provided, inform the user that no
    notification channels are attached to the alerting policies, advise them to
    configure and attach notification channels, and ask if they want to
    configure notification channels.

> [!IMPORTANT]
> **Always tell the user about the referral, even on the fallback path.** Some
> reference files in this skill include standalone burn-rate templates to use
> when the `google-cloud-slo-alert-configuration` skill is not installed. If you
> emit policies from those fallback templates, your response MUST still tell the
> user that `google-cloud-slo-alert-configuration` owns SLO configuration, state
> that the emitted policies use the local fallback templates, and list the
> handoff context. Never silently present SLO policies as if this
> skill owned them.

> [!NOTE]
> **Exception**: Agent Platform (OpenTelemetry-instrumented AI agents on any
> runtime, including Vertex AI Agent Engine and Cloud Run) is the one resource
> whose Fast and Slow burn policies live in this skill and remain authoritative.
> Delegate only for SLO customization — see
> [Reliability](references/agent_platform_reliability_alert_policies.md).

## Delegate Related Observability Tasks

*   **Notification Channels**: Delegate to
    `cloud-monitoring-notification-channels-configuration` to configure email,
    PagerDuty, Pub/Sub, or Slack channels. When an alerting policy has no
    notification channels attached, inform the user that no notification
    channels are attached and that they should configure notification channels
    and attach them to the alerting policy.
*   **PromQL Authoring**: Delegate to `cloud-monitoring-promql-query` for
    standalone PromQL query authoring or metric exploration.

## Follow the Alert Configuration Workflow

1.  **Discover**: Identify target resources, metric schemas, and scoping
    projects using the lookup commands in the matching reference file (such as
    [discover_metric_schema.py](scripts/discover_metric_schema.py) for Compute
    Engine metrics and other Google Cloud resource metrics, or
    [gather_agent_info.py](scripts/agent_platform/gather_agent_info.py),
    [check_telemetry.py](scripts/agent_platform/check_telemetry.py),
    [analyze_traffic.py](scripts/agent_platform/analyze_traffic.py),
    [create_online_monitor.py](scripts/agent_platform/create_online_monitor.py),
    [list_trace_scope_table_names.py](scripts/agent_platform/list_trace_scope_table_names.py),
    and
    [list_log_scope_table_names.py](scripts/agent_platform/list_log_scope_table_names.py)
    for AI agents).
2.  **Route**: Load the reference file for the target resource type or delegate
    SLOs to `google-cloud-slo-alert-configuration`.
3.  **Generate**: Produce parameterized Terraform HCL configurations with
    required `user_labels`.
4.  **Validate**: When the loaded reference file requires a validation script
    (such as [lint_promql.py](scripts/lint_promql.py),
    [validate_config.py](scripts/kubernetes/validate_config.py),
    [lint_syntax.py](scripts/agent_platform/lint_syntax.py), or
    [scan_duplicates.py](scripts/agent_platform/scan_duplicates.py)), run or
    print that exact script command. Do not list or search the `scripts/`
    directory.
5.  **Explain and Prompt**: Explain each alert policy in plain English. When no
    notification channels are provided, tell the user that no notification
    channels are attached to the alerting policy, advise them to configure and
    attach notification channels, and ask if they want to configure notification
    channels.
references/
agent_platform_cost_alert_policies.md 9.7 KB
# Configure Cost Alert Policies

These alert policies help alert users when their agents use an unusually high
rate of tokens based on historical metrics.

## Table of Contents

-   [Verify Preconditions](#verify-preconditions): Lines 16-49
    -   [Resolve the Token Usage Workload Pattern](#resolve-the-token-usage-workload-pattern): Lines 18-49
-   [Follow Critical Rules](#follow-critical-rules): Lines 50-77
    -   [Review Telemetry Metrics](#review-telemetry-metrics): Lines 72-77
-   [Configure Policy Specifications](#configure-policy-specifications): Lines 78-211
    -   [Configure Rapid Token Burn Rate](#configure-rapid-token-burn-rate): Lines 80-211
-   [Validate and Finalize](#validate-and-finalize): Lines 212-217

## Verify Preconditions

### Resolve the Token Usage Workload Pattern

Resolve the workload token usage pattern (Seasonal / Cyclical, Steady /
Consistent, or Bursty / Inconsistent) to configure policies monitoring token
usage. If you have not done so already, you MUST run the `check_telemetry` tool
with the flag `--query-monitoring-metadata` enabled to retrieve all namespaces
available for the token usage metric and match the closest one to the target
agent:

```bash
python3 scripts/agent_platform/check_telemetry.py \
  --project-id={gcp_project} \
  --location={location} \
  --agent-resource-name "projects/{project_id}/locations/{location}/reasoningEngines/{agent_id}" \
  --query-monitoring-metadata
```

*   If the user provides a namespace to use in their prompt, you DO NOT need to
    run this tool to retrieve existing namespaces.
*   If the tool does not return a relevant namespace entry, historical metric
    data is not available for this agent.

Follow the instructions corresponding to the availability of historical metrics
data:

*   **Case 1: No historical metrics data available (for example, brand new agent) or no
    monitoring namespaces found**: You MUST read and follow:
    [agent_platform_no_historical_traffic_data.md](agent_platform_no_historical_traffic_data.md)
*   **Case 2: Historical metrics data available (for example, active agent with
    traffic)**: You MUST read and follow:
    [agent_platform_has_historical_traffic_data.md](agent_platform_has_historical_traffic_data.md)

## Follow Critical Rules

*   **Brand New Agents (No Token Usage History)**: When setting up alerts for a
    brand new agent, you MUST explicitly ask the user what token usage pattern
    they expect (Steady / Consistent, Seasonal / Cyclical, or Bursty /
    Inconsistent) in your response. If immediate setup is requested, ask the
    question but proceed using the default Steady/Consistent (`Short-Window
    Z-Score (1h baseline)`) pattern. Follow
    [agent_platform_no_historical_traffic_data.md](agent_platform_no_historical_traffic_data.md).
*   **Alert policy configuration**: You MUST configure the following Cost
    alerting policy. See [Review Telemetry Metrics](#review-telemetry-metrics)
    for the required metrics and descriptions for each signal:
    1.  **Rapid Token Burn Rate** (5-Minute window)
*   **PromQL format**: Configure all Cost alert policies using a PromQL query.
    Do **NOT** use any other language such as Monitoring Query Language (MQL).
    See [Select Telemetry Queries](#select-telemetry-queries) below for the
    queries to use for each signal. Proceed to the **Validate and Finalize**
    section below.
    *   **Disclaimer**: Group by the appropriate field for the underlying
        monitored resource; for example, `generic_node` uses `namespace`. The
        examples below assume `generic_node`.

### Review Telemetry Metrics

| Signal | Raw Metric | Type | Description |
| :--- | :--- | :--- | :--- |
| **Rapid Token Burn Rate** | `gen_ai.client.token.usage` | Counter | Amount of tokens used by the agent. |

## Configure Policy Specifications

### Configure Rapid Token Burn Rate

#### Select Telemetry Queries

##### Configure Z-Score for Steady Traffic

**Long-Window Z-Score (`1w Z-Score Baseline`, for established agents with more than 1 week of history)**

Compares the 5-minute 95th percentile token usage to the 1-week baseline.

*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_NAME_SHORT`: "long_window_zscore"
*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_NAME_LONG`: "Long-Window Z-Score"
*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_CONDITION_DESCRIPTION`: "Rapid Token Burn
    Rate Long-Window Z-Score > 3"

```promql
abs(
  histogram_quantile(0.95,sum by ("namespace","le")(increase({"__name__"="workload_googleapis_com:gen_ai_client_token_usage_bucket","monitored_resource"="generic_node"}[5m])))
  -
  histogram_quantile(0.95,sum by ("namespace","le")(increase({"__name__"="workload_googleapis_com:gen_ai_client_token_usage_bucket","monitored_resource"="generic_node"}[1w])))
)
/
stddev_over_time(
  (histogram_quantile(0.95,sum by ("namespace","le")(increase({"__name__"="workload_googleapis_com:gen_ai_client_token_usage_bucket","monitored_resource"="generic_node"}[5m]))))[1w:5m]
) > 3
```

**Short-Window Z-Score (`Short-Window Z-Score (1h baseline)`, for newer agents with more than 1 hour of history)**

Compares the 1-minute 95th percentile token usage to the 1-hour baseline for
rapid activation on new agents.

*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_NAME_SHORT`: "short_window_zscore"
*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_NAME_LONG`: "Short-Window Z-Score"
*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_CONDITION_DESCRIPTION`: "Rapid Token Burn
    Rate Short-Window Z-Score > 3"

```promql
abs(
  histogram_quantile(0.95,sum by ("namespace","le")(increase({"__name__"="workload_googleapis_com:gen_ai_client_token_usage_bucket","monitored_resource"="generic_node"}[1m])))
  -
  histogram_quantile(0.95,sum by ("namespace","le")(increase({"__name__"="workload_googleapis_com:gen_ai_client_token_usage_bucket","monitored_resource"="generic_node"}[1h])))
)
/
stddev_over_time(
  (histogram_quantile(0.95,sum by ("namespace","le")(increase({"__name__"="workload_googleapis_com:gen_ai_client_token_usage_bucket","monitored_resource"="generic_node"}[1m]))))[1h:1m]
) > 3
```

##### Configure Moving Averages for Bursty Traffic

Compares the 5-minute token usage to the 1-hour `Moving Averages` baseline.

*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_NAME_SHORT`: "moving_average"
*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_NAME_LONG`: "Moving Average"
*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_CONDITION_DESCRIPTION`: "Rapid Token Burn
    Rate 5m window > 1h avg"

```promql
histogram_quantile(0.95,sum by ("namespace","le")(increase({"__name__"="workload_googleapis_com:gen_ai_client_token_usage_bucket","monitored_resource"="generic_node"}[5m])))
>
1.5 * histogram_quantile(0.95,sum by ("namespace","le")(increase({"__name__"="workload_googleapis_com:gen_ai_client_token_usage_bucket","monitored_resource"="generic_node"}[1h])))
```

##### Configure Seasonal Decomposition for Cyclical Traffic

> [!NOTE]
> ONLY use seasonal decomposition (`Seasonal Decomposition (average 1w and 1d)`)
> to track token usage spikes. Alert policies using seasonal decomposition to
> track both spikes and drops can falsely trigger alerts.

Compares the 5-minute token usage to the average of 1-week and 1-day lookback
baselines.

> [!CAUTION]
> The numerator (current token usage) MUST NOT have any offset. Offsets
> (`offset 1d`, `offset 1w`) MUST only be applied to the denominator to
> construct the historical baseline for comparison. Never apply an offset to the
> first numerator.

*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_NAME_SHORT`: "seasonal_decomposition"
*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_NAME_LONG`: "Seasonal Decomposition"
*   `RAPID_TOKEN_BURN_RATE_ALGORITHM_CONDITION_DESCRIPTION`: "Seasonal
    Decomposition > 2"

```promql
histogram_quantile(0.95,sum by ("namespace","le")(increase({"__name__"="workload_googleapis_com:gen_ai_client_token_usage_bucket","monitored_resource"="generic_node"}[5m])))
/
(
  (
    histogram_quantile(0.95,sum by ("namespace","le")(increase({"__name__"="workload_googleapis_com:gen_ai_client_token_usage_bucket","monitored_resource"="generic_node"}[5m] offset 1d)))
    +
    histogram_quantile(0.95,sum by ("namespace","le")(increase({"__name__"="workload_googleapis_com:gen_ai_client_token_usage_bucket","monitored_resource"="generic_node"}[5m] offset 1w)))
  ) / 2
)
> 2
```

#### Define Terraform HCL

```terraform
resource "google_monitoring_alert_policy" "rapid_token_burn_rate_{rapid_token_burn_rate_algorithm_name_short}" {
  project      = var.project_id
  display_name = "Agent Cost - Rapid Token Burn Rate {rapid_token_burn_rate_algorithm_name_long}"
  combiner     = "OR"

  conditions {
    display_name = "{rapid_token_burn_rate_algorithm_condition_description}"
    condition_prometheus_query_language {
      # Using __name__ for metric with special characters.
      query    = {rapid_token_burn_rate_telemetry_query}
      duration = "300s" # 5m buffer
    }
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-alert-configuration"
  }
}
```

Where:

*   `{rapid_token_burn_rate_algorithm_name_short}`: The short name version of
    the algorithm chosen in [Select Telemetry Queries](#select-telemetry-queries).
*   `{rapid_token_burn_rate_algorithm_name_long}`: The long name version of the
    algorithm chosen in [Select Telemetry Queries](#select-telemetry-queries).
*   `{rapid_token_burn_rate_algorithm_condition_description}`: A description for
    the alert condition chosen in [Select Telemetry Queries](#select-telemetry-queries).
*   `{rapid_token_burn_rate_telemetry_query}`: The PromQL alert query chosen and
    configured in [Select Telemetry Queries](#select-telemetry-queries).

## Validate and Finalize

*   **Handle Script Failures**: If `check_telemetry.py` fails unexpectedly,
    verify the parameters (project ID, location, and agent resource name).
    Ensure you have permissions to view Cloud Monitoring metrics and Vertex AI
    Reasoning Engines.
agent_platform_has_historical_traffic_data.md 5.8 KB
# Analyze Historical Traffic Data

Follow these instructions when the agent has historical metrics data available.

## Table of Contents

-   [Follow Critical Instructions](#follow-critical-instructions): Lines 13-89
    -   [Run the Traffic Analyzer Script](#run-the-traffic-analyzer-script): Lines 15-57
    -   [Map Metrics to Algorithms](#map-metrics-to-algorithms): Lines 58-89
-   [Notify the User](#notify-the-user): Lines 90-106
-   [Avoid Common Pitfalls](#avoid-common-pitfalls): Lines 107-112

## Follow Critical Instructions

### Run the Traffic Analyzer Script

-   Run the `analyze_traffic.py` script to classify the metrics traffic pattern
    profile:

    -   **Gather arguments**: Use different arguments in your call depending on
        the target policy you are running the tool for:
        -   **Latency**: Use
            `workload.googleapis.com/gen_ai.invoke_agent.duration` as the
            `--metric-type` and assign the value of the agent's
            `metric.labels.gen_ai_agent_name` as the
            `--reasoning-engine-id`.
        -   **Rapid Token Burn Rate**: Use
            `workload.googleapis.com/gen_ai.client.token.usage` as the
            `--metric-type` and assign the value of the agent's
            `resource.labels.namespace` as the `--reasoning-engine-id`.
    -   **Running the tool**: Use one of the following commands (adjust the
        script path if running from a parent directory):
        -   **Live Query**: `python3 scripts/agent_platform/analyze_traffic.py --live
            --project-id {project_id} --reasoning-engine-id
            {reasoning_engine_id} --metric-type={metric_type}`
        -   **Metrics File**: `python3 scripts/agent_platform/analyze_traffic.py --metrics-file
            {path_to_json} --metric-type={metric_type}`
    -   **Parallel Traffic Analysis**: If you need to run live traffic analysis
        for both latency and token usage, call the tool for each case
        concurrently using background tasks.
    -   **Handling Tool Failures**:
        -   If the `--live` command fails with `CredentialsMissingError` (exit
            code 1), report the error and instruct the user to run `gcloud auth
            application-default login` on their terminal.
        -   For other unexpected failures, analyze the error message (such as
            connection timeouts, invalid permissions, or missing resources).
            Attempt to dynamically correct parameters (such as verifying or
            correcting the region, project ID, or metric type) and retry
            execution before escalating.

-   Map the traffic pattern profile classified by the script to the
    corresponding policy:
    -   **Steady / Consistent**: Maps to **Long-Window Z-Score Baseline (`1w Z-Score Baseline`, 1-week lookback)**
        (safe since the script verified at least 14 days of history).
    -   **Seasonal / Cyclical**: Maps to **Seasonal Decomposition (average 1w and 1d)**.
    -   **Bursty / Inconsistent**: Maps to **Moving Averages** (1h baseline).

### Map Metrics to Algorithms

| Variance Ratio (`std_dev / mean`) | Autocorrelation (1-week lag) | Traffic Classification | Assigned Latency Algorithm and Baseline |
| :--- | :--- | :--- | :--- |
| `≤ 2.0` | `≤ 0.75` | **Steady / Consistent** | Long-Window Z-Score (`1w Z-Score Baseline`, 1-week lookback) |
| `≤ 2.0` | `> 0.75` | **Seasonal / Cyclical** | Seasonal Decomposition (average 1w and 1d) |
| `> 2.0` | Any / Not Applicable | **Bursty / Inconsistent** | Moving Averages (1-hour window) |

*Example classifications:*

-   *Steady / Consistent*: Low variance data (such as steady queries per second)
    with little or no weekly cyclical pattern.
-   *Seasonal / Cyclical*: Clear daily or weekly repeating patterns with high
    weekly correlation (such as daily peak traffic).
-   *Bursty / Inconsistent*: Highly volatile data with rapid spikes and quiet
    periods (such as batch job workloads).

-   **Fallback for Insufficient Data / No Traffic**:

    -   If the script fails with a `ValueError` indicating insufficient data
        points (less than 14 days of history), or if it outputs "New Agent / No
        Traffic" (inactive agent), you MUST fall back to the user inquiry
        instructions in
        [agent_platform_no_historical_traffic_data.md](agent_platform_no_historical_traffic_data.md)
        to ask the user for the expected traffic pattern.

-   Regardless of the script's output profile, the other policies MUST use their
    correct data-class defaults:

    -   **Error Rate**: ALWAYS use **Multi-Window Multi-Burn Rate SLO Alerting**
        (or ratio-based static limits).

## Notify the User

Clearly communicate the findings and selection at the start of your response:

1.  Explain the classified profile (Seasonal / Cyclical, Steady / Consistent, or
    Bursty / Inconsistent) output by the metrics analysis script (citing
    indicators such as standard deviation, autocorrelation, or zero-ratio from
    the script output). If falling back to user inquiry due to zero metrics or
    insufficient data, explain that.
2.  Propose the corresponding alerting policy mapping (Latency matching the
    traffic profile, Error Rate using SLO Burn Rate).
3.  Ask the user whether this expected profile mapping is correct or if they
    would like to customize standard deviation thresholds.
4.  Provide a brief plain-English explanation of what each of the proposed
    alerts measures and how the underlying algorithms work. Keep this
    explanation in the conversational response text.

## Avoid Common Pitfalls

*   **Sparse Traffic Guidance**: If `zero_ratio > 0.95` (even if the profile is
    "Steady / Consistent"), warn the user that Z-score alerts may be unstable.
    Recommend using `Short-Window Z-Score (1h baseline)` or Static Thresholds
    instead of Long-Window Z-Score (`1w Z-Score Baseline`).
agent_platform_no_historical_traffic_data.md 4.1 KB
# Configure Alerts Without Historical Traffic Data

Follow these instructions when no historical metrics data is available for the
agent (for example, a brand new agent).

## Ask the User for the Metric Pattern and Handle Defaults

-   Because no historical metrics data is available and we do NOT perform
    pattern inference based on the name, description, or context of the agent,
    you MUST explicitly ask the user directly in your response what pattern they
    expect for their agent.
-   **Direct Question Format**: You MUST write a direct question in your
    response (for example, "What traffic or usage pattern do you expect for your
    agent?") and explicitly present the following three options for
    customization:
    -   **Steady / Consistent**: Maps the alert policy to **Short-Window Z-Score
        (`Short-Window Z-Score (1h baseline)`, 1-hour lookback)**.
    -   **Bursty / Inconsistent**: Maps the alert policy to **Moving Averages
        (1-hour baseline)**.
    -   **Seasonal / Cyclical**: Maps the alert policy to **Seasonal
        Decomposition (`Seasonal Decomposition (average 1w and 1d)`, requires
        offsets `1d` and `1w`)**.
-   Inform the user that the default pattern is **Steady / Consistent** (which
    maps to `Short-Window Z-Score (1h baseline)`), and that you will use this
    default if they do not specify one.
-   **Handling Automated or Immediate Setup Requests**: If the user's prompt
    asks you to configure or write the alerting policies immediately (for
    example, "Set up its alerting policies in 'monitoring/alerts.tf'"), or if
    you are running in an automated or non-interactive script, you MUST NOT
    pause to wait for their response. Instead, ask the question in your
    response, state that you are deploying the default Steady / Consistent
    pattern because no choice was specified yet, and **immediately proceed to
    generate and write the default configuration (Steady / Consistent ->
    `Short-Window Z-Score (1h baseline)`)**.
-   Regardless of the selected pattern, the other policies MUST use their
    correct data-class defaults:
    -   **Error Rate**: ALWAYS use **Multi-Window Multi-Burn Rate SLO Alerting**
        (or ratio-based static limits).

*   **Short-Window Z-Score (`Short-Window Z-Score (1h baseline)`) / Moving
    Averages**: Require **1 hour** of metric history.

*   **SLO Burn Rate (Error Rate)**: Requires up to **3 days** for the slow burn
    component, though the fast burn component (`1h`/`5m`) works after 1 hour.

*   **Seasonal Decomposition (`Seasonal Decomposition (average 1w and 1d)`)**:
    Requires **1 week** of history (due to the `1w` offset). **WARNING:** If the
    user switches to Seasonal Decomposition, warn them that they will have a
    1-week blind spot, and suggest starting with **Short-Window Z-Score
    (`Short-Window Z-Score (1h baseline)`)** or **Static Thresholds** as a
    temporary guard.

## Notify the User

Clearly communicate the lack of historical data, explain the options, and detail
the immediate actions taken at the start of your response:

1.  Explain that because the agent has no historical data, you cannot
    automatically analyze the traffic pattern.
2.  Ask the user directly what traffic pattern they expect (Steady / Consistent,
    Seasonal / Cyclical, or Bursty / Inconsistent), detailing the mapping
    differences and the 1-week blind spot risk if they choose Seasonal.
3.  Inform the user that the default is **Steady / Consistent** (`Short-Window
    Z-Score (1h baseline)` algorithm for Latency) and you will proceed with this
    default if they do not choose another option.
4.  If the user accepts the default, explain that you have deployed the Steady /
    Consistent default to ensure the files are configured immediately, and that
    they can request an update if they prefer another pattern.
5.  Explain the warm-up periods (1 hour for Latency, up to 3 days for SLOs).
6.  Propose the rest of the configuration mapping: Error Rate (SLO Burn Rate).
7.  Provide a brief plain-English explanation of what each of the proposed
    alerts measures and how the underlying algorithms work.
agent_platform_quality_alert_policies.md 12.8 KB
# Configure Quality Alert Policies

> [!IMPORTANT]
> Quality alerting policies are specific to **Vertex AI Agent Engine**
> deployments and rely on metrics exported by **Vertex AI Online Monitors**.

These alert policies help users diagnose drops in response quality (intent
drift) or hallucination rates from their agents. They also help identify when
an agent gets stuck in an infinite reasoning or tool call loop.

## Table of Contents

-   [Verify Prerequisites](#verify-prerequisites): Lines 25-117
    -   [Warn About Billing Costs and Provision the Online Monitor](#warn-about-billing-costs-and-provision-the-online-monitor): Lines 27-117
-   [Follow Critical Rules](#follow-critical-rules): Lines 118-161
    -   [Review Telemetry Metrics](#review-telemetry-metrics): Lines 134-146
    -   [Construct the Metric Filter](#construct-the-metric-filter): Lines 147-161
-   [Configure Policy Specifications](#configure-policy-specifications): Lines 162-263
    -   [Configure Final Response Quality](#configure-final-response-quality): Lines 164-196
    -   [Configure Tool Use Quality](#configure-tool-use-quality): Lines 197-229
    -   [Configure Hallucination Alerts](#configure-hallucination-alerts): Lines 230-263
-   [Run Tooling Scripts](#run-tooling-scripts): Lines 264-281
-   [Validate and Finalize](#validate-and-finalize): Lines 282-292

## Verify Prerequisites

### Warn About Billing Costs and Provision the Online Monitor

Quality alerting policies rely on metrics exported by Online Monitors. If
telemetry is disabled on the reasoning engine, no traces are sent, and the
quality metrics remain empty. Ensure the Online Monitor is provisioned for the
agent and telemetry is enabled:

-   [ ] **Ask for Approval with Billing Warning**: Both Online Monitors and
    Telemetry incur separate billing charges. If not pre-approved in the prompt:
    -   Your response MUST warn the user about the potential billing costs of
        **Online Monitor** and explicitly ask the user for approval before
        configuring or provisioning it.
    -   Your response MUST warn the user about the potential billing costs of
        **Telemetry (Cloud Trace/Logging export)** and explicitly ask the user
        for approval before configuring or enabling it.
    -   **Important**: Even when printing draft Terraform HCL or CLI commands
        without executing them, do not merely list billing warnings as passive
        bullet points — you MUST include a direct question asking the user to
        confirm and approve both Online Monitor and Telemetry billing costs
        before configuring them (for example, *"Do you approve enabling
        Telemetry (Cloud Trace/Logging export) and provisioning the Vertex AI
        Online Monitor, given the additional billing costs they incur?"*).
-   [ ] **Verify Telemetry First**: Before generating any alerting policy plan
    or provisioning Online Monitors, you MUST always verify the telemetry status
    of the Reasoning Engine first using the `check_telemetry.py` script as
    detailed in [Verify Telemetry Status](#verify-telemetry-status) below.

#### Verify Telemetry Status

Before generating any alerting policies, proposing a plan, or provisioning
Online Monitors, you MUST always verify whether the agent is ready to export
traces by running the telemetry verification script:

*   **Mandatory Command**: `python3 scripts/agent_platform/check_telemetry.py
    --project-id "{project_id}" --agent-resource-name "{agent_resource_name}"`
    *   **Note on Parameters**: The `{agent_resource_name}` parameter MUST be
        the full resource path format
        `projects/<project_id>/locations/<location>/reasoningEngines/<agent_id>`
        (for example,
        `projects/gcp-prod/locations/us-central1/reasoningEngines/556677`) and
        not just the agent ID itself.
    *   **Dependency Failures**: If package imports or dependency installation
        fails, resolve the issues (for example, by verifying package
        installation) and run the script again with the specific `project-id`
        and `agent-resource-name` parameters. If you cannot run the script
        successfully due to missing dependencies, you MUST still attempt to run
        it first and then include the complete, pre-populated execution command
        in your final response as a verification plan (this applies even if the
        user has pre-approved provisioning).
*   **Detailed Enablement Instructions**: For details on the required
    environment variables, Terraform setups, and project dependencies, you MUST
    read and follow:
    [agent_platform_telemetry_enablement.md](agent_platform_telemetry_enablement.md).

#### Provision the Online Monitor

Because Online Monitors cannot be configured using Terraform, follow the
instructions in [Run Tooling Scripts](#run-tooling-scripts) to run the
`create_online_monitor` provisioning script and generate the required metrics.
Proceed to the **Validate and Finalize** section below.

#### Format the Execution Plan

If execution fails (for example, due to sandbox restrictions or permissions),
you MUST provide a clear, actionable plan for the user to follow as a next
step. Your response MUST explicitly include a section containing the exact
Python execution command with all parameter values (such as project ID, region,
and agent resource name) fully populated. Do not merely state that the user must
run it.

Format the plan as follows:

#### Provide the Online Monitor Provisioning Plan

**Online Monitor Provisioning Command:**

```bash
python3 scripts/agent_platform/create_online_monitor.py \
  --project-id "{project_id}" \
  --agent-resource-name "projects/{project_id}/locations/{location}/reasoningEngines/{agent_id}" \
  --sampling-percentage {percentage}
```

**Verify Telemetry Command (Optional fallback):**

```bash
python3 scripts/agent_platform/check_telemetry.py \
  --project-id "{project_id}" \
  --agent-resource-name "projects/{project_id}/locations/{location}/reasoningEngines/{agent_id}"
```

## Follow Critical Rules

*   **Alert policy configuration**: You MUST configure the following Quality
    alerting policies (single-metric degradation policies, also referred to as
    `Quality - Metric Degradation (Single Metric)`). See
    [Review Telemetry Metrics](#review-telemetry-metrics) to get the required
    metrics and read the descriptions for each signal:
    1.  **Final Response Quality** (5-Minute window)
    2.  **Tool Use Quality** (5-Minute window)
    3.  **Hallucination** (5-Minute window)
*   **Standard Threshold Filters for Agent Quality**: For the 3 agent quality
    metrics, you MUST use standard `condition_threshold` filters matching the
    monitored resource type `aiplatform.googleapis.com/OnlineEvaluator` and
    metric type `aiplatform.googleapis.com/online_evaluator/scores`. Do **NOT**
    use PromQL or `condition_sql`.

### Review Telemetry Metrics

Because the scores metric is of value type `DISTRIBUTION`, standard mean-based
PromQL or arithmetic `ALIGN_MEAN` aligners are unsupported. You MUST use a
percentile aligner (typically `ALIGN_PERCENTILE_50` to evaluate the median
score) within the `aggregations` block of your `condition_threshold`.

| Signal | Metric Name (`evaluation_metric_name`) | Target Threshold | Recommended Aligner |
| :--- | :--- | :--- | :--- |
| **Final Response Quality** | `final_response_quality_v1` | `< 0.8` (or custom) | `ALIGN_PERCENTILE_50` |
| **Tool Use Quality** | `tool_use_quality_v1` | `< 0.8` (or custom) | `ALIGN_PERCENTILE_50` |
| **Hallucination (Groundedness)** | `hallucination_v1` | `< 0.9` (or custom) | `ALIGN_PERCENTILE_50` |

### Construct the Metric Filter

All agent quality evaluation metrics are exported by Online Monitors to the
monitored resource type `aiplatform.googleapis.com/OnlineEvaluator` under the
metric type `aiplatform.googleapis.com/online_evaluator/scores`.

When configuring a quality alert policy in Terraform, use the following filter
expression structure:

```promql
resource.type="aiplatform.googleapis.com/OnlineEvaluator"
AND metric.type="aiplatform.googleapis.com/online_evaluator/scores"
AND metric.labels.evaluation_metric_name="{metric_name}"
```

## Configure Policy Specifications

### Configure Final Response Quality

#### Define Terraform HCL for Final Response Quality

```terraform
resource "google_monitoring_alert_policy" "final_response_quality" {
  project      = var.project_id
  display_name = "Agent Quality - Final Response Quality Low"
  combiner     = "OR"
  conditions {
    display_name = "Final Response Quality Score < 0.8"
    condition_threshold {
      filter                  = "resource.type=\"aiplatform.googleapis.com/OnlineEvaluator\" AND metric.type=\"aiplatform.googleapis.com/online_evaluator/scores\" AND metric.labels.evaluation_metric_name=\"final_response_quality_v1\""
      comparison              = "COMPARISON_LT"
      threshold_value         = 0.8
      duration                = "300s" # 5m buffer
      evaluation_missing_data = "EVALUATION_MISSING_DATA_INACTIVE"
      trigger {
        count = 1
      }
      aggregations {
        alignment_period   = "300s" # Aligned with duration
        per_series_aligner = "ALIGN_PERCENTILE_50"
      }
    }
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-alert-configuration"
  }
}
```

### Configure Tool Use Quality

#### Define Terraform HCL for Tool Use Quality

```terraform
resource "google_monitoring_alert_policy" "tool_use_quality" {
  project      = var.project_id
  display_name = "Agent Quality - Tool Use Quality Low"
  combiner     = "OR"
  conditions {
    display_name = "Tool Use Quality Score < 0.8"
    condition_threshold {
      filter                  = "resource.type=\"aiplatform.googleapis.com/OnlineEvaluator\" AND metric.type=\"aiplatform.googleapis.com/online_evaluator/scores\" AND metric.labels.evaluation_metric_name=\"tool_use_quality_v1\""
      comparison              = "COMPARISON_LT"
      threshold_value         = 0.8
      duration                = "300s"
      evaluation_missing_data = "EVALUATION_MISSING_DATA_INACTIVE"
      trigger {
        count = 1
      }
      aggregations {
        alignment_period   = "300s"
        per_series_aligner = "ALIGN_PERCENTILE_50"
      }
    }
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-alert-configuration"
  }
}
```

### Configure Hallucination Alerts

#### Define Terraform HCL for Hallucination Alerts

```terraform
resource "google_monitoring_alert_policy" "hallucination" {
  project      = var.project_id
  display_name = "Agent Quality - Hallucination (Groundedness) Low"
  combiner     = "OR"

  conditions {
    display_name = "Groundedness Score < 0.9"
    condition_threshold {
      filter                  = "resource.type=\"aiplatform.googleapis.com/OnlineEvaluator\" AND metric.type=\"aiplatform.googleapis.com/online_evaluator/scores\" AND metric.labels.evaluation_metric_name=\"hallucination_v1\""
      comparison              = "COMPARISON_LT"
      threshold_value         = 0.9
      duration                = "300s"
      evaluation_missing_data = "EVALUATION_MISSING_DATA_INACTIVE"
      trigger {
        count = 1
      }
      aggregations {
        alignment_period   = "300s"
        per_series_aligner = "ALIGN_PERCENTILE_50"
      }
    }
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-alert-configuration"
  }
}
```

## Run Tooling Scripts

1.  **create_online_monitor**: Use this script to provision the required Online
    Monitor and generate the telemetry metrics:
    *   Command: `python3 scripts/agent_platform/create_online_monitor.py
        --project-id={gcp_project_id}
        --agent-resource-name={agent_resource_name}
        [--sampling-percentage={percentage}]`
    *   Sampling Rate Recommendation: For production agents, configure a
        conservative sampling percentage (default: **10%**) to control LLM
        evaluation costs. For details, refer to
        [Continuous evaluation with online monitors](https://docs.cloud.google.com/gemini-enterprise-agent-platform/optimize/evaluation/evaluate-online.md.txt).
2.  **check_telemetry**: Verify whether telemetry is enabled on a Vertex AI
    Reasoning Engine using this script:
    *   Command: `python3 scripts/agent_platform/check_telemetry.py
        --project-id={gcp_project_id}
        --agent-resource-name="projects/{project_id}/locations/{location}/reasoningEngines/{agent_id}"`

## Validate and Finalize

*   **Apply Duration Buffers (Transient Glitches)**: To avoid alerts firing on
    transient spikes, always use a `duration = "300s"` (5 minutes) buffer to
    filter out transient scoring dips or evaluation outliers caused by temporary
    LLM judge congestion or edge-case query outliers.
*   **Handle Script Failures**: If `check_telemetry.py` or
    `create_online_monitor.py` fails unexpectedly, analyze the error message.
    Common issues include an invalid `agent-resource-name` format (must be the
    full path), missing permissions, or an unenabled API. Dynamically correct
    parameters and retry.
agent_platform_reliability_alert_policies.md 28.5 KB
# Configure Reliability Alert Policies

These alert policies help users pinpoint the root cause of ongoing increased
agent latency and high error rates with model and tool requests.

> [!IMPORTANT]
> **Full Production Agent Configuration Requirements**: When configuring full production alerts for an AI agent, you **MUST** read all five policy references ([Reliability](agent_platform_reliability_alert_policies.md), [Quality](agent_platform_quality_alert_policies.md), [Cost](agent_platform_cost_alert_policies.md), [Safety](agent_platform_safety_alert_policies.md), and [Security](agent_platform_security_alert_policies.md)) and:
> 1. Generate **11 alerting policies** (5 reliability, 3 quality, 1 cost, 1 safety, and 1 security including High IAM Permission Denied Trigger Rate).
> 2. Always include all four pre-populated supporting script commands with all parameter values filled in (even if a fallback table name is provided):
>    * **Streamlined Discovery**: `python3 scripts/agent_platform/gather_agent_info.py --project-id "<project_id>" --agent-name "<agent_name>"`
>    * **Telemetry Verification**: `python3 scripts/agent_platform/check_telemetry.py --project-id "<project_id>" --location "us-central1" --agent-resource-name "projects/<project_id>/locations/us-central1/reasoningEngines/<agent_id>" --query-monitoring-metadata`
>    * **Online Monitor Provisioning**: `python3 scripts/agent_platform/create_online_monitor.py --project-id "<project_id>" --agent-resource-name "projects/<project_id>/locations/us-central1/reasoningEngines/<agent_id>"`
>    * **Duplicate Policy Scanner**: `python3 scripts/agent_platform/scan_duplicates.py monitoring/`
> 3. If Online Monitor provisioning or Telemetry enablement is not pre-approved in the prompt, you **MUST** warn the user about the potential billing costs of **both** the **Online Monitor** and **Telemetry (Cloud Trace/Logging export)** and include an explicit direct question asking the user for approval before configuring or provisioning them.
> 4. Always prompt the user to ask whether they would like to configure notification channels if none were provided.
> 5. Include a `user_labels` block with `created-with-google-skill = "cloud-monitoring-alert-configuration"` on every `google_monitoring_alert_policy` resource.

## Table of Contents

-   [Verify Prerequisites](#verify-prerequisites): Lines 34-110
    -   [Prepare SQL Metric Prerequisites](#prepare-sql-metric-prerequisites): Lines 36-82
    -   [Prepare PromQL Metric Prerequisites](#prepare-promql-metric-prerequisites): Lines 83-110
-   [Follow Critical Rules](#follow-critical-rules): Lines 111-149
    -   [Review Telemetry Metrics](#review-telemetry-metrics): Lines 136-149
-   [Configure Policy Specifications](#configure-policy-specifications): Lines 150-587
    -   [Configure Latency Alerts](#configure-latency-alerts): Lines 152-286
    -   [Configure Error Rate Fast Burn SLO (1-Hour and 5-Minute Windows)](#configure-error-rate-fast-burn-slo-1-hour-and-5-minute-windows): Lines 287-382
    -   [Configure Error Rate Slow Burn SLO (3-Day and 6-Hour Windows)](#configure-error-rate-slow-burn-slo-3-day-and-6-hour-windows): Lines 383-440
    -   [Configure Model Call Error Rate Alerts](#configure-model-call-error-rate-alerts): Lines 441-514
    -   [Configure Tool Call Error Rate Alerts](#configure-tool-call-error-rate-alerts): Lines 515-587
-   [Run Tooling Scripts](#run-tooling-scripts): Lines 588-610
-   [Validate and Finalize](#validate-and-finalize): Lines 611-663

## Verify Prerequisites

### Prepare SQL Metric Prerequisites

#### Retrieve the Trace Scope Observability Analytics Table

Retrieve the Observability Analytics table where all the Trace scope spans are
stored for the SQL-based alerts.

#### Link the BigQuery Dataset

A linked BigQuery dataset instance is required to configure SQL alert policies
depending on Observability Analytics trace data. This dataset MUST hold views
for the `_Trace` trace bucket of the target Google Cloud project.

Applicable BigQuery datasets have a `"type": "LINKED"` attribute and reference
the `_Trace` bucket in their description. To list all existing BigQuery datasets
in a project, run the following command:

```bash
bq ls --format=prettyjson --project_id={project_id}
```

Where:

*   `{project_id}`: The target Google Cloud project ID.

If missing, you MUST get user confirmation before creating it. If denied, skip
SQL reliability alerts. Otherwise, create it using:

```bash
gcloud beta observability buckets datasets links create \
  projects/{project_id}/locations/{location}/buckets/{bucket_id}/datasets/{dataset_id}/links/{link_id} \
 --dataset={dataset_id} \
 --bucket={bucket_id} \
 --location={location} \
 --project={project_id}
```

Where:

*   `{project_id}`: Target Google Cloud project ID.
*   `{location}`: Observability bucket location (found in the Observability
    Analytics table name).
*   `{bucket_id}`: Bucket ID (default: `_Trace`).
*   `{dataset_id}`: Dataset ID (default: `Spans`).
*   `{link_id}`: New BigQuery dataset name (default:
    `trace_bq_linked_dataset`).

### Prepare PromQL Metric Prerequisites

#### Select Algorithms and Map Policies

Alerting policies for agents MUST map to the appropriate algorithms to ensure
statistical stability and prevent alert noise or blind spots based on data
classes:

*   **Latency**: Follows the workload traffic pattern (Steady / Consistent ->
    `1w Z-Score Baseline` or `Short-Window Z-Score (1h baseline)`; Seasonal /
    Cyclical -> `Seasonal Decomposition (average 1w and 1d)`; Bursty /
    Inconsistent -> `Moving Averages`).
*   **Error Rate**: ALWAYS use **Multi-Window Multi-Burn Rate SLOs** (or
    ratio-based static thresholds). Error rate is naturally sparse (`0`). If
    standard deviation is `0`, Z-scores are mathematically unstable
    (division-by-zero), causing false alerts.

To resolve the workload traffic pattern (Seasonal / Cyclical, Steady /
Consistent, or Bursty / Inconsistent), follow the instructions corresponding to
the availability of historical metrics data:

*   **Case 1: No historical metrics data available (for example, brand new agent)**:
    You MUST read and follow:
    [agent_platform_no_historical_traffic_data.md](agent_platform_no_historical_traffic_data.md)
*   **Case 2: Historical metrics data available (for example, active agent with
    traffic)**: You MUST read and follow:
    [agent_platform_has_historical_traffic_data.md](agent_platform_has_historical_traffic_data.md)

## Follow Critical Rules

*   **Brand New Agents (No Traffic History)**: When setting up alerts for a
    brand new agent, you MUST explicitly ask the user what traffic pattern they
    expect (Steady / Consistent, Seasonal / Cyclical, or Bursty / Inconsistent)
    in your response. If immediate setup is requested, ask the question but
    proceed using the default Steady/Consistent (`Short-Window Z-Score (1h
    baseline)`) pattern. Follow
    [agent_platform_no_historical_traffic_data.md](agent_platform_no_historical_traffic_data.md).
*   **Query Types for Reliability (No MQL or Threshold Filters)**:
    *   For latency and container SLO error rate metrics, you MUST use
        `condition_prometheus_query_language` with PromQL.
    *   For the downstream model call and tool call error rate metrics, you MUST
        use `condition_sql` with GoogleSQL querying `_Trace.Spans._AllSpans`.
    *   Do **NOT** use Monitoring Query Language (MQL) or standard
        `condition_threshold` for these reliability metrics.
*   **Critical alert thresholds**: Configure alerts with a **5% critical
    threshold** (aligned with the Vertex AI SLA uptime definition). For warning
    alerts, optionally configure a **1% threshold** to catch downstream
    degradation or quota exhaustion before it affects user experience.
*   **For Metrics using PromQL**: ALWAYS use grouping aggregations. Group by
    `gen_ai_agent_name` (for example, `by (gen_ai_agent_name)`). Avoid filtering
    to a single ID or name unless requested. Metrics are emitted through
    OpenTelemetry.

### Review Telemetry Metrics

All raw telemetry metrics for the Agent Platform container runtime are
cumulative **counters** monitored using PromQL. Downstream model calls are
tracked through OpenTelemetry Trace Spans exported to Observability Analytics
and monitored using SQL queries.

| Signal | Source / Raw Metric | Type | Description |
| :--- | :--- | :--- | :--- |
| **Latency** | `gen_ai_invoke_agent_duration_bucket` | Counter | Histogram bucket of agent request latencies |
| **Error Rate** | `gen_ai_invoke_agent_duration_count` | Counter | Cumulative count of agent requests |
| **Model Call Error Rate** | `global._Trace.Spans._AllSpans` view | Trace Spans | Downstream LLM API call traces (`status.code = 2` is error) |
| **Tool Call Error Rate** | `global._Trace.Spans._AllSpans` view | Trace Spans | Downstream tool execution traces (`status.code = 2` is error) |

## Configure Policy Specifications

### Configure Latency Alerts

#### Select the Latency Telemetry Query

##### Configure Z-Score for Steady Traffic

**Long-Window Z-Score (`1w Z-Score Baseline`, for established agents with more than 1 week of history)**

Compares the 5-minute 95th percentile latency to the 1-week baseline.

*   `LATENCY_ALGORITHM_NAME_SHORT`: "long_window_zscore"
*   `LATENCY_ALGORITHM_NAME_LONG`: "Long-Window Z-Score"
*   `LATENCY_ALGORITHM_CONDITION_DESCRIPTION`: "Z-Score > 3"

```promql
abs(
  histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resource="generic_node"}[5m])) by (le, gen_ai_agent_name))
  -
  histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resource="generic_node"}[1w])) by (le, gen_ai_agent_name))
)
/
stddev_over_time(
  (histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resource="generic_node"}[5m])) by (le, gen_ai_agent_name)))[1w:5m]
) > 3
```

*Note: The denominator uses a subquery `[1w:5m]` to calculate standard deviation
of the 5-minute latency over 1 week. The numerator uses `[1w]` rate directly to
avoid a second subquery for the mean.*

**Short-Window Z-Score (`Short-Window Z-Score (1h baseline)`, for newer agents with more than 1 hour of history)**

Compares the 1-minute 95th percentile latency to the 1-hour baseline for rapid
activation on new agents.

*   `LATENCY_ALGORITHM_NAME_SHORT`: "short_window_zscore"
*   `LATENCY_ALGORITHM_NAME_LONG`: "Short-Window Z-Score"
*   `LATENCY_ALGORITHM_CONDITION_DESCRIPTION`: "Z-Score > 3"

```promql
abs(
  histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resource="generic_node"}[1m])) by (le, gen_ai_agent_name))
  -
  histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resource="generic_node"}[1h])) by (le, gen_ai_agent_name))
)
/
stddev_over_time(
  (histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resource="generic_node"}[1m])) by (le, gen_ai_agent_name)))[1h:1m]
) > 3
```

##### Configure Moving Averages for Bursty Traffic

Compares the 5-minute latency to the 1-hour `Moving Averages` baseline.

*   `LATENCY_ALGORITHM_NAME_SHORT`: "moving_average"
*   `LATENCY_ALGORITHM_NAME_LONG`: "Moving Average"
*   `LATENCY_ALGORITHM_CONDITION_DESCRIPTION`: "5m Above 1h Average"

```promql
histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resource="generic_node"}[5m])) by (le, gen_ai_agent_name))
>
1.5 * histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resource="generic_node"}[1h])) by (le, gen_ai_agent_name))
```

##### Configure Seasonal Decomposition for Cyclical Traffic

> [!NOTE]
> For the Latency alert policy, ONLY use seasonal decomposition (`Seasonal
> Decomposition (average 1w and 1d)`) to track latency spikes. Alert policies
> using seasonal decomposition tracking both spikes and drops can falsely
> trigger alerts.

Compares the 5-minute latency to the average of 1-week and 1-day lookback
baselines.

> [!CAUTION]
> The numerator (current latency) MUST NOT have any offset. Offsets
> (`offset 1d`, `offset 1w`) MUST only be applied to the denominator to
> construct the historical baseline for comparison. Never apply an offset to the
> first numerator.

*   `LATENCY_ALGORITHM_NAME_SHORT`: "seasonal_decomposition"
*   `LATENCY_ALGORITHM_NAME_LONG`: "Seasonal Decomposition"
*   `LATENCY_ALGORITHM_CONDITION_DESCRIPTION`: "Seasonal Decomposition > 2"

```promql
histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resource="generic_node"}[5m])) by (le, gen_ai_agent_name))
/
(
  (
    histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resource="generic_node"}[5m] offset 1d)) by (le, gen_ai_agent_name))
    +
    histogram_quantile(0.95, sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_bucket{monitored_resource="generic_node"}[5m] offset 1w)) by (le, gen_ai_agent_name))
  ) / 2
)
> 2
```

#### Define Terraform HCL for Latency

```terraform
resource "google_monitoring_alert_policy" "latency_{latency_algorithm_name_short}" {
  project      = var.project_id
  display_name = "Agent Reliability - Latency {latency_algorithm_name_long}"
  combiner     = "OR"

  conditions {
    display_name = "Latency {latency_algorithm_condition_description}"
    condition_prometheus_query_language {
      query    = <<EOT
{latency_telemetry_query}
EOT
    }
  }

  documentation {
    content   = "High latency detected for the agent."
    mime_type = "text/markdown"
    subject   = "Agent Reliability - Latency {latency_algorithm_name_long} on $${metric.label.gen_ai_agent_name}"
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-alert-configuration"
  }
}
```

Where:

*   `{latency_algorithm_name_short}`: Short algorithm name.
*   `{latency_algorithm_name_long}`: Long algorithm name.
*   `{latency_algorithm_condition_description}`: Condition description.
*   `{latency_telemetry_query}`: PromQL query from above.

### Configure Error Rate Fast Burn SLO (1-Hour and 5-Minute Windows)

> [!IMPORTANT] **SLO standard alignment.** The Fast Burn (factor `14.4`, `1h` &
> `5m` windows, `duration = "300s"`) and Slow Burn (factor `1.0`, `3d` & `6h`
> windows, **no `duration`** because the lookback exceeds 25h) policies below
> are the Agent Platform implementation of the standard SRE burn-rate contract,
> and remain the authoritative templates for agent reliability alerts.
>
> This is a deliberate **exception** to the skill-wide delegation rule: Agent
> Platform is the one resource whose burn-rate policies live in this skill. If
> the user asks to **customize the SLO** — a different target, a latency SLO,
> window-based "good minutes" evaluation, or App Hub scoping — delegate to the
> `google-cloud-slo-alert-configuration` skill, which owns the SLO wizard, the
> burn-rate templates (`references/promql_templates.md`), the SLI mapping
> (`references/service_metrics.md`), and the App Hub scoping labels
> (`references/app_hub_labels.md`).
>
> **Context to hand off** (so the SLO skill does not repeat discovery):
>
> *   **Resource type**: an OpenTelemetry-instrumented AI agent. This is
>     **runtime-agnostic** — the agent may run on Vertex AI Agent Engine, Cloud
>     Run, or any other OpenTelemetry-instrumented host. Do **not** hand off a
>     Vertex-specific monitored resource: these are generic OpenTelemetry
>     workload metrics, which land under `generic_node`, and every query in this
>     file filters `monitored_resource="generic_node"`.
> *   **Grouping labels**: `gen_ai_agent_name`.
> *   **Error rate SLI**:
>     `workload_googleapis_com:gen_ai_invoke_agent_duration_count`; bad =
>     `error_type!=""`.
> *   **Latency SLI**:
>     `workload_googleapis_com:gen_ai_invoke_agent_duration_bucket`; percentile
>     using `histogram_quantile(q, sum(rate(...)) by (le, gen_ai_agent_name))`.
> *   **SLO target**: `slo_target` (default `0.999`).
>
> Model call and tool call error rates are **not** available as SLIs: they are
> derived from trace spans in `global._Trace.Spans._AllSpans` using SQL, not
> PromQL, so the SLO skill cannot build burn-rate queries from them.
>
> Define `variable "slo_target"` (default `0.999`) in the generated Terraform so
> the burn-rate thresholds stay parameterized.

#### Define the Fast Burn Telemetry Query

Always use Multi-Window Multi-Burn Rate SLOs. Z-score is not recommended due to
sparsity.

```promql
(
  sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resource="generic_node",error_type!=""}[5m])) by (gen_ai_agent_name)
  /
  sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resource="generic_node"}[5m])) by (gen_ai_agent_name)
  > (1 - ${var.slo_target}) * 14.4
)
and
(
  sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resource="generic_node",error_type!=""}[1h])) by (gen_ai_agent_name)
  /
  sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resource="generic_node"}[1h])) by (gen_ai_agent_name)
  > (1 - ${var.slo_target}) * 14.4
)
```

#### Define Terraform HCL for Fast Burn SLO

```terraform
resource "google_monitoring_alert_policy" "error_rate_fast_burn" {
  project      = var.project_id
  display_name = "Agent Reliability - Error Rate Fast Burn SLO"
  combiner     = "OR"

  conditions {
    display_name = "Error Rate Fast Burn (1h/5m)"
    condition_prometheus_query_language {
      query    = {error_rate_fast_slo_telemetry_query}
      duration = "300s" # 5m buffer
    }
  }

  documentation {
    content   = "Fast Burn error rate SLO violation detected."
    mime_type = "text/markdown"
    subject   = "Error Rate Fast Burn (1h/5m) on $${metric.label.gen_ai_agent_name}"
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-alert-configuration"
  }
}
```

Where:

*   `{error_rate_fast_slo_telemetry_query}`: The PromQL alert query configured
    in [Define the Fast Burn Telemetry Query](#define-the-fast-burn-telemetry-query)
    above.

### Configure Error Rate Slow Burn SLO (3-Day and 6-Hour Windows)

#### Define the Slow Burn Telemetry Query

Always use Multi-Window Multi-Burn Rate SLOs. Z-score is not recommended due to
sparsity.

```promql
(
  sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resource="generic_node",error_type!=""}[6h])) by (gen_ai_agent_name)
  /
  sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resource="generic_node"}[6h])) by (gen_ai_agent_name)
  > (1 - ${var.slo_target}) * 1.0
)
and
(
  sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resource="generic_node",error_type!=""}[3d])) by (gen_ai_agent_name)
  /
  sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{monitored_resource="generic_node"}[3d])) by (gen_ai_agent_name)
  > (1 - ${var.slo_target}) * 1.0
)
```

#### Define Terraform HCL for Slow Burn SLO

```terraform
resource "google_monitoring_alert_policy" "error_rate_slow_burn" {
  project      = var.project_id
  display_name = "Agent Reliability - Error Rate Slow Burn SLO"
  combiner     = "OR"

  conditions {
    display_name = "Error Rate Slow Burn (3d/6h)"
    condition_prometheus_query_language {
      query = <<EOT
{error_rate_slow_slo_telemetry_query}
EOT
    }
  }

  documentation {
    content   = "Slow Burn error rate SLO violation detected."
    mime_type = "text/markdown"
    subject   = "Error Rate Slow Burn (3d/6h) on $${metric.label.gen_ai_agent_name}"
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-alert-configuration"
  }
}
```

Where:

*   `{error_rate_slow_slo_telemetry_query}`: The PromQL alert query configured
    in [Define the Slow Burn Telemetry Query](#define-the-slow-burn-telemetry-query)
    above.

### Configure Model Call Error Rate Alerts

#### Define the Model Call Error Rate Query

When configuring a SQL-based alerting condition (`condition_sql`) in Google
Cloud Monitoring for an agent, use the following template to query trace spans
exported to Observability Analytics:

```sql
SELECT
  JSON_VALUE(resource.attributes, '$."cloud.resource_id"') as agent_id,
  JSON_VALUE(attributes, '$."gen_ai.request.model"') as model,
  (COUNTIF(status.code = 2) * 100.0) / COUNT(*) AS model_error_rate
FROM
  `${TRACE_SCOPE_TABLE_NAME}`
WHERE
  JSON_VALUE(attributes, '$."gen_ai.request.model"') IS NOT NULL
GROUP BY
  agent_id,
  model
HAVING
  model_error_rate > 5.0
```

Where:

*   `{trace_scope_table_name}`: The Trace scope Observability Analytics table
    name retrieved in [Verify Prerequisites](#verify-prerequisites).

#### Define Terraform HCL for Model Call Error Rate

Implement the alert policy resource using a `condition_sql` block with a
`row_count_test` condition:

```terraform
resource "google_monitoring_alert_policy" "model_call_error_rate" {
  project      = var.project_id
  display_name = "Agent Reliability - High Model Call Error Rate"
  combiner     = "OR"

  conditions {
    display_name = "Agent Model Call Error Rate Exceeds 5%"
    condition_sql {
      query = <<EOT
{model_call_high_error_rate_telemetry_query}
EOT

      # Run evaluation periodically (periodicity value must be between 5 and 1440 minutes)
      minutes {
        periodicity = 5
      }

      # Test triggers when one or more models violate the threshold (returning rows)
      row_count_test {
        comparison = "COMPARISON_GT"
        threshold  = 0
      }
    }
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-alert-configuration"
  }

  notification_channels = [google_monitoring_notification_channel.email.name]
}
```

Where:

*   `{model_call_high_error_rate_telemetry_query}`: The SQL alert query
    configured in [Define the Model Call Error Rate Query](#define-the-model-call-error-rate-query)
    above.

### Configure Tool Call Error Rate Alerts

#### Define the Tool Call Error Rate Query

When configuring a SQL-based alerting condition (`condition_sql`) in Google
Cloud Monitoring for an agent to monitor tool call error rates, use the
following template to query trace spans exported to Observability Analytics:

```sql
SELECT
  JSON_VALUE(resource.attributes, '$."cloud.resource_id"') as agent_id,
  JSON_VALUE(attributes, '$."gen_ai.tool.name"') as tool_name,
  (COUNTIF(status.code = 2) * 100.0) / COUNT(*) AS tool_error_rate
FROM
  `${TRACE_SCOPE_TABLE_NAME}`
WHERE
  JSON_VALUE(attributes, '$."gen_ai.operation.name"') = 'execute_tool'
  AND JSON_VALUE(attributes, '$."gen_ai.tool.name"') IS NOT NULL
GROUP BY
  agent_id,
  tool_name
HAVING
  tool_error_rate > 5.0
```

Where:

*   `{trace_scope_table_name}`: The Trace scope Observability Analytics table
    name retrieved in [Verify Prerequisites](#verify-prerequisites).

#### Define Terraform HCL for Tool Call Error Rate

Implement the alert policy resource using a `condition_sql` block with a
`row_count_test` condition:

```terraform
resource "google_monitoring_alert_policy" "tool_call_error_rate" {
  project      = var.project_id
  display_name = "Agent Reliability - High Tool Call Error Rate"
  combiner     = "OR"

  conditions {
    display_name = "Agent Tool Call Error Rate Exceeds 5%"
    condition_sql {
      query = <<EOT
{tool_call_high_error_rate_telemetry_query}
EOT

      minutes {
        periodicity = 5
      }

      row_count_test {
        comparison = "COMPARISON_GT"
        threshold  = 0
      }
    }
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-alert-configuration"
  }

  notification_channels = [google_monitoring_notification_channel.email.name]
}
```

Where:

*   `{tool_call_high_error_rate_telemetry_query}`: The SQL alert query
    configured in [Define the Tool Call Error Rate Query](#define-the-tool-call-error-rate-query)
    above.

## Run Tooling Scripts

1.  **gather_agent_info (Primary Streamlined Discovery — REQUIRED)**: Always run
    (or print when execution is disabled) this streamlined discovery command
    first with all parameter values filled in, even if a fallback table name is
    provided:
    *   Command: `python3 scripts/agent_platform/gather_agent_info.py --project-id="{gcp_project}" --agent-name="{agent_name}"`
2.  **scan_duplicates (Required Duplicate Policy Verification)**: Always run (or
    print when execution is disabled) this command to verify that no duplicate
    alert policy blocks exist:
    *   Command: `python3 scripts/agent_platform/scan_duplicates.py monitoring/`
3.  **lint_syntax (HCL and PromQL Syntax Validation)**: When reviewing,
    validating, or correcting an existing or draft `.tf` file for an AI agent,
    run (or print when execution is disabled) this linter to check for balanced
    parentheses/braces, valid PromQL time windows (`[5m]`, `[1w:5m]`), agent
    identifier grouping (`gen_ai_agent_name`), and duration buffer rules:
    *   Command: `python3 scripts/agent_platform/lint_syntax.py <path_to_tf_file>`
4.  **list_trace_scope_table_names (Fallback)**: Use this script ONLY if
    `gather_agent_info.py` fails to retrieve the associated Trace scope
    Observability Analytics SQL table name:
    *   Command: `python3 scripts/agent_platform/list_trace_scope_table_names.py
        --project_id={gcp_project}`

## Validate and Finalize

*   **Lint Draft HCL and PromQL Queries**: When asked to validate or fix draft
    agent alert configurations (for example, in `draft_invalid_query.tf` or
    `monitoring/alerts.tf`), run `python3 scripts/agent_platform/lint_syntax.py
    <path_to_tf_file>` to detect and auto-correct unbalanced parentheses or
    braces, invalid time window units, missing `gen_ai_agent_name` grouping, and
    invalid `duration` buffers on long-lookback (>25h) queries.

*   **Enforce SQL Alert Constraints**:
    1.  **No manual timestamp filters** or temporal groupings.
    2.  **Group by agent identifier**: Use `cloud.resource_id` (Reasoning Engine
        ID or Cloud Run service) to monitor dynamically. Do NOT filter for
        specific agents unless requested.
    3.  **Aggregate failures**: Group by agent or tool name, calculating the
        ratio of failed requests (status code `2` indicating ERROR) to total
        requests.
    4.  **Use `HAVING` clause** to filter out healthy tools and models.
    5.  **Pinning (Only if explicitly requested)**: Use
        `ENDS_WITH(JSON_VALUE(resource.attributes, '$."cloud.resource_id"'),
        'AGENT_IDENTIFIER')` with a string identifier (for example,
        `'support-bot'`), not numeric, unless instructed. Customize this filter
        only when explicitly requested; otherwise avoid pinning in favor of
        dynamic grouping as described in the main skill instructions.
*   **Configure Duration Buffers (Transient Glitches)**: To avoid alerts firing
    on transient spikes, use duration and retest window buffers appropriately:
    *   **Reliability Metrics (PromQL / Cloud Monitoring)**:
        *   For short-lookback alerts querying data under 25 hours (such as
            `Short-Window Z-Score (1h baseline)`, `Moving Averages`, and Fast
            Burn SLO), ALWAYS use a `duration = "300s"` (5 minutes) buffer to
            filter out transient cold start or deployment spikes.
        *   For long-lookback alerts querying data longer than 25 hours (such as
            `1w Z-Score Baseline`, `Seasonal Decomposition (average 1w and 1d)`,
            and Slow Burn SLO), duration and retest windows are disabled by the
            platform. Do **not set a duration** (omit it entirely).
*   **Explain the Dynamic Baseline Adaptation Blind Spot**: Explain to users
    that dynamic statistical Z-score thresholds compare current rates to a
    moving statistical baseline. If a system degrades slowly over days, the
    standard baseline curve adapts to this slow drift, making standard Z-score
    alerts blind to persistent slow errors. Recommend a hard static threshold
    alert in parallel for strict SLA enforcement.
*   **Prevent Seasonal Decomposition Double Alerting**: Configure seasonal
    decomposition alert policies ONLY to track spikes (for example, latency
    spikes) OR drops, and NEVER use dual-direction evaluations (such as absolute
    deviation). Explain this limitation to the user: when comparing to a
    historical offset (for example, `offset 1w`), the alert policy triggers
    twice if tracking both directions (when the anomaly first occurs, and again
    after 1 week when the anomaly becomes the baseline). To prevent this, the
    generated policy MUST only track either spikes (using `>`) or drops (using
    `<`), avoiding `abs()`.
*   **Handle Script Failures**: If `list_trace_scope_table_names.py` fails
    unexpectedly, verify the project ID and ensure you have permissions to view
    trace scopes and linked datasets.
agent_platform_safety_alert_policies.md 7.0 KB
# Configure Safety Alert Policies

These alert policies help users detect high trigger rates of Model Armor policy
violations in their deployed agents caused by prompt injections, false
positives, or hallucinations.

## Table of Contents

-   [Verify Prerequisites](#verify-prerequisites): Lines 17-71
    -   [Retrieve the Trace Scope Observability Analytics Table](#retrieve-the-trace-scope-observability-analytics-table): Lines 19-25
    -   [Link the BigQuery Dataset](#link-the-bigquery-dataset): Lines 26-71
-   [Follow Critical Rules](#follow-critical-rules): Lines 72-194
    -   [Configure High Model Armor Safety Policy Trigger Rate](#configure-high-model-armor-safety-policy-trigger-rate): Lines 81-194
-   [Run Tooling Scripts](#run-tooling-scripts): Lines 195-202
-   [Validate and Finalize](#validate-and-finalize): Lines 203-209

## Verify Prerequisites

### Retrieve the Trace Scope Observability Analytics Table

Retrieve the Observability Analytics table where all the Trace scope spans are
stored. See the `list_trace_scope_table_names` entry in
[Run Tooling Scripts](#run-tooling-scripts) below for instructions on running
the retrieval tool.

### Link the BigQuery Dataset

A linked BigQuery dataset instance is required to configure alert policies
depending on Observability Analytics trace data. This dataset MUST hold views
for the `_Trace` trace bucket of the target Google Cloud project.

Applicable BigQuery datasets have a `"type": "LINKED"` attribute and reference
the `_Trace` bucket in their description. To list all existing BigQuery datasets
in a project, run the following command:

```bash
bq ls --format=prettyjson --project_id=$PROJECT_ID
```

Where:

*   `PROJECT_ID`: The target Google Cloud project ID.

If the Google Cloud project does not have a linked BigQuery dataset for the
Trace bucket, you MUST EXPLICITLY ask the user for confirmation before
proceeding to create one. If the user does not approve, you MUST skip creating
safety alert policies. Otherwise, create a linked dataset by running the
following command:

```bash
gcloud beta observability buckets datasets links create \
  projects/$PROJECT_ID/locations/$LOCATION/buckets/$BUCKET_ID/datasets/$DATASET_ID/links/$LINK_ID \
 --dataset=$DATASET_ID \
 --bucket=$BUCKET_ID \
 --location=$LOCATION \
 --project=$PROJECT_ID
```

Where:

*   `PROJECT_ID`: The target Google Cloud project ID.
*   `LOCATION`: The location of the observability buckets. If unknown, the
    location is included in the Observability Analytics table name retrieved in
    [Retrieve the Trace Scope Observability Analytics Table](#retrieve-the-trace-scope-observability-analytics-table).
*   `BUCKET_ID`: The ID of the observability bucket. By default, this ID is
    `_Trace`.
*   `DATASET_ID`: The ID of the dataset. By default, the trace data is stored in
    a dataset named `Spans`.
*   `LINK_ID`: The name of the new BigQuery dataset. Use
    `trace_bq_linked_dataset` as the default.

## Follow Critical Rules

*   **Alert policy configuration**: You MUST configure the following Safety
    alerting policy. Proceed to the **Validate and Finalize** section below:
    1.  **High Model Armor Safety Policy Trigger Rate** (15-Minute window)
*   **SQL format**: Configure all Safety alert policies using SQL queries. Do
    **NOT** use any other language such as PromQL or Monitoring Query Language
    (MQL).

### Configure High Model Armor Safety Policy Trigger Rate

#### Define the Safety Telemetry Query

Use this query to configure the alert policy. Replace each variable enclosed in
curly braces (for example, `{placeholder}`) with the corresponding values
provided below:

```sql
WITH
  trace_to_agent AS (
  SELECT
    DISTINCT trace_id,
    JSON_VALUE(resource.attributes, '$."cloud.platform"') AS cloud_platform,
    JSON_VALUE(resource.attributes, '$."cloud.resource_id"') AS agent_id,
    JSON_VALUE(attributes, '$."gen_ai.agent.name"') AS agent_name
  FROM
    `{trace_scope_table_name}`
  WHERE
    JSON_VALUE(resource.attributes, '$."cloud.platform"') = "gcp.agent_engine"
      AND
    JSON_VALUE(resource.attributes, '$."cloud.resource_id"') IS NOT NULL
      AND
    JSON_VALUE(attributes, '$."gen_ai.agent.name"') IS NOT NULL
),
  all_model_armor_spans AS (
  SELECT
    s.*,
    t2a.agent_name,
    t2a.agent_id
  FROM
    `{trace_scope_table_name}` s
  FULL JOIN
    `trace_to_agent` t2a ON s.trace_id = t2a.trace_id
  WHERE
    JSON_VALUE(resource.attributes, '$."service.name"') = "modelarmor"
      AND
    name IN ('Request Path', 'Response Path')
      AND
    t2a.agent_name IS NOT NULL
      AND
    t2a.agent_id IS NOT NULL
)
SELECT
  agent_id,
  agent_name,
  violation,
  JSON_VALUE(attributes, '$."gen_ai.security.policy.id"') AS policy_id,
  COUNT(*) AS trigger_count,
  ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER(PARTITION BY agent_id), 2) AS trigger_rate_percentage
FROM
  `all_model_armor_spans`
  LEFT JOIN
    UNNEST(JSON_VALUE_ARRAY(attributes, '$."gcp.modelarmor.violations"')) AS violation
GROUP BY
  agent_id,
  agent_name,
  violation,
  policy_id
QUALIFY
  violation IS NOT NULL
    AND
  trigger_rate_percentage >= 25
ORDER BY
  trigger_rate_percentage DESC
```

Where:

*   `{trace_scope_table_name}`: The Trace scope Observability Analytics table
    name retrieved in [Verify Prerequisites](#verify-prerequisites).

#### Define Terraform HCL for Safety Alerts

Implement the alert policy resource using a `condition_sql` block with a
`row_count_test` condition:

```terraform
resource "google_monitoring_alert_policy" "high_model_armor_safety_policy_trigger_rate" {
  project      = var.project_id
  display_name = "Agent Safety - High Model Armor Safety Policy Trigger Rate"
  combiner     = "OR"

  conditions {
    display_name = "Agent High Model Armor Safety Policy Trigger Rate Exceeds 25%"
    condition_sql {
      query =  {model_armor_trigger_high_rate_telemetry_query}


      # Run evaluation periodically
      minutes {
        periodicity = 5
      }

      # Test triggers when one or more models violate the threshold (returning rows)
      row_count_test {
        comparison = "COMPARISON_GT"
        threshold  = 0
      }
    }
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-alert-configuration"
  }
}
```

Where:

*   `{model_armor_trigger_high_rate_telemetry_query}`: The SQL alert query
    configured in [Define the Safety Telemetry Query](#define-the-safety-telemetry-query)
    above.

## Run Tooling Scripts

1.  **list_trace_scope_table_names (Fallback)**: Use this script ONLY if
    `gather_agent_info.py` fails to retrieve the associated Trace scope
    Observability Analytics SQL table name:
    *   Command: `python3 scripts/agent_platform/list_trace_scope_table_names.py
        --project_id={gcp_project}`

## Validate and Finalize

*   **Handle Script Failures**: If `list_trace_scope_table_names.py` fails
    unexpectedly, verify the project ID. Ensure you have permissions to list
    trace scopes and linked datasets. If no table is found, verify whether a
    linked BigQuery dataset exists as described in
    [Verify Prerequisites](#verify-prerequisites).
agent_platform_security_alert_policies.md 6.8 KB
# Configure Security Alert Policies

These alert policies help users detect unusually high rates of permission denied
errors in their deployed agents.

## Table of Contents

-   [Verify Prerequisites](#verify-prerequisites): Lines 17-76
    -   [Enable Cloud Audit Logs and Cloud Logging](#enable-cloud-audit-logs-and-cloud-logging): Lines 19-26
    -   [Retrieve the Log Scope Observability Analytics Table](#retrieve-the-log-scope-observability-analytics-table): Lines 27-33
    -   [Link the BigQuery Dataset](#link-the-bigquery-dataset): Lines 34-76
-   [Follow Critical Rules](#follow-critical-rules): Lines 77-182
    -   [Configure High IAM Permission Denied Trigger Rate](#configure-high-iam-permission-denied-trigger-rate): Lines 86-182
-   [Run Tooling Scripts](#run-tooling-scripts): Lines 183-190
-   [Validate and Finalize](#validate-and-finalize): Lines 191-197

## Verify Prerequisites

### Enable Cloud Audit Logs and Cloud Logging

Security alert policies rely on Cloud Audit Logs and Cloud Logging to detect
high trigger rates of IAM permission denied errors. Display a note to the user
letting them know that Cloud Audit Logs and Cloud Logging export must be enabled
for all applicable services that their agent interacts with for Security alert
policies to work.

### Retrieve the Log Scope Observability Analytics Table

Retrieve the Observability Analytics table where all the Cloud Logging entries
are stored. See the `list_log_scope_table_names` entry in
[Run Tooling Scripts](#run-tooling-scripts) below for instructions on running
the retrieval tool.

### Link the BigQuery Dataset

A linked BigQuery dataset instance is required to configure alert policies
depending on Observability Analytics and Cloud Logging data. This dataset MUST
hold views for the `_Default` Cloud Logging bucket of the target Google Cloud
project.

Applicable BigQuery datasets have a `"type": "LINKED"` attribute and reference
the `_Default` bucket in their description. To list all existing BigQuery
datasets in a project, run the following command:

```bash
bq ls --format=prettyjson --project_id=$PROJECT_ID
```

Where:

*   `PROJECT_ID`: The target Google Cloud project ID.

If the Google Cloud project does not have a linked BigQuery dataset for the
Cloud Logging bucket, you MUST EXPLICITLY ask the user for confirmation before
proceeding to create one. If the user does not approve, you MUST skip creating
security alert policies. Otherwise, create a linked Cloud Logging dataset by
running the following command:

```bash
gcloud logging links create $LINK_ID \
  --bucket=$BUCKET_ID \
  --location=$LOCATION \
  --project=$PROJECT_ID
```

Where:

*   `PROJECT_ID`: The target Google Cloud project ID.
*   `LOCATION`: The location of the observability buckets. If unknown, the
    location is included in the Observability Analytics table name retrieved in
    [Retrieve the Log Scope Observability Analytics Table](#retrieve-the-log-scope-observability-analytics-table).
*   `BUCKET_ID`: The ID of the observability bucket. By default, this ID is
    `_Default`.
*   `LINK_ID`: The name of the new BigQuery dataset. Use
    `all_logs_bq_linked_dataset` as the default.

## Follow Critical Rules

*   **Alert policy configuration**: You MUST configure the following Security
    alerting policy. Proceed to the **Validate and Finalize** section below:
    1.  **High IAM Permission Denied Trigger Rate** (15-Minute window)
*   **SQL format**: Configure all Security alert policies using SQL queries. Do
    **NOT** use any other language such as PromQL or Monitoring Query Language
    (MQL).

### Configure High IAM Permission Denied Trigger Rate

#### Define the Security Telemetry Query

Use this query to configure the alert policy. Replace each variable enclosed in
curly braces (for example, `{placeholder}`) with the corresponding values
provided below:

```sql
WITH
  iam_agent_audit_logs AS (
    SELECT
      severity,
      proto_payload.audit_log.status.code AS status_code,
      proto_payload.audit_log.authentication_info.principal_email AS principal_email,
      proto_payload.audit_log.service_name AS service_name,
      proto_payload.audit_log.method_name AS method_name
    FROM
      `{log_scope_table_name}`
    WHERE
      proto_payload.type = "type.googleapis.com/google.cloud.audit.AuditLog"
  )
SELECT
  severity,
  status_code,
  principal_email,
  service_name,
  method_name,
  COUNT(*) AS trigger_count,
  ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER(PARTITION BY principal_email, method_name), 2) AS permission_denied_rate_percentage
FROM
  `iam_agent_audit_logs`
GROUP BY
  severity,
  status_code,
  principal_email,
  service_name,
  method_name
QUALIFY
  severity = "ERROR"
    AND
  status_code = 7
    AND
  principal_email LIKE '%gcp-sa-aiplatform-re.iam.gserviceaccount.com'
    AND
  permission_denied_rate_percentage >= 25
ORDER BY
  permission_denied_rate_percentage DESC
```

Where:

*   `{log_scope_table_name}`: The Observability Analytics table name for the
    Cloud Logging scope retrieved in
    [Verify Prerequisites](#verify-prerequisites).

#### Define Terraform HCL for Security Alerts

Implement the alert policy resource using a `condition_sql` block with a
`row_count_test` condition:

```terraform
resource "google_monitoring_alert_policy" "high_iam_permission_denied_trigger_rate" {
  project      = var.project_id
  display_name = "Agent Security - High IAM Permission Denied Trigger Rate"
  combiner     = "OR"

  conditions {
    display_name = "High IAM Permission Denied Trigger Rate Exceeds 25%"
    condition_sql {
      query =  {iam_high_permission_denied_rate_telemetry_query}

      # Run evaluation periodically
      minutes {
        periodicity = 5
      }

      # Test triggers when one or more models violate the threshold (returning rows)
      row_count_test {
        comparison = "COMPARISON_GT"
        threshold  = 0
      }
    }
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-alert-configuration"
  }
}
```

Where:

*   `{iam_high_permission_denied_rate_telemetry_query}`: The SQL alert query
    configured in [Define the Security Telemetry Query](#define-the-security-telemetry-query)
    above.

## Run Tooling Scripts

1.  **list_log_scope_table_names (Fallback)**: Use this script ONLY if
    `gather_agent_info.py` fails to retrieve the associated Observability
    Analytics SQL table name for the Cloud Logging scope:
    *   Command: `python3 scripts/agent_platform/list_log_scope_table_names.py
        --project_id={gcp_project}`

## Validate and Finalize

*   **Handle Script Failures**: If `list_log_scope_table_names.py` fails
    unexpectedly, verify the project ID. Ensure you have permissions to list
    Cloud Logging scopes and linked datasets. If no table is found, verify
    whether a linked BigQuery dataset exists as described in
    [Verify Prerequisites](#verify-prerequisites).
agent_platform_telemetry_enablement.md 2.6 KB
# Verify and Enable Telemetry

## Configure Required Telemetry Environment Variables

To export evaluation traces, configure the agent's deployment specification with
the following environment variables:

| Environment Variable | Required Value | Description |
| :--- | :--- | :--- |
| `GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY` | `"true"` | Enables Cloud Trace and Cloud Logging export. |
| `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` | `"EVENT_ONLY"`, `"SPAN_AND_EVENT"`, or `"true"` | Captures message payloads for evaluation. |
| `OTEL_SEMCONV_STABILITY_OPT_IN` | `"gen_ai_latest_experimental"` | Opts into Generative AI semantic conventions. |

## Enable Telemetry Using Terraform

Update the `google_vertex_ai_reasoning_engine` resource's `deployment_spec.env`
blocks:

```terraform
resource "google_vertex_ai_reasoning_engine" "my_agent" {
  ...
  spec {
    deployment_spec {
      env {
        name  = "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY"
        value = "true"
      }
      env {
        name  = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"
        value = "EVENT_ONLY"
      }
      env {
        name  = "OTEL_SEMCONV_STABILITY_OPT_IN"
        value = "gen_ai_latest_experimental"
      }
    }
  }
}
```

## Verify Telemetry and Data Generation Dependencies

> [!IMPORTANT]
> Both **Online Monitor** and **Telemetry (Cloud Trace/Logging export)** incur
> separate billing charges. If not pre-approved in the prompt, warn the user
> about the potential billing costs of both **Online Monitor** and **Telemetry
> (Cloud Trace/Logging export)** and ask the user for explicit approval before
> enabling or provisioning them.

Even if telemetry environment variables are configured on the agent, verify
these additional dependencies. Quality metrics do NOT populate, and quality
metrics alert policies and the Online Monitor MUST be skipped if the decision is
to NOT enable the required APIs:

1.  **API Enablement**: Ensure the following APIs are enabled in the Google
    Cloud project:

    *   **Cloud Trace API**: `cloudtrace.googleapis.com` (needed for exporting
        spans)
    *   **Observability API**: `observability.googleapis.com` (needed for trace
        storage and SQL queries by the evaluator)

    *To verify whether they are enabled:*

    ```bash
    gcloud services list --enabled --project="{project_id}" \
      --filter="name:(cloudtrace.googleapis.com observability.googleapis.com)"
    ```

2.  **IAM Permissions**: The service account assigned to the agent (default or
    custom) MUST have the Cloud Trace Agent (`roles/cloudtrace.agent`) and Logs
    Writer (`roles/logging.logWriter`) roles.
attribution.md 1.8 KB
# Usage Attribution

Tag every command you execute directly in the terminal while using this skill,
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:cloud-monitoring-alert-configuration)" \
    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:cloud-monitoring-alert-configuration)` 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:cloud-monitoring-alert-configuration)
    ```

-   **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.
cloud_run_jobs.md 5.3 KB
# Configure Cloud Run Job Alerts

Best-practice observability for scheduled or on-demand Cloud Run Jobs.

## Table of Contents

* [Configure the Fast-Path Job Execution Failure Alert](#configure-the-fast-path-job-execution-failure-alert): Lines 16-25
* [Apply Default Constants and Parameterization](#apply-default-constants-and-parameterization): Lines 26-36
* [Delegate SLOs and Apply the Fallback Rule](#delegate-slos-and-apply-the-fallback-rule): Lines 37-71
* [Configure PromQL and Terraform Policies](#configure-promql-and-terraform-policies): Lines 72-133
  * [Configure the Immediate Job Failure Alert](#configure-the-immediate-job-failure-alert): Lines 74-133
* [Map Telemetry Data Sources](#map-telemetry-data-sources): Lines 134-139

---

## Configure the Fast-Path Job Execution Failure Alert

For Cloud Run Jobs (scheduled cron, on-demand batch processing, or ETL workflows),
every execution failure represents direct user or system impact.

The standard observability strategy for Cloud Run Jobs is to **alert immediately
on any failed job execution (`result="failed"`)**.

---

## Apply Default Constants and Parameterization

All generated Terraform alert policies use explicit default constants. Override
any parameter using HCL variables or prompt instructions:

| Constant / Parameter | Explicit Default | HCL Variable Name | Description & Override Option |
| :--- | :--- | :--- | :--- |
| `single_failure_lookback` | `"15m"` | `var.single_failure_lookback` | Lookback window for detecting single job execution failures. |

---

## Delegate SLOs and Apply the Fallback Rule

**Execution success rate SLOs are owned by the
`google-cloud-slo-alert-configuration` skill.** Delegate to it whenever the user
asks for an SLO, an error budget, or burn-rate alerting on a Cloud Run job. That
skill owns the SLO wizard, the burn-rate templates
(`references/promql_templates.md`), the SLI mapping
(`references/service_metrics.md`), and the App Hub scoping labels
(`references/app_hub_labels.md`).

> [!NOTE] For most Cloud Run Jobs the immediate `result="failed"` alert is the
> correct primary signal. An execution success rate SLO is worth adding **in
> addition** only when the job runs frequently (for example every few minutes) —
> a low-frequency nightly job does not produce enough samples for a meaningful
> error budget.

**Context to hand off** (so the SLO skill does not repeat discovery):

*   **Resource type**: Cloud Run job.
*   **Grouping labels**: `job_name`, `location`.
*   **Execution SLI**: `run_googleapis_com:job_completed_execution_count`; bad =
    `result="failed"`, total = all completed executions.
*   **SLO target**: `0.999` (99.9%) by default; confirm with the user.

Delegate the SLO policies and continue generating the immediate
execution-failure policy from this reference in the same response.

**Fallback** — only if `google-cloud-slo-alert-configuration` is not installed:
this reference intentionally carries **no** burn-rate templates. Say that
execution success rate SLOs require that skill, and continue with the immediate
execution-failure policy. Do **NOT** author burn-rate PromQL here, and never
silently present SLO policies as if this skill owned them.

---

## Configure PromQL and Terraform Policies

### Configure the Immediate Job Failure Alert

Monitors any single execution failure (`result="failed"`). Evaluates with
`duration = "0s"` to page immediately upon task/job failure.

#### Write the PromQL Query

```promql
sum(
  increase(run_googleapis_com:job_completed_execution_count{result="failed", job_name="[JOB_NAME]"}[15m])
) by (job_name, location) > 0
```

#### Define the Terraform Policy

```hcl
variable "monitored_jobs" {
  description = "List of Cloud Run job names to monitor for execution failures"
  type        = list(string)
  default     = ["data-ingest", "nightly-sync"]
}

variable "single_failure_lookback" {
  description = "Lookback window for detecting single execution failures"
  type        = string
  default     = "15m"
}

resource "google_monitoring_alert_policy" "job_execution_failure" {
  for_each     = toset(var.monitored_jobs)
  project      = var.scoping_project_id
  display_name = "[Cloud Run Job] Execution Failure - ${each.value}"
  combiner     = "OR"

  conditions {
    display_name = "Job Execution Failed - ${each.value}"
    condition_prometheus_query_language {
      query = <<-EOT
        sum(
          increase(run_googleapis_com:job_completed_execution_count{result="failed", job_name="${each.value}"}[${var.single_failure_lookback}])
        ) by (job_name, location) > 0
      EOT
      duration = "0s"
    }
  }

  user_labels = {
    severity                    = "critical"
    job                         = each.value
    tier                        = "failure"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

---

## Map Telemetry Data Sources

| Signal Indicator | Native Metric | SRE Strategy |
| :--- | :--- | :--- |
| **Job Execution Failure** | `run.googleapis.com/job/completed_execution_count` | **Immediate Failure Alert**: Alert immediately on any failed execution (`result="failed"`) |
| **Execution Success SLO** | `run.googleapis.com/job/completed_execution_count` | **Delegate to `google-cloud-slo-alert-configuration`**: multi-window burn rate, Fast Burn (1h/5m, 14.4x) & Slow Burn (3d/6h, 1.0x) |
cloud_run_services.md 37.8 KB
# Configure Cloud Run Service Alerts

Best-practice observability for HTTP-triggered Cloud Run Services.

---

## Review the Table of Contents

*   [Apply Fast-Path Defaults](#apply-fast-path-defaults): Lines 26-52
    *   [Generate Core SLO and Instance Saturation Alerts](#generate-core-slo-and-instance-saturation-alerts): Lines 33-42
    *   [Generate Extended Dashboard and Resource Protection Alerts](#generate-extended-dashboard-and-resource-protection-alerts): Lines 43-52
*   [Apply Default Constants and Override Parameters](#apply-default-constants-and-override-parameters): Lines 53-76
*   [Delegate SLOs and Apply Fallback Templates](#delegate-slos-and-apply-fallback-templates): Lines 77-114
*   [Apply PromQL and Terraform Query Templates](#apply-promql-and-terraform-query-templates): Lines 115-888
    *   [Monitor Container Instance Saturation](#monitor-container-instance-saturation): Lines 117-223
    *   [Monitor Container Memory and CPU Utilization (OOM Prevention and Throttling)](#monitor-container-memory-and-cpu-utilization-oom-prevention-and-throttling): Lines 224-341
    *   [Configure Availability SLO Burn Rate Queries](#configure-availability-slo-burn-rate-queries): Lines 342-488
    *   [Configure Request Latency SLO Queries (P95 and P99)](#configure-request-latency-slo-queries-p95-and-p99): Lines 489-596
    *   [Detect Client Error Surges (4xx Response Code Storm)](#detect-client-error-surges-4xx-response-code-storm): Lines 597-666
    *   [Detect Traffic and FinOps Anomalies](#detect-traffic-and-finops-anomalies): Lines 667-876
    *   [Diagnose Cold Start Latency](#diagnose-cold-start-latency): Lines 877-888
*   [Map Telemetry Data Sources](#map-telemetry-data-sources): Lines 889-903

---

## Apply Fast-Path Defaults

> [!IMPORTANT]
> When the user prompt explicitly names the target Cloud Run service, job, or worker pool, do not run any shell commands, directory listings, workspace file searches, or `gcloud` discovery commands. Proceed directly to generating the complete Terraform HCL from the templates in this reference. Every generated `google_monitoring_alert_policy` resource **MUST** include `user_labels` with `created-with-google-skill = "cloud-monitoring-alert-configuration"`.

When standard, recommended, or full alerting policies are requested for a Cloud Run HTTP service (or thresholds are unspecified), **always generate the complete recommended suite** covering **both** the Core SLO and Instance Saturation Suite (Policies 1–7) **and** the Extended Dashboard and Resource Protection Suite (Policies 8–12). Delegate the SLO burn-rate policies (Policies 1–4) to the `google-cloud-slo-alert-configuration` skill when it is installed; generate Policies 1–4 from the local fallback templates in this file only when `google-cloud-slo-alert-configuration` is unavailable (while still surfacing the referral to `google-cloud-slo-alert-configuration` as described in [Delegate SLOs and Apply Fallback Templates](#delegate-slos-and-apply-fallback-templates)):

### Generate Core SLO and Instance Saturation Alerts

1. **Availability SLO (Fast Burn)**: 99.9% target, 1h & 5m windows, $14.4\times$ burn rate, `duration = "300s"` (Critical/Paging).
2. **Availability SLO (Slow Burn)**: 99.9% target, 3d & 6h windows, $1.0\times$ burn rate, **omit `duration`** (Warning/Ticket).
3. **Request Latency SLO (P95)**: Window-based 1h lookback, P95 $\le 500\text{ms}$ in 99% of 5m windows (Warning).
4. **Request Latency SLO (P99)**: Window-based 1h lookback, P99 $\le 1000\text{ms}$ in 99% of 5m windows (Warning).
5. **Instance Saturation (Warning)**: >80% of service `max_instances` ceiling (Warning).
6. **Instance Saturation (Critical)**: $\ge 95\%$ of service `max_instances` ceiling (Critical).
7. **Traffic Drop Anomaly**: 5m throughput drop compared to 1h moving average baseline with min-volume guard (`rate(...[1h]) > 1.0`).

### Generate Extended Dashboard and Resource Protection Alerts

8. **Container Memory Saturation & OOM Risk**: P95 container memory utilization $\ge 90\%$ (Critical - Exit Code 137 prevention).
9. **Container CPU Saturation & Throttling**: P95 container CPU utilization $> 85\%$ (Warning).
10. **Client Error Surge (4xx)**: 4xx response code ratio $> 10\%$ with 5 req/s min-volume guard (Warning).
11. **Billable Instance Time Surge**: 5m billable time rate $> 3\times$ 1h moving average baseline (FinOps Warning).
12. **Traffic Surge Anomaly**: 5m request rate $> 3\times$ 1h moving average baseline with min-volume guard (Warning).

---

## Apply Default Constants and Override Parameters

All generated Terraform alert policies use explicit default constants. Override any parameter using HCL variables or prompt instructions:

| Constant / Parameter | Explicit Default | HCL Variable Name | Description & Override Option |
| :--- | :--- | :--- | :--- |
| `availability_slo_target` | `0.999` (99.9%) | `var.availability_slo_target` | Availability target ratio. Override to 0.99 or 0.9999. |
| `latency_p95_threshold_ms` | `500` (500ms) | `var.latency_p95_threshold_ms` | P95 latency limit in milliseconds. |
| `latency_p99_threshold_ms` | `1000` (1000ms) | `var.latency_p99_threshold_ms` | P99 latency limit in milliseconds. |
| `saturation_warning_ratio` | `0.80` (80%) | `var.saturation_warning_ratio` | Instance saturation warning threshold relative to `max_instances`. |
| `saturation_critical_ratio`| `0.95` (95%) | `var.saturation_critical_ratio` | Instance saturation critical threshold relative to `max_instances`. |
| `memory_saturation_ratio` | `0.90` (90%) | `var.memory_saturation_ratio` | P95 container memory utilization critical limit (OOM prevention). |
| `cpu_saturation_ratio` | `0.85` (85%) | `var.cpu_saturation_ratio` | P95 container CPU utilization warning limit. |
| `client_error_4xx_ratio` | `0.10` (10%) | `var.client_error_4xx_ratio` | Maximum allowable ratio of 4xx client errors. |
| `traffic_drop_ratio` | `0.20` (80% drop) | `var.traffic_drop_ratio` | Throughput drop threshold compared to 1h moving average. |
| `traffic_min_hourly_rate` | `1.0` (1 req/s) | `var.traffic_min_hourly_rate` | Min hourly rate guard to prevent scale-to-zero false alarms. |
| `traffic_surge_multiplier` | `3.0` (3x surge) | `var.traffic_surge_multiplier` | Throughput spike multiplier compared to 1h moving average. |
| `traffic_surge_min_rate` | `15.0` (15 req/s) | `var.traffic_surge_min_rate` | Minimum 5m request rate guard (req/s) to suppress traffic surge false alarms on low volume. |
| `billable_time_surge_multiplier` | `3.0` (3x surge) | `var.billable_time_surge_multiplier` | Billable compute time multiplier compared to 1h moving average. |
| `billable_time_min_rate` | `5.0` (5 s/s) | `var.billable_time_min_rate` | Minimum 5m billable instance-seconds rate guard to prevent FinOps false alarms on low baseline usage. |
| `retest_duration_buffer` | `"300s"` (5m) | `var.retest_duration_buffer` | Retest window for lookbacks $\le 25$h. Omitted for lookbacks $>25$h. |

---

## Delegate SLOs and Apply Fallback Templates

**Availability and latency SLOs are owned by the
`google-cloud-slo-alert-configuration` skill.** Delegate to it whenever the user
asks for an SLO, an error budget, or burn-rate alerting on a Cloud Run service.
That skill owns the SLO wizard, the burn-rate templates
(`references/promql_templates.md`), the SLI mapping
(`references/service_metrics.md`), and the App Hub scoping labels
(`references/app_hub_labels.md`).

**Context to hand off** (so the SLO skill does not repeat discovery):

*   **Resource type**: Cloud Run service (`cloud_run_revision` monitored
    resource).
*   **Grouping labels**: `service_name`, `location` (add `project_id` for
    multi-project scopes).
*   **Availability SLI**: `run_googleapis_com:request_count`; bad =
    `response_code_class="5xx"`.
*   **Latency SLI**: `run_googleapis_com:request_latencies_bucket`; thresholds
    `latency_p95_threshold_ms` / `latency_p99_threshold_ms`.
*   **SLO target**: `availability_slo_target` (default `0.999`).

Delegate the SLO policies and continue generating the remaining golden-signal
policies (saturation, CPU/memory, 4xx, FinOps, traffic) from this reference in
the same response.

**Fallback** — only if `google-cloud-slo-alert-configuration` is not installed:
use the standalone burn-rate templates in this reference, which are a complete
solution on their own. Always keep the `monitored_resource="cloud_run_revision"`
matcher and the min-volume guard shown in
[Configure Availability SLO Burn Rate Queries](#configure-availability-slo-burn-rate-queries)
so idle or scale-to-zero services cannot page. Even then, your response MUST
name `google-cloud-slo-alert-configuration` as the owner of SLO configuration,
state that what you emitted is a local fallback, and list the handoff context
above. Never silently present SLO policies as if this skill owned them.

---

## Apply PromQL and Terraform Query Templates

### Monitor Container Instance Saturation
Monitors when active container instances approach configured scaling ceilings (`max_instances`).
> [!NOTE]
> PromQL queries for `container_instance_count` MUST include the label matcher `monitored_resource="cloud_run_revision"` to prevent API validation errors resulting from metric ambiguity with `cloud_run_worker_pool`.

#### Configure the Warning Query (>80% Capacity)

```promql
sum(
  max_over_time(run_googleapis_com:container_instance_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", state="active"}[5m])
) by (service_name, location) / [SERVICE_MAX_INSTANCES] > 0.80
```

#### Configure the Critical Query (>=95% Capacity)

```promql
sum(
  max_over_time(run_googleapis_com:container_instance_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", state="active"}[5m])
) by (service_name, location) / [SERVICE_MAX_INSTANCES] >= 0.95
```

#### Define the Instance Saturation Terraform Policies

```hcl
variable "cloud_run_services" {
  description = "Map of Cloud Run services to monitor and their max_instances ceilings"
  type = map(object({
    max_instances = number
  }))
  default = {
    "api-gateway" = { max_instances = 1000 }
  }
}

variable "saturation_warning_ratio" {
  description = "Ratio threshold for container instance saturation warning"
  type        = number
  default     = 0.80
}

variable "saturation_critical_ratio" {
  description = "Ratio threshold for container instance saturation critical"
  type        = number
  default     = 0.95
}

resource "google_monitoring_alert_policy" "instance_saturation_warning" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Container Instance Saturation Warning (>80% Limit) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Active Instances Exceed 80% of ${each.key} Ceiling (${each.value.max_instances})"
    condition_prometheus_query_language {
      query = <<-EOT
        sum(
          max_over_time(run_googleapis_com:container_instance_count{monitored_resource="cloud_run_revision", service_name="${each.key}", state="active"}[5m])
        ) by (service_name, location) / ${each.value.max_instances} > ${var.saturation_warning_ratio}
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "saturation"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}

resource "google_monitoring_alert_policy" "instance_saturation_critical" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Container Instance Saturation Critical (>=95% Limit) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Active Instances Exceed 95% of ${each.key} Ceiling (${each.value.max_instances})"
    condition_prometheus_query_language {
      query = <<-EOT
        sum(
          max_over_time(run_googleapis_com:container_instance_count{monitored_resource="cloud_run_revision", service_name="${each.key}", state="active"}[5m])
        ) by (service_name, location) / ${each.value.max_instances} >= ${var.saturation_critical_ratio}
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "critical"
    service                     = each.key
    tier                        = "saturation"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

---

### Monitor Container Memory and CPU Utilization (OOM Prevention and Throttling)

Monitors actual CPU and Memory resource consumption inside container instances.

#### Monitor Container Memory Saturation (OOM Risk)
Triggers when the 95th percentile memory utilization reaches critical levels, preventing container abrupt termination from Linux kernel OOMKilled (exit code 137).

```promql
histogram_quantile(0.95,
  sum(
    rate(run_googleapis_com:container_memory_utilizations_bucket{
      monitored_resource="cloud_run_revision",
      service_name="[SERVICE_NAME]"
    }[5m])
  ) by (le, service_name, location)
) >= 0.90
```

#### Monitor Container CPU Saturation and Throttling
Triggers when the 95th percentile container CPU utilization exceeds 85%, indicating compute starvation or inadequate vCPU sizing.

```promql
histogram_quantile(0.95,
  sum(
    rate(run_googleapis_com:container_cpu_utilizations_bucket{
      monitored_resource="cloud_run_revision",
      service_name="[SERVICE_NAME]"
    }[5m])
  ) by (le, service_name, location)
) > 0.85
```

#### Define the Resource Saturation Terraform Policies

```hcl
variable "memory_saturation_ratio" {
  description = "P95 container memory utilization threshold (OOM danger)"
  type        = number
  default     = 0.90
}

variable "cpu_saturation_ratio" {
  description = "P95 container CPU utilization threshold (throttling danger)"
  type        = number
  default     = 0.85
}

resource "google_monitoring_alert_policy" "container_memory_saturation_critical" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Container Memory Saturation Critical (P95 >= 90% OOM Risk) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "P95 Memory Utilization >= 90% on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        histogram_quantile(0.95,
          sum(
            rate(run_googleapis_com:container_memory_utilizations_bucket{
              monitored_resource = "cloud_run_revision",
              service_name       = "${each.key}"
            }[5m])
          ) by (le, service_name, location)
        ) >= ${var.memory_saturation_ratio}
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "critical"
    service                     = each.key
    tier                        = "saturation"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}

resource "google_monitoring_alert_policy" "container_cpu_saturation_warning" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Container CPU Saturation Warning (P95 > 85%) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "P95 CPU Utilization > 85% on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        histogram_quantile(0.95,
          sum(
            rate(run_googleapis_com:container_cpu_utilizations_bucket{
              monitored_resource = "cloud_run_revision",
              service_name       = "${each.key}"
            }[5m])
          ) by (le, service_name, location)
        ) > ${var.cpu_saturation_ratio}
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "saturation"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

---

### Configure Availability SLO Burn Rate Queries

#### Configure Availability Fast Burn (1h and 5m Windows)

```promql
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", response_code_class="5xx"}[5m])) by (service_name, location)
  /
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location)
  > (1 - [SLO_TARGET]) * 14.4
)
and
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", response_code_class="5xx"}[1h])) by (service_name, location)
  /
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location)
  > (1 - [SLO_TARGET]) * 14.4
)
and
(
  # Min-volume guard: ensure at least 1 req/s to prevent false alerts on scale-to-zero or low-traffic services
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location) > 1.0
)
```

#### Configure Availability Slow Burn (3d and 6h Windows)
> [!WARNING]
> Lookback windows >25h (like `[3d]`) require **omitting `duration`** in HCL.

```promql
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", response_code_class="5xx"}[6h])) by (service_name, location)
  /
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[6h])) by (service_name, location)
  > (1 - [SLO_TARGET]) * 1.0
)
and
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", response_code_class="5xx"}[3d])) by (service_name, location)
  /
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[3d])) by (service_name, location)
  > (1 - [SLO_TARGET]) * 1.0
)
and
(
  # Min-volume guard: ensure at least 1 req/s to prevent false alerts on scale-to-zero or low-traffic services
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[6h])) by (service_name, location) > 1.0
)
```

#### Define the Availability SLO Terraform Policies

```hcl
variable "availability_slo_target" {
  description = "Availability SLO target ratio"
  type        = number
  default     = 0.999
}

resource "google_monitoring_alert_policy" "availability_slo_fast_burn" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Availability SLO Fast Burn (1h/5m 14.4x) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "5xx Error Burn Rate Exceeds 14.4x on ${each.key} (1h and 5m windows)"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}", response_code_class="5xx"}[5m])) by (service_name, location)
          /
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location)
          > (1 - ${var.availability_slo_target}) * 14.4
        )
        and
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}", response_code_class="5xx"}[1h])) by (service_name, location)
          /
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[1h])) by (service_name, location)
          > (1 - ${var.availability_slo_target}) * 14.4
        )
        and
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[1h])) by (service_name, location) > ${var.traffic_min_hourly_rate}
        )
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "critical"
    service                     = each.key
    tier                        = "slo"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}

resource "google_monitoring_alert_policy" "availability_slo_slow_burn" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Availability SLO Slow Burn (3d/6h 1.0x) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "5xx Error Burn Rate Exceeds 1.0x on ${each.key} (3d and 6h windows)"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}", response_code_class="5xx"}[6h])) by (service_name, location)
          /
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[6h])) by (service_name, location)
          > (1 - ${var.availability_slo_target}) * 1.0
        )
        and
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}", response_code_class="5xx"}[3d])) by (service_name, location)
          /
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[3d])) by (service_name, location)
          > (1 - ${var.availability_slo_target}) * 1.0
        )
        and
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[6h])) by (service_name, location) > ${var.traffic_min_hourly_rate}
        )
      EOT
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "slo"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

---

### Configure Request Latency SLO Queries (P95 and P99)

#### Configure the P95 Request Latency SLO

```promql
avg_over_time(
  (
    histogram_quantile(0.95, sum(rate(run_googleapis_com:request_latencies_bucket{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (le, service_name, location)) > [LATENCY_THRESHOLD_MS]
  )[1h:5m]
) > (1 - [WINDOW_SLO_TARGET])
```

#### Configure the P99 Request Latency SLO

```promql
avg_over_time(
  (
    histogram_quantile(0.99, sum(rate(run_googleapis_com:request_latencies_bucket{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (le, service_name, location)) > [LATENCY_THRESHOLD_MS]
  )[1h:5m]
) > (1 - [WINDOW_SLO_TARGET])
```

#### Define the Request Latency SLO Terraform Policies

```hcl
variable "latency_p95_threshold_ms" {
  description = "P95 request latency threshold in milliseconds"
  type        = number
  default     = 500
}

variable "latency_p99_threshold_ms" {
  description = "P99 request latency threshold in milliseconds"
  type        = number
  default     = 1000
}

variable "window_slo_target" {
  description = "Window-based latency SLO target ratio"
  type        = number
  default     = 0.99
}

resource "google_monitoring_alert_policy" "request_latency_slo_p95" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Request Latency P95 SLO (>500ms) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "P95 Latency Exceeds ${var.latency_p95_threshold_ms}ms in >1% of 5m Windows on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        avg_over_time(
          (
            histogram_quantile(0.95, sum(rate(run_googleapis_com:request_latencies_bucket{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (le, service_name, location)) > ${var.latency_p95_threshold_ms}
          )[1h:5m]
        ) > (1 - ${var.window_slo_target})
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "latency"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}

resource "google_monitoring_alert_policy" "request_latency_slo_p99" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Request Latency P99 SLO (>1000ms) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "P99 Latency Exceeds ${var.latency_p99_threshold_ms}ms in >1% of 5m Windows on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        avg_over_time(
          (
            histogram_quantile(0.99, sum(rate(run_googleapis_com:request_latencies_bucket{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (le, service_name, location)) > ${var.latency_p99_threshold_ms}
          )[1h:5m]
        ) > (1 - ${var.window_slo_target})
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "latency"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

---

### Detect Client Error Surges (4xx Response Code Storm)
Detects client authorization failures (401/403) or concurrency rate-limiting (429) across inbound requests.

```promql
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", response_code_class="4xx"}[5m])) by (service_name, location)
  /
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location)
  > [CLIENT_ERROR_RATIO]
)
and
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location) > [MIN_REQ_RATE]
)
```

#### Define the 4xx Client Error Terraform Policy

```hcl
variable "client_error_4xx_ratio" {
  description = "Ratio threshold for 4xx client errors"
  type        = number
  default     = 0.10
}

variable "client_error_min_rate" {
  description = "Minimum request rate (req/s) to guard against low-volume noise"
  type        = number
  default     = 5.0
}

resource "google_monitoring_alert_policy" "client_error_4xx_surge" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Client Error Surge (4xx > 10%) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "4xx Error Ratio Exceeds 10% on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}", response_code_class="4xx"}[5m])) by (service_name, location)
          /
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location)
          > ${var.client_error_4xx_ratio}
        )
        and
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location) > ${var.client_error_min_rate}
        )
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "client_error"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

---

### Detect Traffic and FinOps Anomalies

#### Detect Traffic Drop Anomalies
Detects sudden traffic drops compared to 1h moving average, guarded against scale-to-zero.

```promql
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location)
  /
  (sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location) + 0.001)
) < [DROP_THRESHOLD_RATIO]
and
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location) > [MIN_HOURLY_RATE]
)
```

#### Define the Traffic Drop Terraform Policy

```hcl
variable "traffic_drop_ratio" {
  description = "Ratio threshold compared to 1h average for traffic drop anomaly"
  type        = number
  default     = 0.20 # 80% drop
}

variable "traffic_min_hourly_rate" {
  description = "Minimum hourly request rate (req/s) guard to prevent scale-to-zero false alarms"
  type        = number
  default     = 1.0 # 1 req/s
}

resource "google_monitoring_alert_policy" "traffic_drop_anomaly" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Traffic Drop Anomaly (>80% Drop) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Traffic Dropped >80% Compared to 1h Average on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location)
          /
          (sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[1h])) by (service_name, location) + 0.001)
        ) < ${var.traffic_drop_ratio}
        and
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[1h])) by (service_name, location) > ${var.traffic_min_hourly_rate}
        )
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "traffic"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

#### Detect Traffic Surge Anomalies
Detects sudden volumetric traffic spikes (such as DDoS or unexpected viral load) compared to the 1h moving average baseline (`> 3x` baseline with a minimum rate guard of `> 15 req/s`).

##### Write the Traffic Surge PromQL Query

```promql
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location)
  /
  (sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location) + 0.1)
  > 3.0
)
and
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location) > 15.0
)
```

##### Define the Traffic Surge Terraform Policy

```hcl
variable "traffic_surge_multiplier" {
  description = "Throughput spike multiplier compared to 1h moving average baseline"
  type        = number
  default     = 3.0 # 3x surge
}

variable "traffic_surge_min_rate" {
  description = "Minimum 5m request rate guard (req/s) to suppress false alarms on low volume"
  type        = number
  default     = 15.0 # 15 req/s
}

resource "google_monitoring_alert_policy" "traffic_surge_anomaly" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Traffic Surge Anomaly (>3x Baseline) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Traffic Surged >3x Compared to 1h Average on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location)
          /
          (sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[1h])) by (service_name, location) + 0.1)
          > ${var.traffic_surge_multiplier}
        )
        and
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location) > ${var.traffic_surge_min_rate}
        )
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "traffic"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

#### Detect Billable Instance Time Surges (FinOps Cost Control)
Monitors runaway autoscaling or unoptimized compute consumption by tracking surges in billable container instance time (`> 3x` 1-hour moving average baseline with a minimum billable instance-seconds guard `> 5.0`).

##### Write the Billable Instance Time PromQL Query

```promql
(
  sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location)
  /
  (sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location) + 0.1)
  > 3.0
)
and
(
  sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location) > 5.0
)
```

##### Define the Billable Instance Time Terraform Policy

```hcl
variable "billable_time_surge_multiplier" {
  description = "Billable compute time surge multiplier compared to 1h moving average baseline"
  type        = number
  default     = 3.0 # 3x surge
}

variable "billable_time_min_rate" {
  description = "Minimum 5m billable instance-seconds rate guard to suppress alerts on low baseline usage"
  type        = number
  default     = 5.0 # 5 billable instance-seconds/s
}

resource "google_monitoring_alert_policy" "billable_instance_time_surge" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] FinOps Billable Instance Time Surge (>3x Baseline) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Billable Instance Time >3x Compared to 1h Average on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location)
          /
          (sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="${each.key}"}[1h])) by (service_name, location) + 0.1)
          > ${var.billable_time_surge_multiplier}
        )
        and
        (
          sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location) > ${var.billable_time_min_rate}
        )
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "finops"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

---

### Diagnose Cold Start Latency

```promql
histogram_quantile(0.95,
  sum(
    rate(run_googleapis_com:container_startup_latencies_bucket{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[30m])
  ) by (le, service_name, location)
) > [STARTUP_LATENCY_SECONDS]
```

---

## Map Telemetry Data Sources

| Signal Indicator | Native Metric | SRE Observability Strategy |
| :--- | :--- | :--- |
| **Availability (5xx)** | `run.googleapis.com/request_count` | **SLO Fast Burn (1h/5m) & Slow Burn (3d/6h)** (`response_code_class="5xx"`) |
| **Request Latency (P50/P95/P99)** | `run.googleapis.com/request_latencies` | **SLO P95 & P99 Window Evaluation** (`request_latencies_bucket`) |
| **Performance / Client Errors (4xx)** | `run.googleapis.com/request_count` | **Client Error Spike Alert**: 4xx ratio $> 10\%$ with 5 req/s guard |
| **Container Instance Saturation** | `run.googleapis.com/container/instance_count` | **Scaling Ceiling Warning (0.80) & Critical (0.95)** relative to `max_instances` |
| **Container Memory Utilization** | `run.googleapis.com/container/memory/utilizations` | **OOM Prevention Alert**: P95 memory utilization $\ge 90\%$ (Exit 137 guard) |
| **Container CPU Utilization** | `run.googleapis.com/container/cpu/utilizations` | **Compute Throttling Alert**: P95 CPU utilization $> 85\%$ |
| **Billable Instance Time** | `run.googleapis.com/container/billable_instance_time` | **FinOps Cost Spike Alert**: 5m rate $> 3\times$ 1h moving average baseline |
| **Container CPU Allocation** | `run.googleapis.com/container/cpu/allocation_time` | **Regional vCPU Quota Headroom Monitoring** |
| **Container Memory Allocation** | `run.googleapis.com/container/memory/allocation_time` | **Regional RAM Quota Headroom Monitoring** |
| **Traffic Drop Anomaly** | `run.googleapis.com/request_count` | **Guarded Anomaly Alert**: Drop compared to 1h baseline (`rate(...[1h]) > 1.0`) |
| **Cold Start Latency** | `run.googleapis.com/container/startup_latencies` | **Conditional Diagnostic**: P95 startup latency over 30m window |
cloud_run_worker_pools.md 13.7 KB
# Configure Cloud Run Worker Pool Alerts

Best-practice observability for Cloud Run Worker Pools.

## Table of Contents

* [Apply Fast-Path Defaults](#apply-fast-path-defaults): Lines 21-33
* [Apply Default Constants and Override Parameters](#apply-default-constants-and-override-parameters): Lines 34-47
* [Delegate SLOs and Apply Fallback Templates](#delegate-slos-and-apply-fallback-templates): Lines 48-85
* [Discover Workload Targets](#discover-workload-targets): Lines 86-98
  * [Discover Parameters Autonomously](#discover-parameters-autonomously): Lines 88-98
* [Apply PromQL and Terraform Query Templates](#apply-promql-and-terraform-query-templates): Lines 99-280
  * [Configure Task Success Rate SLO Burn Rate Queries](#configure-task-success-rate-slo-burn-rate-queries): Lines 101-160
  * [Monitor Queue Backlog Drain Time (ETD)](#monitor-queue-backlog-drain-time-etd): Lines 161-230
  * [Monitor Oldest Unacked Message Age](#monitor-oldest-unacked-message-age): Lines 231-238
  * [Configure Health Probe Success Rate SLO Burn Rate Queries](#configure-health-probe-success-rate-slo-burn-rate-queries): Lines 239-280
* [Map Telemetry Data Sources](#map-telemetry-data-sources): Lines 281-288

---

## Apply Fast-Path Defaults
When standard alerting is requested or thresholds are unspecified, **always generate the following 4-policy standard suite**. Delegate the Task Success Rate SLO burn-rate policies (Policies 1–2) to the `google-cloud-slo-alert-configuration` skill when it is installed; generate Policies 1–2 from the local fallback templates in this file only when `google-cloud-slo-alert-configuration` is unavailable (while still surfacing the referral to `google-cloud-slo-alert-configuration` as described in [Delegate SLOs and Apply Fallback Templates](#delegate-slos-and-apply-fallback-templates)):

1. **Task Success Rate SLO (Fast Burn)**: 99.9% target, 1h & 5m windows, $14.4\times$ burn rate, `duration = "300s"` (Critical/Paging).
2. **Task Success Rate SLO (Slow Burn)**: 99.9% target, 3d & 6h windows, $1.0\times$ burn rate, **omit `duration`** (Warning/Ticket).
3. **Queue Backlog Drain Time (ETD)**: Estimated time to drain queue exceeds processing SLA threshold (for example, >30m) with `duration = "300s"` retest buffer (Warning/Paging).
4. **Oldest Unacked Message Age**: Oldest unacknowledged message age exceeds SLA threshold (Critical/Paging).

> [!NOTE]
> Unlike HTTP Services (where container saturation directly causes HTTP 504 errors), Worker Pools operating at `max_instances` are operating at maximum efficiency. As long as Queue Drain Time (ETD) and Message Age remain within SLA, instance saturation is expected and does not trigger alerts.

---

## Apply Default Constants and Override Parameters

All generated Terraform alert policies use explicit default constants. Override any parameter using HCL variables or prompt instructions:

| Constant / Parameter | Explicit Default | HCL Variable Name | Description & Override Option |
| :--- | :--- | :--- | :--- |
| `task_success_slo_target` | `0.999` (99.9%) | `var.task_success_slo_target` | Task processing success rate target. Override to 0.99 or 0.9999. |
| `health_probe_slo_target` | `0.999` (99.9%) | `var.health_probe_slo_target` | Process health probe attempt success target. |
| `max_drain_time_second` | `1800` (30m) | `var.max_drain_time_second` | Maximum allowed Queue Estimated Time to Drain (ETD) SLA. |
| `oldest_message_age_second`| `1800` (30m) | `var.oldest_message_age_second`| Maximum allowed unacknowledged message age SLA. |
| `retest_duration_buffer` | `"300s"` (5m) | `var.retest_duration_buffer` | Retest window for lookbacks $\le 25$h. Omitted for lookbacks $>25$h. |

---

## Delegate SLOs and Apply Fallback Templates

**Task success rate and health probe SLOs are owned by the
`google-cloud-slo-alert-configuration` skill.** Delegate to it whenever the user
asks for an SLO, an error budget, or burn-rate alerting on a worker pool. That
skill owns the SLO wizard, the burn-rate templates
(`references/promql_templates.md`), the SLI mapping
(`references/service_metrics.md`), and the App Hub scoping labels
(`references/app_hub_labels.md`).

**Context to hand off** (so the SLO skill does not repeat discovery):

*   **Resource type**: Cloud Run worker pool (plus the bound Pub/Sub
    subscription, if any).
*   **Grouping labels**: `subscription_id` for queue SLIs; `service_name`,
    `location` for probe SLIs.
*   **Task success SLI**: bad =
    `pubsub_googleapis_com:subscription_nack_requests`, total = nacks +
    `pubsub_googleapis_com:subscription_ack_message_count`.
*   **Health probe SLI**: bad = failed attempts of
    `run_googleapis_com:container_completed_probe_attempt_count`, total = all
    attempts.
*   **SLO target**: `task_success_slo_target` / `health_probe_slo_target`
    (default `0.999`).

Delegate the SLO policies and continue generating the queue-health policies
(Backlog Drain Time / ETD and Oldest Unacked Message Age) from this reference in
the same response.

**Fallback** — only if `google-cloud-slo-alert-configuration` is not installed:
use the standalone burn-rate templates in this reference, which are a complete
solution on their own. Even then, your response MUST name
`google-cloud-slo-alert-configuration` as the owner of SLO configuration, state
that what you emitted is a local fallback, and list the handoff context above.
Never silently present SLO policies as if this skill owned them.

---

## Discover Workload Targets

### Discover Parameters Autonomously
Before proposing alerts, discover worker pool telemetry and queue bindings:

* **Queue Integration (Direct API & Config Scan)**:
  1. **Worker Pool API**: Run `gcloud beta run worker-pools describe [NAME] --format="json"` to inspect container environment variables (`spec.template.spec.containers[].env`) for `PUBSUB_SUBSCRIPTION`, `SUBSCRIPTION_ID`, or `TOPIC_ID`.
  2. **Service Account IAM Binding**: Extract `serviceAccountName` from the worker pool description and run `gcloud pubsub subscriptions list --format="json"` to verify which subscriptions grant `roles/pubsub.subscriber` to that service account.
  3. **Terraform Scan**: Search `.tf` files for `google_pubsub_subscription` resources associated with the worker pool module.
  * *Outcome*: If a Pub/Sub subscription is identified, apply Task Success SLOs, Backlog Drain Time (ETD), and Message Age alerts. If no queue is bound, apply Health Probe Success Rate SLOs.

---

## Apply PromQL and Terraform Query Templates

### Configure Task Success Rate SLO Burn Rate Queries

#### Configure Task Success Fast Burn (1h and 5m Windows)

```promql
(
  (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[5m])) or vector(0))
  /
  (
    (sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="[SUBSCRIPTION_ID]"}[5m])) or vector(0))
    +
    (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[5m])) or vector(0))
    + 0.001
  )
  > (1 - [SLO_TARGET]) * 14.4
)
and
(
  (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[1h])) or vector(0))
  /
  (
    (sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="[SUBSCRIPTION_ID]"}[1h])) or vector(0))
    +
    (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[1h])) or vector(0))
    + 0.001
  )
  > (1 - [SLO_TARGET]) * 14.4
)
```

#### Configure Task Success Slow Burn (3d and 6h Windows)
> [!WARNING]
> Lookback windows >25h (like `[3d]`) require **omitting `duration`** in HCL.

```promql
(
  (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[6h])) or vector(0))
  /
  (
    (sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="[SUBSCRIPTION_ID]"}[6h])) or vector(0))
    +
    (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[6h])) or vector(0))
    + 0.001
  )
  > (1 - [SLO_TARGET]) * 1.0
)
and
(
  (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[3d])) or vector(0))
  /
  (
    (sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="[SUBSCRIPTION_ID]"}[3d])) or vector(0))
    +
    (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[3d])) or vector(0))
    + 0.001
  )
  > (1 - [SLO_TARGET]) * 1.0
)
```

### Monitor Queue Backlog Drain Time (ETD)
Monitors estimated queue drain processing time in seconds.
> [!IMPORTANT]
> PromQL conditions for ETD MUST specify `duration = "300s"` (5-minute retest buffer) in HCL. This buffer absorbs temporary ETD spikes caused by autoscaler scale-up lag during sudden bursty traffic.

#### Write the ETD PromQL Query

```promql
(
  (sum(pubsub_googleapis_com:subscription_num_undelivered_messages{subscription_id="[SUBSCRIPTION_ID]"}) or vector(0))
  /
  clamp_min((sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="[SUBSCRIPTION_ID]"}[5m])) or vector(0)), 0.05)
) > [MAX_DRAIN_TIME_SECONDS]
```

#### Define the ETD Terraform Policy

```hcl
variable "worker_pools_etd" {
  description = "Map of worker pools to subscription IDs and maximum drain time SLAs (in seconds)"
  type = map(object({
    subscription_id       = string
    max_drain_time_second = number
  }))
  default = {
    "order-processor" = {
      subscription_id       = "order-topic-sub"
      max_drain_time_second = 1800 # 30 minutes SLA
    }
  }
}

variable "retest_duration_buffer" {
  description = "Retest duration buffer for lookbacks <= 25h"
  type        = string
  default     = "300s"
}

resource "google_monitoring_alert_policy" "queue_backlog_etd" {
  for_each     = var.worker_pools_etd
  project      = var.scoping_project_id
  display_name = "[Worker Pool] Queue Backlog Estimated Time to Drain (ETD) Exceeded - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Estimated drain time on ${each.value.subscription_id} exceeds ${each.value.max_drain_time_second}s"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          (sum(pubsub_googleapis_com:subscription_num_undelivered_messages{subscription_id="${each.value.subscription_id}"}) or vector(0))
          /
          clamp_min((sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="${each.value.subscription_id}"}[5m])) or vector(0)), 0.05)
        ) > ${each.value.max_drain_time_second}
      EOT
      duration = var.retest_duration_buffer # 5m retest buffer to absorb autoscaling scale-up lag
    }
  }

  user_labels = {
    severity                    = "warning"
    worker                      = each.key
    tier                        = "saturation"
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

### Monitor Oldest Unacked Message Age

```promql
(
  (pubsub_googleapis_com:subscription_oldest_unacked_message_age{subscription_id="[SUBSCRIPTION_ID]"} or vector(0))
) > [AGE_THRESHOLD_SECONDS]
```

### Configure Health Probe Success Rate SLO Burn Rate Queries

#### Configure Health Probe Fast Burn (1h and 5m Windows)

```promql
(
  (sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]", is_healthy="false"}[5m])) or vector(0))
  /
  sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]"}[5m]))
  > (1 - [SLO_TARGET]) * 14.4
)
and
(
  (sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]", is_healthy="false"}[1h])) or vector(0))
  /
  sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]"}[1h]))
  > (1 - [SLO_TARGET]) * 14.4
)
```

#### Configure Health Probe Slow Burn (3d and 6h Windows)
> [!WARNING]
> Lookback windows >25h (like `[3d]`) require **omitting `duration`** in HCL.

```promql
(
  (sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]", is_healthy="false"}[6h])) or vector(0))
  /
  sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]"}[6h]))
  > (1 - [SLO_TARGET]) * 1.0
)
and
(
  (sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]", is_healthy="false"}[3d])) or vector(0))
  /
  sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]"}[3d]))
  > (1 - [SLO_TARGET]) * 1.0
)
```

---

## Map Telemetry Data Sources

| Signal Indicator | Native Metric | SRE Strategy |
| :--- | :--- | :--- |
| **Task Availability** | `pubsub.googleapis.com/subscription/nack_message_count` | **SLO Skill (`google-cloud-slo-alert-configuration`)**: Fast Burn (1h/5m) & Slow Burn (3d/6h) |
| **Process Health SLO** | `run.googleapis.com/container/completed_probe_attempt_count` | **SLO Skill (`google-cloud-slo-alert-configuration`)**: Probe Failure Ratio (`is_healthy="false"`) Fast & Slow Burn |
| **Queue Backlog ETD** | `pubsub.googleapis.com/subscription/num_undelivered_messages` & `pubsub.googleapis.com/subscription/ack_message_count` | **Estimated Time to Drain (ETD)**: Drain time > SLA threshold with `duration = "300s"` retest buffer |
| **Message Age** | `pubsub.googleapis.com/subscription/oldest_unacked_message_age` | **Threshold Alert**: Message age > SLA limit (for example, 30m) |
compute_engine_alerts.md 40.4 KB
# Configure Compute Engine and AI Hypercomputer Alerts

Configure observability and alerting policies for Google Cloud Compute Engine VMs, Managed Instance Groups (MIGs), and AI Hypercomputer GPU and TPU reservations using Terraform and PromQL.

## Table of Contents

* [Discover Resource Parameters and Schemas](#discover-resource-parameters-and-schemas): Lines 28-49
* [Monitor Core Compute Engine VM Golden Signals](#monitor-core-compute-engine-vm-golden-signals): Lines 50-130
  * [Monitor Hypervisor CPU Utilization](#monitor-hypervisor-cpu-utilization): Lines 52-63
  * [Monitor Guest OS Memory Saturation](#monitor-guest-os-memory-saturation): Lines 64-79
  * [Monitor Mounted Filesystem Disk Space](#monitor-mounted-filesystem-disk-space): Lines 80-102
  * [Monitor Persistent Disk and Hyperdisk I/O Throttling](#monitor-persistent-disk-and-hyperdisk-io-throttling): Lines 103-115
  * [Monitor Network Egress, Packet Drops, and MIG Saturation](#monitor-network-egress-packet-drops-and-mig-saturation): Lines 116-130
* [Configure Host and Reservation Maintenance Alerts](#configure-host-and-reservation-maintenance-alerts): Lines 131-215
  * [Differentiate Planned, Emergent, and Combined Maintenance](#differentiate-planned-emergent-and-combined-maintenance): Lines 156-194
  * [Filter Maintenance Lifecycle Events](#filter-maintenance-lifecycle-events): Lines 195-215
* [Monitor VM Availability and Interruption Reports](#monitor-vm-availability-and-interruption-reports): Lines 216-265
  * [Detect Stopped VMs with Absent Uptime Conditions](#detect-stopped-vms-with-absent-uptime-conditions): Lines 218-223
  * [Alert on VM Interruption Count Metrics](#alert-on-vm-interruption-count-metrics): Lines 224-241
  * [Diagnose Interruptions with Interruption Report Logs](#diagnose-interruptions-with-interruption-report-logs): Lines 242-265
* [Configure GPU XID Health Insights Alerts](#configure-gpu-xid-health-insights-alerts): Lines 266-287
* [Monitor Machine, Sub-Block, and Fabric Health](#monitor-machine-sub-block-and-fabric-health): Lines 288-328
  * [Query Machine and Fabric Health Metrics](#query-machine-and-fabric-health-metrics): Lines 301-326
  * [Compare Current Metrics with Evolving Domain Signals](#compare-current-metrics-with-evolving-domain-signals): Lines 327-328

---

## Discover Resource Parameters and Schemas

Before finalizing alert thresholds, label matchers, or Terraform variables, ground all Compute Engine resource identifiers, hardware families, and capacity ceilings in actual resource configuration rather than guesswork:

* **Determine When to Execute or Parameterize**:
  * If a required parameter (such as `machine_type`, numeric `instance_id` versus `instance_name`, disk `device_name`, `storage_type`, `provisionedIops`, or `provisionedThroughput`, network egress bandwidth tier `totalEgressBandwidthTier`, MIG `max_replicas` or `location`, reservation `enableEmergentMaintenance`, `block_id`, or `subblock_id`, or Cloud Logging `_Default` bucket `retentionDays`) is **already supplied in the user prompt**, use the provided value directly.
  * If any parameter is **not specified** and live Google Cloud credentials are available, look it up using the CLI and API commands below. Always include the relevant lookup commands in your operational explanation so operators can verify or populate their Terraform variables.
  * **Guardrail**: Do **not** search the local workspace for unrelated `.tf` files or external modules. Always validate generated PromQL queries with `python3 scripts/lint_promql.py '<PROMQL_QUERY>'`.

| Alert Domain | Parameters to Look Up | CLI and Script Lookup Commands | REST API Field or Endpoint |
| :--- | :--- | :--- | :--- |
| **Metric Schema and PromQL Validation** | Exact PromQL metric name, `unit`, `metricKind`, `valueType`, resource and metric labels | `python3 scripts/discover_metric_schema.py --project <PROJECT_ID> --resource-type gce_instance` (or `gce_instance_group`, `compute.googleapis.com/Machine`) and `python3 scripts/lint_promql.py '<PROMQL_QUERY>'` | `GET monitoring.googleapis.com/v3/projects/{project}/metricDescriptors` |
| **VM Identity and Machine Family** | Numeric `instance_id` (`id`), string `instance_name` (`name`), `zone`, `machineType` (`e2-*` versus `n2`, `c2`, `c3`, `m2`, `a3`, or `a4`) | `gcloud compute instances list --project=<PROJECT_ID> --format="table(id,name,zone.basename(),machineType.basename(),status)"` | `instances.get` $\rightarrow$ `id`, `name`, `zone`, `machineType` |
| **Guest OS and Cloud Ops Agent** | Guest OS license (`cos-cloud` versus Linux or Windows), Ops Agent metadata (`enable-osconfig`), active `agent.googleapis.com/*` time series | `gcloud compute instances describe <INSTANCE_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(machineType,disks[].licenses,metadata.items)"` and `python3 scripts/discover_metric_schema.py --project <PROJECT_ID> --resource-type gce_instance --metric-prefix agent.googleapis.com/` | `instances.get` $\rightarrow$ `disks[].licenses[]`, `metadata.items[]`; `projects.timeSeries.list` |
| **Persistent Disk and Hyperdisk Caps** | Attached `device_name` (`deviceName`), `storage_type` (`type`), `sizeGb`, `provisionedIops`, `provisionedThroughput` | `gcloud compute instances describe <INSTANCE_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="table(disks[].deviceName,disks[].source.basename(),disks[].type,disks[].interface)"` and `gcloud compute disks list --project=<PROJECT_ID> --format="table(name,zone.basename(),type.basename(),sizeGb,provisionedIops,provisionedThroughput)"` | `instances.get` $\rightarrow$ `disks[].deviceName`; `disks.get` $\rightarrow$ `type`, `sizeGb`, `provisionedIops`, `provisionedThroughput` |
| **Network Egress Bandwidth Cap** | Machine family vCPU count (`guestCpus`), `nicType` (`GVNIC`), `totalEgressBandwidthTier` (`TIER_1` versus `DEFAULT`) | `gcloud compute instances describe <INSTANCE_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(machineType,networkPerformanceConfig.totalEgressBandwidthTier,networkInterfaces[].nicType)"` and `gcloud compute machine-types describe <MACHINE_TYPE> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(name,guestCpus)"` | `instances.get` $\rightarrow$ `networkPerformanceConfig.totalEgressBandwidthTier`; `machineTypes.get` $\rightarrow$ `guestCpus` |
| **MIG Autoscaler Ceiling** | `instance_group_name`, `location` (zone or region), `max_replicas` (`maxNumReplicas`), `minNumReplicas`, `targetSize` | `gcloud compute instance-groups managed list --project=<PROJECT_ID> --format="table(name,location(),targetSize,autoscaler.autoscalingPolicy.maxNumReplicas,autoscaler.autoscalingPolicy.mode)"` and `gcloud compute autoscalers list --project=<PROJECT_ID> --format="table(name,target.basename(),autoscalingPolicy.maxNumReplicas)"` | `instanceGroupManagers.get` / `regionInstanceGroupManagers.get` $\rightarrow$ `status.autoscaler`; `autoscalers.get` $\rightarrow$ `autoscalingPolicy.maxNumReplicas` |
| **Reservations, Blocks, Sub-Blocks, and Maintenance Types** | `reservation_id`, `enableEmergentMaintenance`, maintenance `type` (`scheduled`, `unscheduled`, or `multiple`), `block_id`, `subblock_id`, `cluster_id`, `subblockHealthInfo` | `gcloud compute reservations describe <RESERVATION_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(id,name,enableEmergentMaintenance,specificReservation,resourceStatus)"`; `gcloud compute reservations blocks list <RESERVATION_NAME> --zone=<ZONE> --project=<PROJECT_ID>`; `gcloud compute reservations sub-blocks list <RESERVATION_NAME> --block-name=<BLOCK_NAME> --zone=<ZONE> --project=<PROJECT_ID>` | `reservations.get`, `reservationBlocks.list`/`get`, `reservationSubBlocks.list`/`get` (`--full-view=SUB_BLOCK_VIEW_FULL`) |
| **Cloud Logging Bucket Retention and Reports** | `_Default` log bucket `retentionDays` ($\ge 3$ days required for 72h diagnosis), active interruption and XID logs | `gcloud logging buckets describe _Default --location=global --project=<PROJECT_ID> --format="value(retentionDays)"` and `gcloud logging read 'resource.type="gce_instance" AND (log_id("compute.googleapis.com/interruption_report") OR log_id("compute.googleapis.com/gpu_health_insights_report"))' --project=<PROJECT_ID> --limit=5` | `logging.googleapis.com/v2/projects/{project}/locations/global/buckets/_Default` $\rightarrow$ `retentionDays` |

---

## Monitor Core Compute Engine VM Golden Signals

### Monitor Hypervisor CPU Utilization
* **PromQL Metric**: `compute_googleapis_com:instance_cpu_utilization` (`monitored_resource="gce_instance"`)
* **Scale**: Fractional `0.0` to `1.0` (`unit = "10^2.%"`). Set threshold to `> 0.85` for 85%.
* **Parameter and Resource Lookups**:
  * Look up numeric `instance_id` (`id`), human-readable `instance_name` (`name`), `zone`, and `machineType` (including shared-core `e2-micro`, `e2-small`, and `e2-medium` bursting behavior versus dedicated vCPUs) by running:
    `gcloud compute instances list --project=<PROJECT_ID> --format="table(id,name,zone.basename(),machineType.basename(),status)"`
  * Verify metric descriptor unit and labels by running:
    `python3 scripts/discover_metric_schema.py --project <PROJECT_ID> --resource-type gce_instance --metric-prefix compute.googleapis.com/instance/cpu/`
* **Grouping and Filtering Rules**:
  * Always aggregate with `avg by (instance_id, instance_name, zone)` or `avg_over_time(...[5m])` — **never** flat-sum CPU percentages across instances (`sum(...)`).
  * Filter human-readable VM names using `instance_name` or `metadata_system_name` (never assign a string hostname to numeric `instance_id`).

### Monitor Guest OS Memory Saturation

* **Prerequisite and Cost Guardrail (MUST Explain)**: You **must** explain that native hypervisor memory metrics (`compute.googleapis.com/instance/memory/balloon/ram_used`) are **only available for E2 family VMs**. For N2, C2, C3, M2, A3, and A4 VMs, the **Cloud Ops Agent** must be installed on the VM to emit `agent.googleapis.com/memory/percent_used`, and you **must explicitly state that the Cloud Ops Agent incurs Cloud Monitoring metric ingestion charges** (see [Cloud Monitoring pricing](https://cloud.google.com/products/observability/pricing)).
* **Parameter and Resource Lookups**:
  * **Machine Type Lookup**: Verify whether target VMs belong to the `e2-*` series or non-E2 series (`n2-*`, `c2-*`, `c3-*`, `m2-*`, `a3-*`, `a4-*`) by running:
    `gcloud compute instances describe <INSTANCE_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="value(machineType.basename())"`
  * **Ops Agent Telemetry Verification**: Verify whether the Cloud Ops Agent is installed and actively reporting `agent.googleapis.com/memory/percent_used` in the project by running:
    ```bash
    python3 scripts/discover_metric_schema.py \
      --project <PROJECT_ID> \
      --resource-type gce_instance \
      --metric-prefix agent.googleapis.com/memory/
    ```
* **PromQL Query**:
  ```promql
  avg by (instance_id, zone) (
    agent_googleapis_com:memory_percent_used{monitored_resource="gce_instance", state="used"}
  ) >= 90
  ```
  *Alternatively, sum non-free states: `sum by (instance_id, zone) (agent_googleapis_com:memory_percent_used{monitored_resource="gce_instance", state!="free"}) >= 90`. Never sum across all states, which always equals 100%.*

### Monitor Mounted Filesystem Disk Space

* **Prerequisite and Cost Guardrail (MUST Explain)**: You **must** explain that standard hypervisor `compute.googleapis.com/instance/disk/*` metrics only measure block-level I/O (bytes and IOPS), not mounted filesystem fullness (`ENOSPC`). Monitoring mounted disk space requires the **Cloud Ops Agent** (`agent.googleapis.com/disk/*`, which **incurs Cloud Monitoring metric ingestion charges**; see [Cloud Monitoring pricing](https://cloud.google.com/products/observability/pricing)) or Container-Optimized OS guest metrics (`compute.googleapis.com/guest/disk/bytes_used`).
* **Parameter and Resource Lookups**:
  * **Guest OS Image and Device Lookup**: Inspect the boot and data disk OS license (to distinguish `cos-cloud` Container-Optimized OS from standard Linux or Windows) and attached block `deviceName` values by running:
    `gcloud compute instances describe <INSTANCE_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(disks[].deviceName,disks[].licenses,metadata.items)"`
  * **Active Filesystem Metric and `device` Label Discovery**: Verify active `agent.googleapis.com/disk/percent_used` or `compute.googleapis.com/guest/disk/bytes_used` series and mounted `device` labels by running:
    `python3 scripts/discover_metric_schema.py --project <PROJECT_ID> --resource-type gce_instance --metric-prefix agent.googleapis.com/disk/`
* **PromQL Queries**:
  * **Static Threshold (>85%)**:
    ```promql
    max by (instance_id, device, zone) (
      agent_googleapis_com:disk_percent_used{monitored_resource="gce_instance", state="used", device!~"loop.*|tmpfs|squashfs"}
    ) > 85
    ```
  * **4-Day Linear Exhaustion Forecast**:
    ```promql
    predict_linear(
      agent_googleapis_com:disk_bytes_used{monitored_resource="gce_instance", state="free"}[6h:5m],
      4 * 24 * 3600
    ) < 0
    ```

### Monitor Persistent Disk and Hyperdisk I/O Throttling
* **Metrics (`monitored_resource="gce_instance"`)**:
  * Throttled IOPS: `compute_googleapis_com:instance_disk_throttled_read_ops_count`, `compute_googleapis_com:instance_disk_throttled_write_ops_count`
  * Throttled Throughput: `compute_googleapis_com:instance_disk_throttled_read_bytes_count`, `compute_googleapis_com:instance_disk_throttled_write_bytes_count`
  * Total IOPS, Throughput, and Latency: `compute_googleapis_com:instance_disk_read_ops_count`, `compute_googleapis_com:instance_disk_write_ops_count`, `compute_googleapis_com:instance_disk_read_bytes_count`, `compute_googleapis_com:instance_disk_write_bytes_count`, `compute_googleapis_com:instance_disk_average_io_latency`
* **Parameter and Resource Lookups**:
  * **Disk Type and Provisioned IOPS or Throughput Lookup**: Look up each disk's `type` (`pd-balanced`, `pd-ssd`, `pd-extreme`, `hyperdisk-balanced`, `hyperdisk-extreme`, `hyperdisk-throughput`, `hyperdisk-ml`), `sizeGb`, `provisionedIops`, and `provisionedThroughput` by running:
    `gcloud compute disks list --project=<PROJECT_ID> --format="table(name,zone.basename(),type.basename(),sizeGb,provisionedIops,provisionedThroughput)"`
    `gcloud compute disks describe <DISK_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(name,type,sizeGb,provisionedIops,provisionedThroughput)"`
  * **VM `device_name` Mapping**: Resolve how each disk maps to the `device_name` and `storage_type` metric labels on the VM by running:
    `gcloud compute instances describe <INSTANCE_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="table(disks[].deviceName,disks[].source.basename(),disks[].type,disks[].interface)"`
* **Rule**: Wrap `DELTA` counters in `rate(...[5m])`, group by `(instance_id, instance_name, device_name, storage_type, zone)`, and use `duration = "300s"` to filter out sub-second micro-burst throttling.

### Monitor Network Egress, Packet Drops, and MIG Saturation
* **Parameter and Resource Lookups**:
  * **Per-VM Network Egress Bandwidth Ceiling Lookup**: Because Compute Engine egress bandwidth limits depend on machine family, vCPU count (`2 Gbps` per vCPU up to the machine-series standard cap), and whether `TIER_1` high-bandwidth networking on `GVNIC` is enabled, look up the VM's networking tier and vCPU count before setting static bytes-per-second thresholds:
    `gcloud compute instances describe <INSTANCE_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(machineType,networkPerformanceConfig.totalEgressBandwidthTier,networkInterfaces[].nicType)"`
    `gcloud compute machine-types describe <MACHINE_TYPE> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(name,guestCpus)"`
    *Convert the resolved Gbps limit to bytes per second using $\text{Gbps} \times 125{,}000{,}000$ and set the alert threshold at 80–85% of the ceiling; use `125000000` (1 Gbps) as a baseline when unspecified.*
  * **MIG `max_replicas` and Location Lookup**: Look up the Managed Instance Group's `name` (`instance_group_name`), `location` (zone for zonal MIGs or region for regional MIGs), `targetSize`, and autoscaler ceiling (`autoscaler.autoscalingPolicy.maxNumReplicas`) by running:
    `gcloud compute instance-groups managed list --project=<PROJECT_ID> --format="table(name,location(),targetSize,autoscaler.autoscalingPolicy.maxNumReplicas,autoscaler.autoscalingPolicy.minNumReplicas,autoscaler.autoscalingPolicy.mode)"`
    `gcloud compute instance-groups managed describe <MIG_NAME> [--zone=<ZONE> | --region=<REGION>] --project=<PROJECT_ID> --format="yaml(name,targetSize,status.autoscaler,autoscaler.autoscalingPolicy)"`
* **Network Egress Bandwidth**: `sum by (instance_id, instance_name, zone) (rate(compute_googleapis_com:instance_network_sent_bytes_count{monitored_resource="gce_instance"}[5m])) > 125000000` (1 Gbps = 125 MB/s; scale to 80–85% of the looked-up machine-type or `TIER_1` bandwidth cap).
* **Packet Drops**: `compute_googleapis_com:firewall_dropped_packets_count` (VPC firewall drops) and `agent_googleapis_com:interface_errors` (Ops Agent guest NIC RX/TX errors).
* **MIG Capacity Saturation**: Compare `compute_googleapis_com:instance_group_size{monitored_resource="gce_instance_group"}` (or `autoscaler_googleapis_com:capacity`) by `(instance_group_name, location)` against `max_replicas` (`autoscalingPolicy.maxNumReplicas`) at Warning (`> 0.80`) and Critical (`>= 0.95`).

---

## Configure Host and Reservation Maintenance Alerts

For Compute Engine VMs and AI Hypercomputer GPU and TPU reservations (`A3`, `A3 Ultra`, `A4`, `A4X`, `A4X Max`), configure log-based alerting policies (`google_monitoring_alert_policy` with `condition_matched_log` or `google_logging_metric`) to track scheduled, started, and completed maintenance and repair events—including differentiating **Planned maintenance (`type=scheduled`)**, **Emergent maintenance (`type=unscheduled`)**, and **Combined planned and emergent maintenance (`type=multiple`)**.

* **Parameter and Topology Lookups**:
  * **Reservation, Maintenance `type`, and `enableEmergentMaintenance` Lookup**: Inspect reservation names, machine types, `enableEmergentMaintenance` status, and `resourceStatus.reservationMaintenance` (`upcomingGroupMaintenance.type`, `upcomingGroupMaintenance.maintenanceReasons`, `windowStartTime`, `windowEndTime`) by running:
    `gcloud compute reservations list --project=<PROJECT_ID> --format="table(name,zone.basename(),specificReservation.instanceProperties.machineType,specificReservation.count,enableEmergentMaintenance)"`
    `gcloud compute reservations describe <RESERVATION_NAME> --zone=<ZONE> --project=<PROJECT_ID> --flatten=resourceStatus.reservationMaintenance`
    *REST API: `GET https://compute.googleapis.com/compute/v1/projects/{project}/aggregated/reservations?fields=items.name,items.specificReservation.instanceProperties.machineType,items.enableEmergentMaintenance,items.resourceStatus.reservationMaintenance`*
  * **Reservation Block and Sub-Block Topology Lookup**: Discover block and sub-block names, IDs, `upcomingGroupMaintenance.type`, and pending or ongoing maintenance counts by running:
    `gcloud compute reservations blocks list <RESERVATION_NAME> --zone=<ZONE> --project=<PROJECT_ID>`
    `gcloud compute reservations blocks describe <RESERVATION_NAME> --block-name=<BLOCK_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(id,name,reservationBlockMaintenance)"`
    `gcloud compute reservations sub-blocks list <RESERVATION_NAME> --block-name=<BLOCK_NAME> --zone=<ZONE> --project=<PROJECT_ID>`
    `gcloud compute reservations sub-blocks describe <RESERVATION_NAME> --block-name=<BLOCK_NAME> --sub-block-name=<SUB_BLOCK_NAME> --zone=<ZONE> --full-view=SUB_BLOCK_VIEW_FULL --project=<PROJECT_ID>`
  * **VM Instance Maintenance `type` Lookup**: Inspect individual VM upcoming maintenance metadata (`resourceStatus.upcomingMaintenance.type`) by running:
    `gcloud compute instances describe <INSTANCE_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(resourceStatus.upcomingMaintenance)"`
    *Or query from inside the Guest OS using `curl "http://metadata.google.internal/computeMetadata/v1/instance/upcoming-maintenance?alt=json" -H "Metadata-Flavor: Google"`.*

> [!TIP]
> * **7-Day Advance Notice (`enableEmergentMaintenance`)**: Recommend enabling hardware emergency maintenance notifications (`gcloud compute reservations update RESERVATION_NAME --enable-emergent-maintenance --zone=ZONE` or `enableEmergentMaintenance: true` in REST) to increase advance notice from a few hours to **at least 7 days** for unplanned host repairs. Wait for explicit user confirmation before executing `gcloud compute reservations update`.
> * **Maintenance Reasons (`upcomingGroupMaintenance.maintenanceReasons` / `protoPayload.metadata.maintenanceReasons`)**:
>   * **Planned**: `PLANNED_UPDATE`, `PLANNED_NETWORK_UPDATE`, `FAILURE_GPU_CUSTOMER_REPORTED` (after faulty host report).
>   * **Unplanned or Emergency**: `FAILURE_GPU`, `FAILURE_GPU_XID`, `FAILURE_GPU_TEMPERATURE`, `FAILURE_NVLINK`, `FAILURE_DISK`, `FAILURE_MEMORY`, `FAILURE_INTERFACE`, `FAILURE_NETWORK`, `FAILURE_INFRA`.
> * **Proactive Manual Maintenance**: Operators can proactively trigger maintenance before the scheduled window using `gcloud compute reservations perform-maintenance`, `gcloud compute reservations blocks perform-maintenance`, or `gcloud compute reservations sub-blocks perform-maintenance` with `--scope=all|running|unused`. Never execute `perform-maintenance` commands without explicit user confirmation.

### Differentiate Planned, Emergent, and Combined Maintenance

Maintenance notification metadata includes a **`type`** field that distinguishes routine planned maintenance from urgent hardware or emergent maintenance:
* **Cloud Audit Logs (`cloudaudit.googleapis.com/system_event`)**: Populated at **`protoPayload.metadata.type`** (flat top-level key inside `protoPayload.metadata` on `compute.instances.upcomingMaintenance`, `compute.reservations.upcomingGroupMaintenance`, `compute.reservations.block.upcomingGroupMaintenance`, and `compute.reservations.subBlock.upcomingGroupMaintenance`).
* **Compute Engine API and Guest Metadata**: Populated at `resourceStatus.upcomingMaintenance.type` (VM instances) and `upcomingGroupMaintenance.type` (reservations, blocks, and sub-blocks).

| Metadata `type` Value | Maintenance Category | Description and Alert Routing Strategy |
| :--- | :--- | :--- |
| **`scheduled`** (`"SCHEDULED"`) | **Planned Maintenance** | Routine infrastructure or network updates (`PLANNED_UPDATE`, `PLANNED_NETWORK_UPDATE`, or `FAILURE_GPU_CUSTOMER_REPORTED`) scheduled with standard advance notice (7+ days). Route to **Warning or ticket** channels so operators can plan a maintenance window or run `perform-maintenance` proactively. |
| **`unscheduled`** (`"UNSCHEDULED"`) | **Emergent Maintenance** | Urgent, unplanned host hardware or critical security repairs (`FAILURE_GPU`, `FAILURE_GPU_XID`, `FAILURE_GPU_TEMPERATURE`, `FAILURE_NVLINK`, `FAILURE_DISK`, `FAILURE_MEMORY`, `FAILURE_INTERFACE`, `FAILURE_NETWORK`, `FAILURE_INFRA`). Route to **Critical or paging** channels so operators can checkpoint jobs and drain or repair affected capacity. |
| **`multiple`** (`"MULTIPLE"`) | **Combination of Planned and Emergent Maintenance** | Indicates that **both planned (`scheduled`) and emergent (`unscheduled`) maintenance events** are pending concurrently within the same group window (emitted on **Reservations, Reservation Blocks, and Sub-Blocks**). **Always include `type=multiple` (`"MULTIPLE"`) alongside `type=unscheduled` (`"UNSCHEDULED"`) in Emergent Maintenance alerts** so an existing planned maintenance window never masks a newly scheduled urgent hardware repair. |

> [!IMPORTANT]
> **Avoid Filtering Emergent or Multiple Alerts by `protoPayload.status.message =~ "scheduled"`**: For `UNSCHEDULED` and `MULTIPLE` group maintenance events on reservation blocks and sub-blocks, `protoPayload.status.message` reads `"Urgent maintenance is required..."` or `"Multiple maintenance events are required..."` (which does **not** contain the word `"scheduled"`). When differentiating Planned versus Emergent maintenance, filter directly on **`protoPayload.metadata.type`** (using case-insensitive regex `protoPayload.metadata.type =~ "(?i)^scheduled$"` or exact uppercase enum `protoPayload.metadata.type="SCHEDULED"`, `"UNSCHEDULED"`, `"MULTIPLE"`), optionally paired with `protoPayload.metadata.maintenanceStatus="PENDING"` to alert only when a window is pending rather than ongoing.

#### Filter Log-Based Alerts by Maintenance Type

1. **Planned Maintenance Alert (`type=scheduled` / `"SCHEDULED"`)**:
   ```text
   protoPayload.methodName=~"^compute\.(instances\.upcomingMaintenance|reservations\.(block\.|subBlock\.)?upcomingGroupMaintenance)$" AND severity>=DEFAULT AND protoPayload.metadata.type=~"(?i)^scheduled$"
   ```
   *Or exact match: `protoPayload.metadata.type="SCHEDULED"`.*
2. **Emergent Maintenance Alert (`type=unscheduled` / `"UNSCHEDULED"` and `type=multiple` / `"MULTIPLE"`)**:
   * **Emergent Only (`type=unscheduled`)**:
     ```text
     protoPayload.methodName=~"^compute\.(instances\.upcomingMaintenance|reservations\.(block\.|subBlock\.)?upcomingGroupMaintenance)$" AND severity>=DEFAULT AND protoPayload.metadata.type=~"(?i)^unscheduled$"
     ```
     *Or exact match: `protoPayload.metadata.type="UNSCHEDULED"`.*
   * **Emergent and Combined Planned/Emergent (`type=unscheduled` OR `type=multiple` — Recommended for Paging on Any Urgent Repair)**:
     ```text
     protoPayload.methodName=~"^compute\.(instances\.upcomingMaintenance|reservations\.(block\.|subBlock\.)?upcomingGroupMaintenance)$" AND severity>=DEFAULT AND protoPayload.metadata.type=~"(?i)^(unscheduled|multiple)$"
     ```
     *Or exact match: `(protoPayload.metadata.type="UNSCHEDULED" OR protoPayload.metadata.type="MULTIPLE")`.*
3. **Combination of Planned and Emergent Maintenance Alert (`type=multiple` / `"MULTIPLE"`, Group/Reservation/Block/Sub-Block)**:
   ```text
   protoPayload.methodName=~"^compute\.reservations\.(block\.|subBlock\.)?upcomingGroupMaintenance$" AND severity>=DEFAULT AND protoPayload.metadata.type=~"(?i)^multiple$"
   ```
   *Or exact match: `protoPayload.metadata.type="MULTIPLE"`.*

### Filter Maintenance Lifecycle Events

1. **Reservation-Level Group Maintenance**:
   * **Scheduled**: `protoPayload.methodName="compute.reservations.upcomingGroupMaintenance" AND severity>=DEFAULT AND protoPayload.status.message =~ "scheduled"`
   * **Completed**: `protoPayload.methodName="compute.reservations.completedGroupMaintenance" AND severity>=DEFAULT AND protoPayload.status.message =~ "completed"`
2. **Reservation Block-Level Group Maintenance**:
   * **Scheduled**: `protoPayload.methodName="compute.reservations.block.upcomingGroupMaintenance" AND severity>=DEFAULT AND protoPayload.status.message =~ "scheduled"`
   * **Started**: `protoPayload.methodName="compute.reservations.block.startGroupMaintenance" AND severity>=DEFAULT AND protoPayload.status.message =~ "started"`
   * **Completed**: `protoPayload.methodName="compute.reservations.block.completedGroupMaintenance" AND severity>=DEFAULT AND protoPayload.status.message =~ "completed"`
3. **Reservation Sub-Block Maintenance and Unused Machine Repairs (A4X and A4X Max)**:
   * **Scheduled**: `protoPayload.methodName="compute.reservations.subBlock.upcomingGroupMaintenance" AND severity>=DEFAULT AND protoPayload.status.message =~ "scheduled"`
   * **Started**: `protoPayload.methodName="compute.reservations.subBlock.startGroupMaintenance" AND severity>=DEFAULT AND protoPayload.status.message =~ "started"`
   * **Completed**: `protoPayload.methodName="compute.reservations.subBlock.completedGroupMaintenance" AND severity>=DEFAULT AND protoPayload.status.message =~ "completed"`
   * **Unused Machine Repair Started**: `protoPayload.methodName="compute.reservations.subblock.unusedmachinerepair" AND severity>=DEFAULT AND protoPayload.status.message =~ "maintenance"`
   * **Unused Machine Repair Completed**: `protoPayload.methodName="compute.reservations.subblock.unusedmachinerepaircomplete" AND severity>=DEFAULT AND protoPayload.status.message =~ "repaired"`
4. **Individual Compute Instance Host Maintenance**:
   * **Scheduled, Window Opened, or Completed**: `protoPayload.methodName="compute.instances.upcomingMaintenance" AND severity>=DEFAULT AND protoPayload.status.message =~ "(scheduled|ongoing|completed)"`
   * **Started (Termination on Maintenance)**: `protoPayload.methodName="compute.instance.terminateOnHostMaintenance" AND severity>=DEFAULT`

---

## Monitor VM Availability and Interruption Reports

### Detect Stopped VMs with Absent Uptime Conditions
When a Compute Engine (GCE) VM stops, crashes, or is terminated, it **stops emitting `compute.googleapis.com/instance/uptime` time-series samples altogether**. Consequently, a simple threshold alert (`compute.googleapis.com/instance/uptime < 1`) will **fail to trigger**. Always use `absent_over_time(compute_googleapis_com:instance_uptime{monitored_resource="gce_instance"}[5m])` (or `condition_absent`) to detect down VMs, and `compute_googleapis_com:instance_uptime_total < 300` to detect recent reboots.
* **Parameter and Resource Lookups**:
  * Verify VM host maintenance policy (`scheduling.onHostMaintenance`: `MIGRATE` versus `TERMINATE` and `scheduling.automaticRestart`) by running:
    `gcloud compute instances describe <INSTANCE_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(id,name,status,scheduling)"`

### Alert on VM Interruption Count Metrics
* **PromQL Metric**: `compute_googleapis_com:instance_interruption_count` (`monitored_resource="gce_instance"`, `GAUGE`, `INT64`, emitted every 1m with ~2m latency; the stream is undefined when the count is 0).
* **Parameter and Schema Lookup**:
  * Verify `interruption_count` label keys and documented enums by running:
    `python3 scripts/discover_metric_schema.py --project <PROJECT_ID> --resource-type gce_instance --metric-prefix compute.googleapis.com/instance/interruption_count`
* **Labels and Mapping**:
  * `interruption_type="TerminationEvent"` $\rightarrow$ `interruption_reason` $\in$ `["HostError", "UrgentRepairs", "UserReportedFault", "UserInitiatedTermination"]`
  * `interruption_type="MaintenanceEvent"` $\rightarrow$ `interruption_reason` $\in$ `["PlannedMaintenance", "EmergentMaintenance"]`
* **PromQL Query (Paging on Unplanned Disruptions)**:
  ```promql
  sum by (instance_id, instance_name, zone, interruption_type, interruption_reason) (
    compute_googleapis_com:instance_interruption_count{
      monitored_resource="gce_instance",
      interruption_reason=~"HostError|UrgentRepairs|EmergentMaintenance|UserReportedFault"
    }
  ) > 0
  ```

### Diagnose Interruptions with Interruption Report Logs
* **Log Stream**: `log_id("compute.googleapis.com/interruption_report")` (or `logName=~"logs/compute.googleapis.com%2Finterruption_report"`) on `resource.type="gce_instance"`.
* **Parameter and Log Retention Lookups**:
  * **Cloud Logging Bucket Retention Lookup**: Verify that the target Cloud Logging bucket (`_Default` or custom routed bucket) has `retentionDays >= 3` (72+ hours) by running:
    `gcloud logging buckets describe _Default --location=global --project=<PROJECT_ID> --format="value(retentionDays)"`
    *If `retentionDays` is less than 3, update it with `gcloud logging buckets update _Default --location=global --retention-days=30 --project=<PROJECT_ID>` after obtaining explicit user confirmation.*
  * **Recent Interruption Report Payload Inspection**: Inspect recent `instanceInterruptionReport` and `resourceTopology` (`reservationId`, `blockId`, `subblockId`, `machineId`) entries by running:
    `gcloud logging read 'resource.type="gce_instance" AND log_id("compute.googleapis.com/interruption_report")' --project=<PROJECT_ID> --limit=5 --format=json`
* **Payload Fields (`jsonPayload.instanceInterruptionReport` and `jsonPayload.resourceTopology`)**:
  * `impactCategory`: `"INSTANCE_INTERRUPTION"`
  * `resourceTopology`: `reservationId`, `blockId`, `subblockId`, `machineId`
  * `type`: `"CRITICAL_FAILURE"` (maps to `HostError`), `"URGENT_REPAIR"` (maps to `UrgentRepairs`), `"EMERGENT_MAINTENANCE"`, `"PLANNED_MAINTENANCE"`, `"USER_REPORTED_FAULT"`, `"USER_INITIATED_TERMINATION"`
  * `reason`:
    * `CRITICAL_FAILURE`: `FAILURE_HOST_SOFTWARE_KPANIC`, `FAILURE_HOST_SOFTWARE_SERR`, `FAILURE_HOST_SOFTWARE_OOM`, `FAILURE_GUEST_KPANIC`, `FAILURE_HOST_POWER`, `FAILURE_HOST_HARDWARE_GPU`
    * `EMERGENT_MAINTENANCE`: `FAILURE_DOMAIN_NVLINK`, `FAILURE_DOMAIN_NVSWITCH`, `FAILURE_DOMAIN_POWER`, `FAILURE_TOR_SWITCH`, `FAILURE_HOST`, `FAILURE_HOST_HARDWARE`, `FAILURE_HOST_HARDWARE_DISK`, `FAILURE_HOST_HARDWARE_MEMORY`, `FAILURE_HOST_HARDWARE_GPU`, `FAILURE_HOST_HARDWARE_GPU_XID`, `FAILURE_HOST_HARDWARE_TEMPERATURE`, `FAILURE_HOST_NETWORK`, `FAILURE_HOST_NETWORK_NIC`, `FAILURE_HOST_NETWORK_LINK`, `FAILURE_HOST_NETWORK_SOFTWARE`
    * `USER_REPORTED_FAULT`: `BEHAVIOR_UNSPECIFIED`, `PERFORMANCE`, `SILENT_DATA_CORRUPTION`, `UNRECOVERABLE_GPU_ERROR`
  * `status` (**72-Hour Diagnostic Lifecycle**):
    1. `"INITIAL_DIAGNOSIS"` (~30 minutes after VM termination)
    2. `"PENDING_DIAGNOSIS"` (~6 hours after VM termination)
    3. `"COMPLETE"` (final root cause diagnosis up to **72 hours** after termination)
* **Log Retention Requirement**: Always configure a Cloud Logging retention policy of **at least 3 days (72+ hours)** to ensure all diagnostic stages (`INITIAL_DIAGNOSIS` $\rightarrow$ `PENDING_DIAGNOSIS` $\rightarrow$ `COMPLETE`) are retained and matched.

---

## Configure GPU XID Health Insights Alerts

Operators running GPU workloads on `A3` (H100), `A3 Ultra` (H200), `A4` (B200), `A4X` (GB200), and `A4X Max` (GB300) instances often call the `Report host as faulty` API for every NVIDIA XID error, even when a **GPU reset** or **NVIDIA driver update** resolves the issue. **Compute Engine (GCE) GPU XID Insights** (published within 5–10 minutes of XID occurrence in syslog) categorizes XID errors and logs actionable recommendations:

* **Parameter and Resource Lookups**:
  * **Accelerator and Machine Family Lookup**: Confirm the VM's GPU machine family (`a3-highgpu-8g`, `a3-megagpu-8g`, `a3-ultragpu-8g`, `a4-highgpu-8g`, `a4x-*`) and attached `guestAccelerators` by running:
    `gcloud compute instances list --project=<PROJECT_ID> --filter="machineType ~ '(a3|a4)'" --format="table(id,name,zone.basename(),machineType.basename(),guestAccelerators[].acceleratorType.basename())"`
  * **GPU XID Insights and In-Band Event Log Lookup**: Inspect recent `gpu_health_insights_report` recommendations and raw in-band XID telemetry (`compute.googleapis.com/gpu_xid_events`, including `driverVersion`, `gpuUuid`, and `code`) by running:
    `gcloud logging read 'resource.type="gce_instance" AND (log_id("compute.googleapis.com/gpu_health_insights_report") OR log_id("compute.googleapis.com/gpu_xid_events"))' --project=<PROJECT_ID> --limit=5 --format=json`
* **Log Stream**: `log_id("compute.googleapis.com/gpu_health_insights_report")` (or `logName=~"logs/compute.googleapis.com%2Fgpu_health_insights_report"`)
* **Resource Type and Severity**: `resource.type="gce_instance"` AND `severity>=ERROR`
* **Payload Structure**:
  * `jsonPayload.impactCategory="GPU_INTERRUPTION"`
  * `jsonPayload.gpuInterruptionReport.xidInterruptionSources[]` (`xidCode`, `gpuUid`)
  * `jsonPayload.gpuInterruptionReport.summary` (contains explicit recommended action)
* **Actionable Remediation Matrix**:
  1. **GPU Driver Update Recommended**: **XIDs `109`, `119`, `120`** (`A3`, `A3-ultra`, `A4`, `A4x`, `A4x-max`) — upgrade to the recommended NVIDIA driver rather than calling `Report host as faulty`.
  2. **GPU Reset Recommended**: **XID `154`** (`A3`, `A3-ultra`, `A4`, `A4x`, `A4x-max`) and **XIDs `144`, `145`, `146`, `149`, `150`** (`A4`, `A4x`, `A4x-max`) — reset the affected GPU(s).
  3. **Host or NVLink Switch Repair**: **XID `79`** (GPU fallen off the bus) — requires physical technician repair through **Emergent Maintenance** (7-day notice when enabled; immediate VM disruption if disabled).

---

## Monitor Machine, Sub-Block, and Fabric Health

When monitoring AI Hypercomputer reservation SLA and SLO targets and physical host, sub-block, or NVLink and ICI fabric health transitions (`HEALTHY` $\rightarrow$ `UNHEALTHY`):

* **Parameter and Topology Lookups**:
  * **Physical Topology ID Lookup (`reservation_id`, `block_id`, `subblock_id`, `cluster_id`, `host`)**: Look up the topology hashes and IDs for instances, blocks, and sub-blocks by running:
    * **From VM Instance**: `gcloud compute instances describe <INSTANCE_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(id,name,resourceStatus.physicalTopology)"` (returns `physicalTopology.cluster`, `physicalTopology.block`, `physicalTopology.subblock`, `physicalTopology.host`).
    * **From Reservation Block (`PhysicalHostTopology`)**: `gcloud compute reservations blocks describe <RESERVATION_NAME> --block-name=<BLOCK_NAME> --zone=<ZONE> --project=<PROJECT_ID> --format="yaml(id,name,physicalTopology,instances)"`
    * **From Reservation Sub-Block (`subblockHealthInfo`)**: `gcloud compute reservations sub-blocks describe <RESERVATION_NAME> --block-name=<BLOCK_NAME> --sub-block-name=<SUB_BLOCK_NAME> --zone=<ZONE> --full-view=SUB_BLOCK_VIEW_FULL --project=<PROJECT_ID> --format="yaml(id,name,healthInfo,physicalTopology)"` (returns `healthyHostCount`, `degradedHostCount`, `healthyInfraCount`, `degradedInfraCount`).
  * **Metric Schema Discovery (`compute.googleapis.com/Machine` and `gce_instance`)**:
    `python3 scripts/discover_metric_schema.py --project <PROJECT_ID> --resource-type compute.googleapis.com/Machine --metric-prefix compute.googleapis.com/machine/`
    `python3 scripts/discover_metric_schema.py --project <PROJECT_ID> --resource-type gce_instance --metric-prefix compute.googleapis.com/instance/gpu/`

### Query Machine and Fabric Health Metrics
1. **Physical Machine Status (`compute.googleapis.com/machine/machine_status`)**:
   * **PromQL Metric**: `compute_googleapis_com:machine_machine_status`
   * **Monitored Resource**: `monitored_resource="compute.googleapis.com/Machine"`
   * **Labels**:
     * `machine_health`: `"HEALTHY"`, `"UNHEALTHY"`
     * `unhealthy_category`: `"REPAIRING"`, `"UNAVAILABLE"`, `"PENDING_USER_REPORT"`, `"UNKNOWN"` (populated when `machine_health="UNHEALTHY"`)
     * `machine_utilization`: values such as `"OCCUPIED"`
     * Topology labels: `reservation_id`, `block_id`, `subblock_id`, `cluster_id`
   * **PromQL Query (Unhealthy Machine or Sub-Block Degradation)**:
     ```promql
     sum by (reservation_id, block_id, subblock_id, cluster_id, unhealthy_category) (
       compute_googleapis_com:machine_machine_status{
         monitored_resource="compute.googleapis.com/Machine",
         machine_health="UNHEALTHY"
       }
     ) > 0
     ```
2. **VM and Slice Infrastructure Health (`compute.googleapis.com/instance/gpu/infra_health` and `compute.googleapis.com/instance/tpu/infra_health`)**:
   * **PromQL Metrics**: `compute_googleapis_com:instance_gpu_infra_health` and `compute_googleapis_com:instance_tpu_infra_health` (`monitored_resource="gce_instance"`)
   * **Labels**: `Value` (`"Healthy"`, `"Unhealthy"`, `"Unknown"`) / `health_status` (`"HEALTHY"`, `"UNHEALTHY"`), `unhealthy_category`, `reservation_id`, `block_id`, `subblock_id`, `machine_id`, `cluster_id`.
3. **NVLink, NVSwitch, GPU DRAM, and TPU ICI Fabric Health Metrics (`monitored_resource="gce_instance"`)**:
   * **GPU NVLink and NVSwitch**: `compute_googleapis_com:instance_gpu_gpu_nvlink_link_downed_counter`, `compute_googleapis_com:instance_gpu_nvswitch_link_downed_counter`, `compute_googleapis_com:instance_gpu_nvlink_runtime_error`
   * **GPU Memory (ECC and Row Remapping)**: `compute_googleapis_com:instance_gpu_dram_uncorrectable_ecc_error_count`, `compute_googleapis_com:instance_gpu_dram_row_remapping_failed`
   * **TPU Inter-Chip Interconnect (ICI)**: `compute_googleapis_com:instance_tpu_accelerator_network_ici_link_health`, `compute_googleapis_com:instance_tpu_accelerator_network_ici_link_flaps`

### Compare Current Metrics with Evolving Domain Signals
* Dedicated domain-level signals—including `domain_status` (with `healthy_host_count`, `degraded_host_count`, `degraded_switch_count`, `maintenance_slo_exceeded`, and `DOWNTIME_PERIOD_INCLUSION`), **Slot API health status enums**, **Subblock Describe API (`subblockHealthInfo`: `healthyHostCount`, `degradedHostCount`, `inSloHostCount`, `outSloHostCount`)**, and **Machine/Domain Repair Lifecycle logs (`PRE_REPAIR_DIAG`, `ACTIVE_REPAIR`, `POST_REPAIR_VALIDATION`, `COMPLETED`)**—are evolving across rollout phases. Always aggregate `compute_googleapis_com:machine_machine_status{machine_health="UNHEALTHY"}`, `compute_googleapis_com:instance_gpu_infra_health` / `instance_tpu_infra_health`, and NVLink or ICI fabric metrics by `(reservation_id, block_id, subblock_id, unhealthy_category)` to alert on machine and domain or sub-block health state changes in Cloud Monitoring today.
generic_alert_policies.md 18.6 KB
# Configure Generic Alert Policies for Other Resources

This reference provides best-practice alerting patterns for **arbitrary Google Cloud
resources, custom workloads, or service types** that do not have dedicated
resource-specific alert references in this skill (such as Cloud Run or GKE).

To maintain **consistency across all alerting policies in this skill**, we
prioritize **PromQL (`condition_prometheus_query_language`)** where supported by
Cloud Monitoring (through managed Prometheus or Cloud Monitoring PromQL
evaluation). Note that **Monitoring Query Language (MQL) is deprecated in favor
of PromQL** — whenever a user requests an MQL alert policy, explicitly inform
them that MQL is deprecated in favor of PromQL and provide the equivalent PromQL
configuration.

## Follow Mandatory Requirements for Generic Resource Alerts

When configuring alerts for any generic, custom, or fallback Google Cloud resource (such
as Cloud SQL, Spanner, Memorystore Redis, Pub/Sub, custom processing pipelines,
MQL migration, or **adding alerts to `monitoring/alerts.tf` / HCL review and
deduplication**), follow the patterns in this reference directly. **Do not search the workspace for additional reference files, scripts, or unrelated `.tf` files.** Only inspect an existing `.tf` file (such as `monitoring/alerts.tf`) when the user asks to add to, review, or deduplicate that file. Run `python3
scripts/discover_metric_schema.py --project <project_id> --resource-type
<resource_type>` to verify exact PromQL metric names (including `_bucket`),
units (for example, `us` versus `ms`), resource grouping labels, and documented label enum
values before writing HCL. **When responding to these requests, you MUST**:

1.  **Run schema & metric discovery commands**: Run `python3
    scripts/discover_metric_schema.py` when configuring alerts for custom or
    unsupported resources, and include the exact commands in your response.
2.  **Run PromQL validation commands**: Run `python3 scripts/lint_promql.py`
    and/or `python3 scripts/discover_metric_schema.py --promql` (and `grep`/`diff`
    for HCL review) when generating, fixing, validating, or deduplicating
    HCL/PromQL queries, and include the exact commands in your response.
3.  **Perform in-place HCL deduplication**: For HCL review or deduplication
    requests, explicitly describe inspecting existing HCL policies for
    duplicates and performing an **in-place update** rather than appending
    duplicate blocks.
4.  **Use explicit grouping**: Use `sum by (<label>)` (for example, `sum by (service)`)
    or `group_by_fields` for fleet-wide aggregation (never ungrouped scalar
    `sum(...)`).
5.  **Explicitly note MQL deprecation**: State that MQL is deprecated in favor
    of PromQL if MQL is requested.
6.  **Prompt for Notification Channels**: Always ask the user at the end of your
    response if they would like to configure notification channels if none were
    provided.
7.  **Delegate SLOs**: Whenever an availability, latency, or throughput SLO (or
    an error-budget / burn-rate alert) is requested, follow
    [Delegate SLOs and Apply the Fallback Rule](#delegate-slos-and-apply-the-fallback-rule) below:
    discover the exact SLI metric with `scripts/discover_metric_schema.py`, then
    delegate the SLO policy generation to the
    `google-cloud-slo-alert-configuration` skill — never emit a single static
    error ratio as an SLO.

---

## Review the Table of Contents

1.  [Discover and Select Metrics](#discover-and-select-metrics): Lines 75-113
2.  [Apply the Four Golden Signals Framework (PromQL)](#apply-the-four-golden-signals-framework-promql): Lines 114-159
    -   [Monitor Error Rate](#monitor-error-rate): Lines 116-127
    -   [Monitor Latency and Duration](#monitor-latency-and-duration): Lines 128-137
    -   [Monitor Traffic and Throughput](#monitor-traffic-and-throughput): Lines 138-147
    -   [Monitor Saturation and Utilization](#monitor-saturation-and-utilization): Lines 148-159
3.  [Apply Terraform Configuration Templates (PromQL)](#apply-terraform-configuration-templates-promql): Lines 160-242
    -   [Use Template A for PromQL-Based Alert Policies (Recommended)](#use-template-a-for-promql-based-alert-policies-recommended): Lines 162-197
    -   [Use Template B for Legacy Threshold-Based Alert Policies (Fallback)](#use-template-b-for-legacy-threshold-based-alert-policies-fallback): Lines 198-242
4.  [Configure Cloud Logging Log-Based Metric Alerts](#configure-cloud-logging-log-based-metric-alerts): Lines 243-313
5.  [Delegate SLOs and Apply the Fallback Rule](#delegate-slos-and-apply-the-fallback-rule): Lines 314-378
6.  [Validate PromQL Syntax and Metric Schemas](#validate-promql-syntax-and-metric-schemas): Lines 379-403
7.  [Review and Deduplicate HCL Configurations](#review-and-deduplicate-hcl-configurations): Lines 404-412
8.  [Follow Best Practices and Validation Rules](#follow-best-practices-and-validation-rules): Lines 413-444

---

## Discover and Select Metrics

Before configuring alerts for an unfamiliar or generic Google Cloud resource, discover
its available metrics, metric types, units, and label enum values:

1.  **Run Universal Schema & Metric Discovery (`discover_metric_schema.py`)**:
    Run the schema discovery script to automatically inspect
    `monitoredResourceDescriptors` and `metricDescriptors` through the Cloud
    Monitoring v3 API. This script outputs exact PromQL metric names (including
    `_bucket` suffixes for distributions), unit scaling warnings (for example,
    microseconds `us` versus milliseconds `ms`), grouping keys (`sum by (...)`), and
    documented label enum values (for example, `response_class="success"`):

    ```bash
    python3 scripts/discover_metric_schema.py \
        --project="<project_id>" \
        --resource-type="<monitored_resource_type>" \
        --metric-prefix="<metric_prefix_or_domain>"
    ```

2.  **Map to PromQL**: Cloud Monitoring automatically translates Google
    Cloud metric types (`<domain>/<path>`) into Prometheus format by replacing
    dots (`.`) with underscores (`_`), replacing the **first slash (`/`) after
    the domain with a colon (`:`)**, and replacing remaining slashes with
    underscores (`_`). For example,
    `serviceruntime.googleapis.com/api/request_count` maps to
    `serviceruntime_googleapis_com:api_request_count` (append `_bucket` for
    distributions). Always verify `.unit` (`us` versus `ms`) and documented label
    values before writing thresholds or label matchers.

---

## Apply the Four Golden Signals Framework (PromQL)

### Monitor Error Rate

Monitor the ratio of failed requests or error status codes over total requests.

*   **PromQL Query**:

    ```promql
    sum by (service) (rate(serviceruntime_googleapis_com:api_request_count{response_code_class="5xx"}[5m]))
    /
    sum by (service) (rate(serviceruntime_googleapis_com:api_request_count[5m])) > 0.01
    ```

### Monitor Latency and Duration

Monitor 95th or 99th percentile request duration.

*   **PromQL Query**:

    ```promql
    histogram_quantile(0.95, sum by (service, le) (rate(serviceruntime_googleapis_com:api_request_latencies_bucket[5m]))) > 2000
    ```

### Monitor Traffic and Throughput

Monitor total request volume or transaction rate.

*   **PromQL Query**:

    ```promql
    sum by (service) (rate(serviceruntime_googleapis_com:api_request_count[5m]))
    ```

### Monitor Saturation and Utilization

Monitor CPU, memory, or resource capacity utilization percentage.

*   **PromQL Query**:

    ```promql
    avg(rate(container_cpu_usage_seconds_total[5m])) by (instance) > 0.85
    ```

---

## Apply Terraform Configuration Templates (PromQL)

### Use Template A for PromQL-Based Alert Policies (Recommended)

This is the standard alerting pattern used across Cloud Run, GKE, and Agent
Platform in this skill.

```terraform
resource "google_monitoring_alert_policy" "generic_promql_error_rate" {
  display_name = "Generic High Error Rate (PromQL)"
  project      = var.project_id
  combiner     = "OR"

  conditions {
    display_name = "Error rate exceeds 1% over 5m"

    condition_prometheus_query_language {
      query    = <<-EOT
        sum by (service) (rate(serviceruntime_googleapis_com:api_request_count{response_code_class="5xx"}[5m]))
        /
        sum by (service) (rate(serviceruntime_googleapis_com:api_request_count[5m])) > 0.01
      EOT
      duration = "300s"
    }
  }

  alert_strategy {
    auto_close = "604800s"
  }

  user_labels = {
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
    "alert-category"          = "reliability"
    "query-language"          = "promql"
  }
}
```

### Use Template B for Legacy Threshold-Based Alert Policies (Fallback)

Use this only if PromQL is unsupported for the specific metric backend.

```terraform
resource "google_monitoring_alert_policy" "generic_threshold_error_rate" {
  display_name = "Generic High Error Rate (Threshold)"
  project      = var.project_id
  combiner     = "OR"

  conditions {
    display_name = "Error count exceeds threshold"

    condition_threshold {
      filter          = "metric.type=\"serviceruntime.googleapis.com/api/request_count\" resource.type=\"global\" metric.label.response_code_class=\"5xx\""
      duration        = "300s"
      comparison      = "COMPARISON_GT"
      threshold_value = 10

      aggregations {
        alignment_period     = "60s"
        per_series_aligner   = "ALIGN_RATE"
        cross_series_reducer = "REDUCE_SUM"
        group_by_fields      = ["resource.labels.project_id"]
      }

      trigger {
        count = 1
      }
    }
  }

  alert_strategy {
    auto_close = "604800s"
  }

  user_labels = {
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
    "alert-category"          = "reliability"
  }
}
```

---

## Configure Cloud Logging Log-Based Metric Alerts

For applications or services that output text or structured logs rather than
native metrics, configure Cloud Logging log-based metrics (`google_logging_metric`)
and alert on them using Cloud Monitoring.

### Define a Cloud Logging Log-Based Metric (`google_logging_metric`)

Extracts a counter or distribution metric from log entries matching a filter
(for example, application crashes or unhandled exceptions).

```terraform
resource "google_logging_metric" "app_error_log_metric" {
  name        = "app-error-log-count"
  project     = var.project_id
  description = "Count of application error log entries"
  filter      = "resource.type=\"global\" severity>=ERROR"

  metric_descriptor {
    metric_kind  = "DELTA"
    value_type   = "INT64"
    unit         = "1"
    display_name = "Application Error Log Count"
  }
}
```

### Create an Alert Policy on a Cloud Logging Log-Based Metric

Create an alert policy tracking the Cloud Logging log-based metric using threshold conditions:

```terraform
resource "google_monitoring_alert_policy" "log_metric_alert" {
  display_name = "High Application Error Log Rate"
  project      = var.project_id
  combiner     = "OR"

  conditions {
    display_name = "Error log rate exceeds threshold"

    condition_threshold {
      filter          = "metric.type=\"logging.googleapis.com/user/${google_logging_metric.app_error_log_metric.name}\" resource.type=\"global\""
      duration        = "300s"
      comparison      = "COMPARISON_GT"
      threshold_value = 5

      aggregations {
        alignment_period     = "60s"
        per_series_aligner   = "ALIGN_RATE"
        cross_series_reducer = "REDUCE_SUM"
      }

      trigger {
        count = 1
      }
    }
  }

  alert_strategy {
    auto_close = "604800s"
  }

  user_labels = {
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
    "alert-category"          = "reliability"
  }
}
```

---

## Delegate SLOs and Apply the Fallback Rule

**Availability, latency, and throughput SLOs are owned by the
`google-cloud-slo-alert-configuration` skill.** Delegate to it whenever the user
asks for an SLO, an error budget, or burn-rate alerting on a generic resource.
That skill owns the SLO wizard, the burn-rate templates
(`references/promql_templates.md`), the SLI mapping
(`references/service_metrics.md`), and the App Hub scoping labels
(`references/app_hub_labels.md`).

Never emit a single static threshold or a bare error ratio as an "SLO". Unlike
the Cloud Run and GKE references, generic resources have **no documented default
SLI**, so this reference **must** resolve the SLI first and hand that context
over.

**Context to hand off** (so the SLO skill does not repeat discovery):

*   **Resource type**: the monitored resource type you confirmed with discovery.
*   **Grouping labels**: the resource identity labels returned by discovery (the
    `sum by (...)` clause).
*   **SLI**: the discovered metric name, its good/bad filter, and its unit.
*   **SLO target**: the user's target, or `0.999` (99.9%) if they did not give
    one.

### Discover the Exact SLI Metric and Hand It to the SLO Skill

Generic resources (Cloud SQL, Spanner, Memorystore, Pub/Sub, custom pipelines)
rarely have a documented default SLI. Run the schema discovery script and
include the exact command in your response:

```bash
python3 scripts/discover_metric_schema.py \
    --project="<project_id>" \
    --resource-type="<monitored_resource_type>" \
    --metric-prefix="<metric_prefix_or_domain>"
```

Use its output to resolve the four things a burn-rate query cannot be written
without:

| Discovery Output | Why the SLO Needs It |
| :--- | :--- |
| Exact PromQL metric name | `{GOOD_METRIC}` / `{BAD_METRIC}` / `{TOTAL_METRIC}` substitution (for example, `serviceruntime_googleapis_com:api_request_count`) |
| `_bucket` distribution series | Latency SLIs need the `_bucket` series for `histogram_fraction` / `histogram_quantile` |
| Unit (`us`, `ms`, or `s`) | A 500 ms target is `500` for `ms` metrics but `500000` for `us` metrics (`us` versus `ms`) — the wrong unit silently produces an alert that never fires |
| Documented label enum values | The failure filter must use real values (for example, `response_class="success"` or `response_code_class="5xx"`); an invalid enum yields an always-empty series |
| Resource grouping labels | The `sum by (...)` clause that keeps the burn rate per-service instead of fleet-averaged |

Hand the resolved SLI to `google-cloud-slo-alert-configuration` as the
`ServiceLevelIndicator` input, along with the SLO target and window if the user
supplied them.

**Fallback** — only if `google-cloud-slo-alert-configuration` is not installed:
this reference intentionally carries **no** burn-rate templates. Say that SLO
alerting requires that skill, report the SLI you discovered, and continue with
the non-SLO golden-signal policies. Never silently present SLO policies as if
this skill owned them.

> [!IMPORTANT] Your response MUST say, in plain text, that you will **not invent
> or guess a metric name** and that you will **ask the user for the custom
> metric name and failure filter** if schema discovery does not resolve one. Say
> this even when you believe you have identified the right metric — the SLO is
> only as correct as the SLI it is built on, and a guessed metric silently
> produces an alert that never fires.

## Validate PromQL Syntax and Metric Schemas

When fixing, validating, or generating PromQL alert queries (such as diagnosing
and fixing unbalanced parentheses or invalid time windows), **never search the
workspace or directory tree for a query file if no file path was
provided**. If the user describes a syntax error (such as unbalanced
parentheses) without pasting the query, demonstrate the fix using a concrete
before-and-after example (for example, fixing missing closing parenthesis in
`sum by (service) (rate(serviceruntime_googleapis_com:api_request_count{response_code_class="5xx"}[5m]) > 0.01`
to
`sum by (service) (rate(serviceruntime_googleapis_com:api_request_count{response_code_class="5xx"}[5m])) > 0.01`).
Always run or print both the static syntax linter (`lint_promql.py`) and the
schema-aware validator (`discover_metric_schema.py`), and include the exact
commands in your response:

```bash
# 1. Static PromQL syntax & bracket/window validation
python3 scripts/lint_promql.py "<promql_expression>"

# 2. Live Google Cloud schema, metric existence, unit scaling ('us' versus 'ms'), & label enum validation
python3 scripts/discover_metric_schema.py \
    --project="<project_id>" \
    --promql '<promql_expression>'
```

## Review and Deduplicate HCL Configurations

When adding new alerts to `monitoring/alerts.tf`, inspect existing HCL policies
(for example, using `grep` or file inspection) to prevent duplicate alert blocks, perform
in-place updates when modifying existing policies, and always prompt the user
regarding notification channel configuration.

---

## Follow Best Practices and Validation Rules

1.  **Prioritize PromQL & Note MQL Deprecation**: Always use
    `condition_prometheus_query_language` where supported to maintain
    consistency with Cloud Run, GKE, and Agent Platform alert definitions. If a
    user requests an MQL policy, explicitly note that **MQL is deprecated in
    favor of PromQL** and provide PromQL instead.
2.  **Cover Golden Signals (Error Rate + Saturation/Latency)**: When configuring
    production alerts for any generic or unsupported resource (such as Cloud
    SQL, Spanner, Memorystore Redis, or custom workloads), always provide
    alert policies covering **at least Error Rate** (or failed operations,
    evictions, or rejected connections) **and Saturation/Latency**.
3.  **Evaluation Window**: Ensure PromQL queries specify an evaluation duration
    of at least `300s` (5 minutes) to avoid flapping.
4.  **SLOs**: Delegate dedicated Service Level Objective tracking and error
    budget burn-rate alerting to the `google-cloud-slo-alert-configuration`
    skill, handing off the SLI metric resolved by schema discovery (see
    [Delegate SLOs and Apply the Fallback Rule](#delegate-slos-and-apply-the-fallback-rule)).
5.  **Notification Channels**: Attach notification channels using the
    `cloud-monitoring-notification-channels-configuration` skill. **Always
    prompt the user to ask if they would like to configure notification channels
    if none were provided.**
6.  **Run & Include CLI Commands for Reproducibility**: Always run the `python3
    scripts/discover_metric_schema.py` and `python3 scripts/lint_promql.py
    "<promql_expression>"` commands to discover schemas and validate PromQL
    expressions, and include the exact commands in your response so users can
    reproduce your validation.
7.  **Fleet-Wide Aggregation (`sum by` / `group_by_fields`)**: For fleet-wide
    scaling or multi-instance alerts, **always** include explicit grouping: use
    `sum by (service, instance_id)` (or `sum by (service)`) in PromQL queries,
    or `aggregations { group_by_fields = [...] }` in threshold queries — never
    use ungrouped scalar `sum(...)`.
kubernetes_gke_configuration_prerequisites.md 13.3 KB
# Configure GKE Telemetry Prerequisites for Alerting Policies

This document details the Google Kubernetes Engine (GKE) and Google Cloud
configurations required to support the 16 critical alerting policies defined in
the reference catalog. It provides cluster operators with the setup commands,
configuration parameters, and verification queries to ensure telemetry flows
correctly for each alert.

# Table of Contents

- [Review the Telemetry Ingestion Architecture](#review-the-telemetry-ingestion-architecture): Lines 35-60
- [Verify Prerequisites by Alert](#verify-prerequisites-by-alert): Lines 61-86
- [Configure GKE Control Plane Metrics](#configure-gke-control-plane-metrics): Lines 87-119
  - [Enable Control Plane Metrics](#enable-control-plane-metrics): Lines 94-109
  - [Verify Control Plane Metrics](#verify-control-plane-metrics): Lines 110-119
- [Configure Kube State Metrics](#configure-kube-state-metrics): Lines 120-176
  - [Configure KSM Scraping](#configure-ksm-scraping): Lines 136-166
  - [Apply the PodMonitoring Allowlist Target](#apply-the-podmonitoring-allowlist-target): Lines 142-166
  - [Verify KSM Deployment](#verify-ksm-deployment): Lines 167-176
- [Configure Kubelet and cAdvisor Metrics](#configure-kubelet-and-cadvisor-metrics): Lines 177-218
  - [Define Container Resource Limits for Saturation Alerts](#define-container-resource-limits-for-saturation-alerts): Lines 183-218
  - [Identify Containers Missing Limits](#identify-containers-missing-limits): Lines 193-218
- [Configure Volume and Storage Telemetry](#configure-volume-and-storage-telemetry): Lines 219-238
  - [Verify CSI Driver Requirements](#verify-csi-driver-requirements): Lines 224-231
  - [Verify Volume Telemetry](#verify-volume-telemetry): Lines 232-238

> [!IMPORTANT] **Mandatory Kubernetes and GKE Alerting Guardrails**:
> * **Direct Response**: Read `references/kubernetes_*.md` and respond directly. Do not search the workspace for additional files before answering. **Do NOT search the codebase for external Terraform modules or extra reference files, and do NOT write `.tf` files to disk unless the user explicitly specifies a target file path.**
> * **Tier 2 KSM Permission Guardrail (`kube_*` state metrics)**: For any Tier 2 `kube-state-metrics (KSM)` alert (`kube_deployment_*`, `kube_statefulset_*`, `kube_daemonset_*`, `kube_cronjob_*`, `kube_job_*`, `kube_persistentvolume_*`, `kube_pod_status_phase`, `kube_pod_container_resource_limits`), **do NOT assume KSM is enabled or write or apply any Terraform files**. At the very top of your response, you MUST: (a) alert the user that the policy requires `kube-state-metrics (KSM)`, (b) explain that KSM incurs billable Managed Service for Prometheus (GMP) sample ingestion costs (see [Cloud Monitoring pricing](https://cloud.google.com/products/observability/pricing)), (c) **ask the user a direct question in second-person asking for explicit permission** (literally include: **"Do you grant explicit permission to enable and ingest kube-state-metrics (KSM) in your cluster for this alert?"**), and (d) recommend a filtered `PodMonitoring` allowlist (`metricRelabeling` with `action: keep`) that keeps only the required metrics.
> * **Tier 1 Native Metrics (Zero KSM Surcharge)**: For native cAdvisor, Kubelet, or Control Plane metrics (`container_memory_working_set_bytes`, `container_spec_memory_limit_bytes`, `kube_pod_container_status_restarts_total`, `kubernetes.io/container/restart_count`, `kube_node_status_condition`, `kubelet_volume_stats_available_bytes`, `apiserver_*`, `rest_client_*`), explicitly state that the metric is a **Tier 1 native/standard metric with zero KSM cost surcharge** (a **Tier 1 Kubelet/cAdvisor metric that does not require kube-state-metrics** or a **Tier 1 Control Plane metric with zero KSM cost surcharge**), explain that container resource limits (`resources.limits`) must be defined in pod specs for saturation alerts to resolve, and provide a clear plain-English explanation of the alert and thresholds.
> * **Mandatory Terraform Variables and `user_labels`**: Every Kubernetes Terraform HCL configuration MUST define `variable "project_id"`, `variable "cluster_name"`, and `variable "namespace"` (`var.project_id`, `${var.cluster_name}`, `${var.namespace}`) and include `user_labels = { "created-with-google-skill" = "cloud-monitoring-alert-configuration" }` in every `google_monitoring_alert_policy` resource.

---

## Review the Telemetry Ingestion Architecture

The following diagram illustrates how metrics for each alert category are
scraped from the cluster and ingested into Cloud Monitoring and Google Cloud Managed
Service for Prometheus (GMP).

```mermaid
graph TD
    subgraph GKE_Cluster["GKE Cluster"]
        subgraph Control_Plane["Control Plane (Google Managed)"]
            APIServer["Kubernetes API Server"] -->|Exposes apiserver_* and rest_*| GMP_CP["GKE Control Plane Metrics Collector"]
        end
        subgraph Worker_Nodes["Worker Nodes"]
            subgraph Kubelet["Kubelet"]
                cAdvisor["cAdvisor"] -->|Exposes container_*| GMP_Operator["GMP Operator / PodMonitoring"]
                KubeletVol["Volume Stats"] -->|Exposes kubelet_volume_*| GMP_Operator
            end
            KSM["kube-state-metrics Pod"] -->|Exposes kube_*| GMP_Operator
        end
    end
    GMP_CP -->|Writes to| GCP_Monitoring["Cloud Monitoring / GMP"]
    GMP_Operator -->|Writes to| GCP_Monitoring
```

---

## Verify Prerequisites by Alert

This table lists the GKE and Google Cloud prerequisites and configuration
requirements for each of the 16 critical alerts.

| Alert Name | Cost Tier | Required Metrics | GKE Cluster Requirement | Workload or Resource Requirement |
| :--- | :--- | :--- | :--- | :--- |
| **Kubernetes Node not ready** | Tier 1 (Native) | `kube_node_status_condition` | System Monitoring Enabled | GKE Nodes running standard Kubelet |
| **Kubernetes Node memory pressure** | Tier 1 (Native) | `kube_node_status_condition` | System Monitoring Enabled | GKE Nodes running standard Kubelet |
| **Kubernetes Node disk pressure** | Tier 1 (Native) | `kube_node_status_condition` | System Monitoring Enabled | GKE Nodes running standard Kubelet |
| **Kubernetes Node network unavailable** | Tier 1 (Native) | `kube_node_status_condition` | System Monitoring Enabled | GKE Nodes running standard Kubelet |
| **Kubernetes Volume full in four days** | Tier 1 (Native) | `kubelet_volume_stats_available_bytes` | System Monitoring Enabled | Pods with attached volumes (CSI Driver supported) |
| **Kubernetes API server errors** | Tier 1 (Native) | `apiserver_request_total` | Control Plane Metrics Enabled | GKE control plane active |
| **Kubernetes API client errors** | Tier 1 (Native) | `rest_client_requests_total` | Control Plane Metrics Enabled | API Clients communicating with API Server |
| **Kubernetes client certificate expires soon** | Tier 1 (Native) | `apiserver_client_certificate_expiration_seconds_count` | Control Plane Metrics Enabled | Client certificate authentication enabled |
| **Kubernetes CronJob failing** | Tier 2 (KSM) | `kube_cronjob_status_*`, `kube_cronjob_spec_*` | `kube-state-metrics` Scraped | Active CronJobs in cluster |
| **Kubernetes PersistentVolume error** | Tier 2 (KSM) | `kube_persistentvolume_status_phase` | `kube-state-metrics` Scraped | PersistentVolume resources configured |
| **Kubernetes StatefulSet down** | Tier 2 (KSM) | `kube_statefulset_*` | `kube-state-metrics` Scraped | StatefulSets deployed |
| **Kubernetes Pod not healthy** | Tier 2 (KSM) | `kube_pod_status_phase` | `kube-state-metrics` Scraped | Pods running in target namespaces |
| **Kubernetes Deployment generation mismatch** | Tier 2 (KSM) | `kube_deployment_*` | `kube-state-metrics` Scraped | Deployments deployed |
| **Kubernetes StatefulSet generation mismatch** | Tier 2 (KSM) | `kube_statefulset_*` | `kube-state-metrics` Scraped | StatefulSets deployed |
| **Kubernetes DaemonSet misscheduled** | Tier 2 (KSM) | `kube_daemonset_*` | `kube-state-metrics` Scraped | DaemonSets deployed |
| **Kubernetes Job slow completion** | Tier 2 (KSM) | `kube_job_*` | `kube-state-metrics` Scraped | Jobs deployed |

---

## Configure GKE Control Plane Metrics

The control plane alerts (`KubernetesAPIServerErrors`,
`KubernetesAPIClientErrors`, and `KubernetesClientCertificateExpiresSoon`) use a
**Tier 1 Control Plane metric with zero KSM cost surcharge** and require API
server and API client telemetry.

### Enable Control Plane Metrics

By default, GKE control plane metrics are not scraped. Enable them in the GKE
cluster configuration using `gcloud`:

```bash
gcloud container clusters update CLUSTER_NAME \
    --zone=COMPUTE_ZONE \
    --monitoring=SYSTEM,API_SERVER,CONTROLLER_MANAGER,SCHEDULER
```

*   **API_SERVER**: Exposes API server request volumes, error rates, and client
    request metrics.
*   **CONTROLLER_MANAGER and SCHEDULER**: Exposes scheduler queue metrics and
    controller manager execution states.

### Verify Control Plane Metrics

Verify that API server telemetry flows to Cloud Monitoring:

```promql
sum(rate(apiserver_request_total[5m])) by (code)
```

---

## Configure Kube State Metrics

All workload, replica mismatch, DaemonSet, StatefulSet, Job, CronJob, Pod phase,
and PersistentVolume alerts require cluster state metrics (`kube_*` metrics)
from `kube-state-metrics (KSM)`.

> [!IMPORTANT] **Mandatory Explicit Permission Guardrail**: Before assuming or
> enabling KSM ingestion, you **MUST** alert the user that the alert requires
> `kube-state-metrics (KSM)`, explain that KSM incurs billable Managed Service
> for Prometheus (GMP) sample ingestion costs (see [Cloud Monitoring pricing](https://cloud.google.com/products/observability/pricing)),
> and **ask the user a direct question for explicit permission**:
> **"Do you grant explicit permission to enable and ingest kube-state-metrics (KSM) in your cluster for this alert?"**
> Do **NOT** write `.tf` files to disk prior to receiving user permission; present
> the `PodMonitoring` allowlist and any Terraform HCL strictly as a conditional
> configuration to use **if KSM is approved**.

### Configure KSM Scraping

If the user approves KSM ingestion, deploy the `kube-state-metrics` service in
the cluster and configure a filtered `PodMonitoring` resource (GMP) to scrape
only the required metrics.

#### Apply the PodMonitoring Allowlist Target

To control costs, apply a filtered `PodMonitoring` specification that keeps only
the metrics required for these 16 critical alerts. Place this manifest in
`kube-system`:

```yaml
apiVersion: monitoring.googleapis.com/v1
kind: PodMonitoring
metadata:
  name: kube-state-metrics-filtered
  namespace: kube-system
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: kube-state-metrics
  endpoints:
  - port: http-metrics
    interval: 60s
    metricRelabeling:
    - action: keep
      sourceLabels: [__name__]
      regex: "^(kube_node_status_condition|kube_pod_status_phase|kube_pod_container_status_restarts_total|kube_deployment_spec_replicas|kube_deployment_status_replicas_available|kube_statefulset_replicas|kube_statefulset_status_replicas_ready|kube_statefulset_status_replicas|kube_deployment_status_observed_generation|kube_deployment_metadata_generation|kube_statefulset_status_observed_generation|kube_statefulset_metadata_generation|kube_daemonset_status_number_misscheduled|kube_cronjob_status_last_schedule_time|kube_cronjob_status_last_successful_time|kube_cronjob_status_active|kube_cronjob_spec_suspend|kube_persistentvolume_status_phase|kube_job_spec_completions|kube_job_status_succeeded|kube_job_status_failed)$"
```

### Verify KSM Deployment

Confirm that KSM is deployed and active:

```promql
up{job="kube-state-metrics"} == 1
```

---

## Configure Kubelet and cAdvisor Metrics

System metrics such as container memory usage and CPU duty cycles are exposed
natively by the Kubelet on each node as a **Tier 1 Kubelet/cAdvisor metric that
does not require kube-state-metrics**.

### Define Container Resource Limits for Saturation Alerts

Saturation alerts (such as non-KSM memory alerts) compare active usage against
container resource limits (`container_spec_memory_limit_bytes` and
`container_spec_cpu_quota`).

> [!WARNING] **The Resource Limit Gotcha**: If a pod or container does not have
> explicit limits defined in its deployment specification, these metrics return
> `NaN` or default values, causing the alert policy to **fail to resolve**.

#### Identify Containers Missing Limits

Run the following verification query to find pods that fail to resolve in
saturation alerting policies:

```promql
# Find containers missing memory limits
container_memory_working_set_bytes{container!=""}
  unless on (pod, container)
container_spec_memory_limit_bytes > 0
```

Ensure all workloads define a limit in their manifest:

```yaml
spec:
  containers:
  - name: my-app
    resources:
      limits:
        memory: "512Mi"
        cpu: "1000m"
```

---

## Configure Volume and Storage Telemetry

The volume alert (`KubernetesVolumeFullInFourDays`) relies on
`kubelet_volume_stats_available_bytes`.

### Verify CSI Driver Requirements

1.  Configure the storage class for the PersistentVolume (PV) to use a CSI
    driver that supports **Volume Stats** (such as the GKE Persistent Disk CSI
    Driver `pd.csi.storage.gke.io`).
2.  Local SSDs or HostPath volumes do not report volume capacity and
    availability statistics consistently.

### Verify Volume Telemetry

Confirm volume statistics are reporting:

```promql
kubelet_volume_stats_available_bytes > 0
```
kubernetes_metrics_and_alerts_catalog.md 22.0 KB
# Select GKE Metrics and Kubernetes Alerting Policies

This catalog compiles public Google Kubernetes Engine (GKE) telemetry metrics
from
[Google Cloud Kubernetes Metrics](https://docs.cloud.google.com/monitoring/api/metrics_kubernetes.md.txt)
and critical alerting rules from the open-source
[Awesome Prometheus Alerts for Kubernetes](https://samber.github.io/awesome-prometheus-alerts/rules/orchestrators/kubernetes/)
catalog.

It serves as the reference catalog for the `cloud-monitoring-alert-configuration`
skill when generating evaluation suites and production alerting policies in
Google Cloud Managed Service for Prometheus (GMP) and Cloud Monitoring.

# Table of Contents

- [Enforce Kubernetes and GKE Telemetry Guardrails](#enforce-kubernetes-and-gke-telemetry-guardrails): Lines 37-138
  - [Classify Telemetry Tiers and Optimize Ingestion Costs](#classify-telemetry-tiers-and-optimize-ingestion-costs): Lines 102-138
  - [Filter Tier 2 Metrics with a PodMonitoring Allowlist](#filter-tier-2-metrics-with-a-podmonitoring-allowlist): Lines 112-138
- [Query Native GKE System Metrics](#query-native-gke-system-metrics): Lines 139-189
  - [Monitor Container and Pod Core Metrics](#monitor-container-and-pod-core-metrics): Lines 144-163
  - [Monitor Node and Infrastructure Core Metrics](#monitor-node-and-infrastructure-core-metrics): Lines 164-177
  - [Monitor Autoscaling and Hardware Accelerator Metrics](#monitor-autoscaling-and-hardware-accelerator-metrics): Lines 178-189
- [Map Open Source Kubernetes Alert Rules](#map-open-source-kubernetes-alert-rules): Lines 190-241
  - [Configure Node Health and Capacity Alerts](#configure-node-health-and-capacity-alerts): Lines 194-204
  - [Configure Workload and Container Reliability Alerts](#configure-workload-and-container-reliability-alerts): Lines 205-219
  - [Configure Job CronJob and Storage Alerts](#configure-job-cronjob-and-storage-alerts): Lines 220-230
  - [Configure API Server and Control Plane Alerts](#configure-api-server-and-control-plane-alerts): Lines 231-241
- [Implement Non KSM Native Alternative Alerts](#implement-non-ksm-native-alternative-alerts): Lines 242-350
  - [Alert on Container Memory Saturation and OOM Risk](#alert-on-container-memory-saturation-and-oom-risk): Lines 248-277
  - [Alert on Pod CrashLoopBackOff and Container Restarts](#alert-on-pod-crashloopbackoff-and-container-restarts): Lines 278-297
  - [Alert on Node Readiness and Health](#alert-on-node-readiness-and-health): Lines 298-307
  - [Alert on Multi Window Multi Burn Rate SLO Error Rates](#alert-on-multi-window-multi-burn-rate-slo-error-rates): Lines 308-340
  - [Detect Traffic Outages](#detect-traffic-outages): Lines 341-350

---

## Enforce Kubernetes and GKE Telemetry Guardrails

For all Kubernetes and GKE requests, read the `references/kubernetes_*.md` files
and respond directly. Do not search the workspace for additional files before
answering. **Do NOT search the codebase for external Terraform modules or extra
reference files, and do NOT write `.tf` files to disk unless the user explicitly
specifies a target file path.**

1.  **Mandatory KSM Permission Guardrail (Tier 2 `kube_*` metrics)**: In Google
    Cloud Managed Service for Prometheus (GMP), billing is based on **samples
    ingested**. Deploying open-source `kube-state-metrics (KSM)` unmodified
    scrapes state for every object across the cluster, generating high
    time-series volume and significant ingestion cost. If the requested alert
    uses KSM metrics (`kube_deployment_*`, `kube_statefulset_*`,
    `kube_daemonset_*`, `kube_cronjob_*`, `kube_job_*`,
    `kube_persistentvolume_*`, `kube_pod_status_phase`,
    `kube_pod_container_resource_limits`), you **MUST NOT assume KSM is enabled
    or write or apply any Terraform files**. At the very top of your response,
    you MUST:
    *   **(a) Alert the user** that the policy requires `kube-state-metrics (KSM)`.
    *   **(b) Explain the GMP cost impact**: Explain that KSM incurs billable
        Managed Service for Prometheus (GMP) sample ingestion costs (see
        [Cloud Monitoring pricing](https://cloud.google.com/products/observability/pricing)).
    *   **(c) Ask a direct question in second-person for explicit permission**
        (literally include this exact question in bold):
        **"Do you grant explicit permission to enable and ingest kube-state-metrics (KSM) in your cluster for this alert?"**
        *(Critical: Never phrase this as a passive statement such as "ensure you
        have approved KSM" or "before enabling KSM, review below" — always ask
        the user directly with a question mark!)*
    *   **(d) Recommend a filtered `PodMonitoring` allowlist**
        (`metricRelabeling` with `action: keep`) that keeps only the required
        metrics (along with any conditional draft HCL clearly marked as pending
        approval), and offer **Non-KSM Native Alternatives** where possible.
2.  **Tier 1 Native Metrics (Zero KSM Surcharge)**: For native cAdvisor,
    Kubelet, or Control Plane metrics (`container_memory_working_set_bytes`,
    `container_spec_memory_limit_bytes`,
    `kube_pod_container_status_restarts_total`,
    `kubernetes.io/container/restart_count`, `kube_node_status_condition`,
    `kubelet_volume_stats_available_bytes`, `apiserver_*`, `rest_client_*`),
    explicitly state that the metric is a **Tier 1 native/standard metric with
    zero KSM cost surcharge** (a **Tier 1 Kubelet/cAdvisor metric that does not
    require kube-state-metrics** or a **Tier 1 Control Plane metric with zero
    KSM cost surcharge**), explain that container resource limits
    (`resources.limits`) must be defined in pod specs for saturation alerts to
    resolve, and provide a clear plain-English explanation of the alert and
    thresholds.
3.  **Mandatory Terraform Variables (`project_id`, `cluster_name`, `namespace`)
    and `user_labels`**: In EVERY Kubernetes Terraform HCL configuration
    (including multi-service latency and SLO burn-rate alerts), you **MUST**
    define `variable "project_id"`, `variable "cluster_name"`, and `variable
    "namespace"` blocks, interpolate all three (`var.project_id`,
    `${var.cluster_name}`, `${var.namespace}`), and include `user_labels = {
    "created-with-google-skill" = "cloud-monitoring-alert-configuration" }` in
    every `google_monitoring_alert_policy` resource.

```mermaid
flowchart TD
    A["User Request for Alert Policy"] --> B{"Can alert use Native GKE or cAdvisor?"}
    B -->|Yes - Tier 1| C["Use Native GKE or cAdvisor Metric (Zero KSM Surcharge)"]
    B -->|No - Requires KSM| D["Alert User on KSM Cost and Ask Explicit Permission Question"]
    D --> E{"User Approved KSM?"}
    E -->|No or Pending| F["Do NOT Write Files to Disk; Show Filtered PodMonitoring Allowlist and Conditional Preview Only"]
    E -->|Yes - Tier 2| G["Generate KSM Alert Policy and Recommend Filtered PodMonitoring Allowlist"]
```

### Classify Telemetry Tiers and Optimize Ingestion Costs

*   **Tier 1: Native GKE Built-ins and cAdvisor (Zero KSM Cost)**: Metrics
    collected natively by GKE, Kubelet/cAdvisor, or Control Plane without
    `kube-state-metrics` (zero KSM cost surcharge).
*   **Tier 2: Filtered KSM (Requires Explicit Consent Question and Allowlist)**:
    Rules requiring Kubernetes control-plane state (such as Deployment,
    StatefulSet, DaemonSet, CronJob, Job, PersistentVolume, or Pod phase
    metrics) that require `kube-state-metrics`.

#### Filter Tier 2 Metrics with a PodMonitoring Allowlist

When a Tier 2 (KSM) alert is requested, ALWAYS ask the user for explicit
permission first and provide a filtered `PodMonitoring` resource (to be used if
KSM is approved) that scrapes only the required metrics and drops all others:

```yaml
apiVersion: monitoring.googleapis.com/v1
kind: PodMonitoring
metadata:
  name: kube-state-metrics-filtered
  namespace: kube-system
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: kube-state-metrics
  endpoints:
  - port: http-metrics
    interval: 30s
    metricRelabeling:
    - action: keep
      sourceLabels: [__name__]
      regex: "^(kube_deployment_spec_replicas|kube_deployment_status_replicas_available|kube_statefulset_status_replicas_ready|kube_statefulset_status_replicas)$"
```

---

## Query Native GKE System Metrics

Below are the public native GKE telemetry metrics (`kubernetes.io/`) available
in Cloud Monitoring.

### Monitor Container and Pod Core Metrics

| Metric Path | Unit | Description | Cost Tier |
| :--- | :--- | :--- | :--- |
| `kubernetes.io/container/cpu/core_usage_time` | `s` | Cumulative CPU time consumed by the container. | Tier 1 (Native) |
| `kubernetes.io/container/cpu/limit_cores` | `1` | CPU core limit configured for the container. | Tier 1 (Native) |
| `kubernetes.io/container/cpu/request_cores` | `1` | CPU core request configured for the container. | Tier 1 (Native) |
| `kubernetes.io/container/memory/used_bytes` | `By` | Total memory currently used by the container. | Tier 1 (Native) |
| `kubernetes.io/container/memory/limit_bytes` | `By` | Memory limit configured for the container. | Tier 1 (Native) |
| `kubernetes.io/container/memory/request_bytes` | `By` | Memory request configured for the container. | Tier 1 (Native) |
| `kubernetes.io/container/memory/page_fault_count` | `1` | Cumulative count of memory page faults. | Tier 1 (Native) |
| `kubernetes.io/container/restart_count` | `1` | Number of times the container has restarted. | Tier 1 (Native) |
| `kubernetes.io/container/uptime` | `s` | Duration the container has been running. | Tier 1 (Native) |
| `kubernetes.io/container/ephemeral_storage/used_bytes` | `By` | Local ephemeral storage used by container. | Tier 1 (Native) |
| `kubernetes.io/container/ephemeral_storage/limit_bytes` | `By` | Ephemeral storage limit for container. | Tier 1 (Native) |
| `kubernetes.io/pod/network/received_bytes_count` | `By` | Cumulative bytes received by pod network interface. | Tier 1 (Native) |
| `kubernetes.io/pod/network/sent_bytes_count` | `By` | Cumulative bytes sent by pod network interface. | Tier 1 (Native) |
| `kubernetes.io/pod/volume/used_bytes` | `By` | Persistent volume storage used by pod. | Tier 1 (Native) |
| `kubernetes.io/pod/volume/total_bytes` | `By` | Total persistent volume storage capacity. | Tier 1 (Native) |

### Monitor Node and Infrastructure Core Metrics

| Metric Path | Unit | Description | Cost Tier |
| :--- | :--- | :--- | :--- |
| `kubernetes.io/node/cpu/allocatable_cores` | `1` | Total allocatable CPU cores on the node. | Tier 1 (Native) |
| `kubernetes.io/node/cpu/total_cores` | `1` | Total physical CPU cores on the node. | Tier 1 (Native) |
| `kubernetes.io/node/cpu/core_usage_time` | `s` | Cumulative CPU core seconds used across node. | Tier 1 (Native) |
| `kubernetes.io/node/memory/allocatable_bytes` | `By` | Total allocatable memory on the node. | Tier 1 (Native) |
| `kubernetes.io/node/memory/used_bytes` | `By` | Total memory currently used on the node. | Tier 1 (Native) |
| `kubernetes.io/node/status` | `1` | Current operational status of the node. | Tier 1 (Native) |
| `kubernetes.io/node/status_condition` | `1` | Condition status (Ready, MemoryPressure, DiskPressure). | Tier 1 (Native) |
| `kubernetes.io/node/ephemeral_storage/used_bytes` | `By` | Ephemeral storage bytes used on node filesystem. | Tier 1 (Native) |
| `kubernetes.io/node/pid_used` / `pid_limit` | `1` | PIDs used compared to maximum PID limit on node. | Tier 1 (Native) |

### Monitor Autoscaling and Hardware Accelerator Metrics

| Metric Path | Unit | Description | Cost Tier |
| :--- | :--- | :--- | :--- |
| `kubernetes.io/autoscaler/container/cpu/per_replica_recommended_request_cores` | `1` | VPA recommended CPU request per replica. | Tier 1 (Native) |
| `kubernetes.io/autoscaler/container/memory/per_replica_recommended_request_bytes` | `By` | VPA recommended memory request per replica. | Tier 1 (Native) |
| `kubernetes.io/autoscaler/recommenders/horizontal/target_value` | `1` | HPA target metric value for autoscaling. | Tier 1 (Native) |
| `kubernetes.io/container/accelerator/duty_cycle` | `%` | GPU/TPU accelerator execution duty cycle. | Tier 1 (Native) |
| `kubernetes.io/container/accelerator/memory_used` | `By` | GPU/TPU accelerator memory allocated. | Tier 1 (Native) |

---

## Map Open Source Kubernetes Alert Rules

Compiled from the open-source `awesome-prometheus-alerts` community catalog.

### Configure Node Health and Capacity Alerts

| Alert Name | Open Source PromQL Rule | Severity | KSM Required? | Non-KSM Native Alternative Available? |
| :--- | :--- | :--- | :--- | :--- |
| **Kubernetes Node not ready** | `kube_node_status_condition{condition="Ready",status="true"} == 0` | Critical | No (Standard) | Yes (Tier 1 PromQL / native node status) |
| **Kubernetes Node scheduling disabled** | `kube_node_spec_taint{key="node.kubernetes.io/unschedulable"} == 1` | Warning | No (Standard) | Yes |
| **Kubernetes Node memory pressure** | `kube_node_status_condition{condition="MemoryPressure",status="true"} == 1` | Critical | No (Standard) | Yes |
| **Kubernetes Node disk pressure** | `kube_node_status_condition{condition="DiskPressure",status="true"} == 1` | Critical | No (Standard) | Yes |
| **Kubernetes Node network unavailable** | `kube_node_status_condition{condition="NetworkUnavailable",status="true"} == 1` | Critical | No (Standard) | Yes |
| **Kubernetes Node out of pod capacity** | `sum by (node) ((kube_pod_status_phase{phase="Running"} == 1) + on(uid, instance) group_left(node) (0 * kube_pod_info{pod_template_hash=""})) / sum by (node) (kube_node_status_allocatable{resource="pods"}) * 100 > 90` | Warning | **Yes (KSM)** | Yes (Approximate using cAdvisor pod count) |

### Configure Workload and Container Reliability Alerts

| Alert Name | Open Source PromQL Rule | Severity | KSM Required? | Non-KSM Native Alternative Available? |
| :--- | :--- | :--- | :--- | :--- |
| **Kubernetes Pod crash looping** | `increase(kube_pod_container_status_restarts_total[15m]) > 3` | Warning | No (cAdvisor) | Yes (`kubernetes.io/container/restart_count`) |
| **Kubernetes Pod not healthy** | `sum by (namespace, pod) (kube_pod_status_phase{phase=~"Pending\|Unknown\|Failed"}) > 0` | Critical | **Yes (KSM)** | Partial (Native pod availability metrics) |
| **Kubernetes Container OOMKiller** | `(kube_pod_container_status_restarts_total - kube_pod_container_status_restarts_total offset 10m >= 1) and ignoring (reason) min_over_time(kube_pod_container_status_last_terminated_reason{reason="OOMKilled"}[10m]) == 1` | Warning | **Yes (KSM)** | Yes (Memory usage > 95% of container limit) |
| **Kubernetes Deployment replicas mismatch** | `kube_deployment_spec_replicas != kube_deployment_status_replicas_available` | Warning | **Yes (KSM)** | No exact match without KSM (Control Plane state) |
| **Kubernetes StatefulSet replicas mismatch** | `kube_statefulset_status_replicas_ready != kube_statefulset_status_replicas` | Warning | **Yes (KSM)** | No exact match without KSM |
| **Kubernetes StatefulSet down** | `kube_statefulset_replicas != kube_statefulset_status_replicas_ready > 0` | Critical | **Yes (KSM)** | No exact match without KSM |
| **Kubernetes Deployment generation mismatch** | `kube_deployment_status_observed_generation != kube_deployment_metadata_generation` | Critical | **Yes (KSM)** | Requires KSM |
| **Kubernetes StatefulSet update not rolled out** | `max without (revision) (kube_statefulset_status_current_revision unless kube_statefulset_status_update_revision) * (kube_statefulset_replicas != kube_statefulset_status_replicas_updated)` | Warning | **Yes (KSM)** | Requires KSM |
| **Kubernetes DaemonSet rollout stuck** | `(kube_daemonset_status_number_ready / kube_daemonset_status_desired_number_scheduled * 100 < 100) or (kube_daemonset_status_desired_number_scheduled - kube_daemonset_status_current_number_scheduled > 0)` | Warning | **Yes (KSM)** | Requires KSM |
| **Kubernetes DaemonSet misscheduled** | `kube_daemonset_status_number_misscheduled > 0` | Critical | **Yes (KSM)** | Requires KSM |

### Configure Job CronJob and Storage Alerts

| Alert Name | Open Source PromQL Rule | Severity | KSM Required? | Non-KSM Native Alternative Available? |
| :--- | :--- | :--- | :--- | :--- |
| **Kubernetes Job failed** | `kube_job_status_failed > 0` | Warning | **Yes (KSM)** | Requires KSM |
| **Kubernetes Job not starting** | `kube_job_status_active == 0 and kube_job_status_failed == 0 and kube_job_status_succeeded == 0 and (time() - kube_job_status_start_time) > 600` | Warning | **Yes (KSM)** | Requires KSM |
| **Kubernetes CronJob failing** | `(kube_cronjob_status_last_schedule_time > kube_cronjob_status_last_successful_time) AND (kube_cronjob_status_active == 0) AND (kube_cronjob_spec_suspend == 0)` | Critical | **Yes (KSM)** | Requires KSM |
| **Kubernetes Volume out of disk space** | `kubelet_volume_stats_available_bytes / kubelet_volume_stats_capacity_bytes * 100 < 10 and kubelet_volume_stats_capacity_bytes > 0` | Warning | No (Kubelet) | Yes (`kubernetes.io/pod/volume/used_bytes`) |
| **Kubernetes Volume full in four days** | `predict_linear(kubelet_volume_stats_available_bytes[6h:5m], 4 * 24 * 3600) < 0` | Critical | No (Kubelet) | Yes |
| **Kubernetes PersistentVolume error** | `kube_persistentvolume_status_phase{phase=~"Failed\|Pending"} > 0` | Critical | **Yes (KSM)** | Requires KSM |

### Configure API Server and Control Plane Alerts

| Alert Name | Open Source PromQL Rule | Severity | KSM Required? | Non-KSM Native Alternative Available? |
| :--- | :--- | :--- | :--- | :--- |
| **Kubernetes API server errors** | `sum(rate(apiserver_request_total{job="apiserver",code=~"(?:5..)"}[1m])) by (instance, job) / sum(rate(apiserver_request_total{job="apiserver"}[1m])) by (instance, job) * 100 > 3 and sum(rate(apiserver_request_total{job="apiserver"}[1m])) by (instance, job) > 0` | Critical | No | Yes (Native Control Plane PromQL) |
| **Kubernetes API client errors** | `(sum(rate(rest_client_requests_total{code=~"(4\|5).."}[1m])) by (instance, job) / sum(rate(rest_client_requests_total[1m])) by (instance, job)) * 100 > 1 and sum(rate(rest_client_requests_total[1m])) by (instance, job) > 0` | Critical | No | Yes (Native Control Plane PromQL) |
| **Kubernetes client certificate expires soon** | `apiserver_client_certificate_expiration_seconds_count{job="apiserver"} > 0 and histogram_quantile(0.01, sum by (job, le) (rate(apiserver_client_certificate_expiration_seconds_bucket{job="apiserver"}[5m]))) < 24*60*60` | Critical | No | Yes (Native Control Plane PromQL) |
| **Kubernetes API server latency** | `histogram_quantile(0.99, sum(rate(apiserver_request_duration_seconds_bucket{verb!~"(?:CONNECT\|WATCHLIST\|WATCH\|PROXY)"}[10m])) WITHOUT (subresource)) > 1` | Warning | No | Yes (Native Control Plane PromQL) |

---

## Implement Non KSM Native Alternative Alerts

When a user requests open-source catalog alerts that normally rely on
`kube-state-metrics`, first offer these **Tier 1 (Non-KSM)** equivalents to
avoid customer ingestion costs:

### Alert on Container Memory Saturation and OOM Risk

Instead of `container_memory_working_set_bytes /
kube_pod_container_resource_limits`, use native cAdvisor limits:

```promql
sum(
  container_memory_working_set_bytes{
    cluster="${var.cluster_name}",
    namespace="${var.namespace}",
    container!=""
  }
) by (pod, container)
/
sum(
  container_spec_memory_limit_bytes{
    cluster="${var.cluster_name}",
    namespace="${var.namespace}",
    container!=""
  }
) > 0.90
```

> [!NOTE] **Memory Compared to CPU Saturation**: In Kubernetes, CPU is
> compressible and throttled by the CFS scheduler without killing containers.
> Memory is uncompressible and triggers fatal OOMKilled events. Therefore,
> cluster saturation alerting focuses on **Memory Saturation**, and CPU
> saturation alerts (and `container_cpu_usage_seconds_total`) are excluded from
> the recommended cluster alert suite.

### Alert on Pod CrashLoopBackOff and Container Restarts

Use native GKE Cloud Monitoring metric `kubernetes.io/container/restart_count`
or the cAdvisor restart counter:

```promql
sum(
  increase(
    kube_pod_container_status_restarts_total{
      cluster="${var.cluster_name}",
      namespace="${var.namespace}"
    }[15m]
  )
) by (pod, container) > 3
```

*   **Duration Rule**: Set Terraform `duration = "0s"` (or `"60s"`). The `[15m]`
    lookback window already smooths transient spikes; adding `duration = "300s"`
    delays critical crashloop alerts by 20 minutes total.

### Alert on Node Readiness and Health

```promql
kube_node_status_condition{
  cluster="${var.cluster_name}",
  condition="Ready",
  status="true"
} == 0
```

### Alert on Multi Window Multi Burn Rate SLO Error Rates

For service error rate monitoring, use multi-window burn rate alerts instead of
simple static ratios:

> [!IMPORTANT] **Service availability and latency SLOs are owned by the
> `google-cloud-slo-alert-configuration` skill.** Delegate to it whenever the
> user asks for an SLO, an error budget, or burn-rate alerting on a GKE service.
> The full handoff contract, the SLI source table, and the fallback variants —
> including the Medium (`6.0`, 6h/30m) and Slow (`1.0`, 3d/6h) burn rates — are
> in [kubernetes_promql_queries.md](kubernetes_promql_queries.md). If you emit
> the fallback queries, your response MUST still name
> `google-cloud-slo-alert-configuration` as the owner of SLO configuration and
> state that what you emitted is a local fallback.

```promql
(
  (
    sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}", status=~"5.."}[5m])) by (service)
    /
    sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}"}[5m])) by (service)
  ) > (1 - ${var.slo_target}) * 14.4
)
and
(
  (
    sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}", status=~"5.."}[1h])) by (service)
    /
    sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}"}[1h])) by (service)
  ) > (1 - ${var.slo_target}) * 14.4
)
```

### Detect Traffic Outages

Avoid brittle `== 0` comparisons. Use `default 0` or `absent()` to detect total
traffic loss:

```promql
(sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}"}[5m])) by (service) default 0) == 0
and
(sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}"}[5m] offset 1w)) by (service)) > 1
```
kubernetes_promql_queries.md 18.2 KB
# Write PromQL Queries for Kubernetes Alerting

This document provides best-practice PromQL queries for monitoring Kubernetes
clusters and services, organized by the Golden Signals and key Cluster Health
metrics.

All queries are designed to be used with **Google Cloud Managed Service for
Prometheus (GMP)** and can be deployed through Cloud Monitoring alerting
policies using `condition_prometheus_query_language`.

# Table of Contents

- [Enforce Mandatory Kubernetes and GKE Alerting Guardrails](#enforce-mandatory-kubernetes-and-gke-alerting-guardrails): Lines 32-133
- [Alert on Latency](#alert-on-latency): Lines 134-177
  - [Query Standard Prometheus HTTP Latency Metrics](#query-standard-prometheus-http-latency-metrics): Lines 139-153
  - [Query OpenTelemetry HTTP Latency Metrics](#query-opentelemetry-http-latency-metrics): Lines 154-177
- [Alert on Traffic Rate and Outages](#alert-on-traffic-rate-and-outages): Lines 178-250
  - [Query Request Rate](#query-request-rate): Lines 183-195
  - [Detect Traffic Drops and Outages](#detect-traffic-drops-and-outages): Lines 196-250
  - [Compare Historical Traffic Using Default Zero](#compare-historical-traffic-using-default-zero): Lines 207-235
  - [Detect Missing Series Using Absent](#detect-missing-series-using-absent): Lines 236-250
- [Alert on Multi Window Multi Burn Rate SLO Errors](#alert-on-multi-window-multi-burn-rate-slo-errors): Lines 251-481
  - [Configure a Fast Burn Rate Alert](#configure-a-fast-burn-rate-alert): Lines 315-370
  - [Configure a Medium Burn Rate Alert](#configure-a-medium-burn-rate-alert): Lines 371-424
  - [Configure a Slow Burn Rate Alert](#configure-a-slow-burn-rate-alert): Lines 425-481
- [Alert on Memory Saturation](#alert-on-memory-saturation): Lines 482-522
  - [Calculate Memory Utilization Against Limits](#calculate-memory-utilization-against-limits): Lines 491-522
- [Monitor Cluster Health and Infrastructure](#monitor-cluster-health-and-infrastructure): Lines 523-562
  - [Alert on Pod CrashLooping and Container Restarts](#alert-on-pod-crashlooping-and-container-restarts): Lines 527-547
  - [Alert on Unready Kubernetes Nodes](#alert-on-unready-kubernetes-nodes): Lines 548-562

## Enforce Mandatory Kubernetes and GKE Alerting Guardrails

For all Kubernetes and GKE requests, read the relevant
`references/kubernetes_*.md` files and respond directly. Do not search the
workspace for additional files before answering. **Do NOT search the codebase
for external Terraform modules or extra reference files, and do NOT write `.tf`
files to disk unless the user explicitly specifies a target file path.** When
configuring Kubernetes alerts, you MUST:

1.  **Mandatory KSM Permission Guardrail (Tier 2 `kube_*` metrics)**: If the
    requested alert uses `kube-state-metrics (KSM)` metrics
    (`kube_deployment_*`, `kube_statefulset_*`, `kube_daemonset_*`,
    `kube_cronjob_*`, `kube_job_*`, `kube_persistentvolume_*`,
    `kube_pod_status_phase`, `kube_pod_container_resource_limits`), you **MUST
    NOT assume KSM is enabled or write or apply any Terraform files** (see
    [kubernetes_metrics_and_alerts_catalog.md](kubernetes_metrics_and_alerts_catalog.md)).
    At the very top of your response, you MUST: (a) alert the user that the
    policy requires `kube-state-metrics (KSM)`, (b) explain that KSM incurs
    billable Managed Service for Prometheus (GMP) sample ingestion costs (see
    [Cloud Monitoring pricing](https://cloud.google.com/products/observability/pricing)),
    (c) **ask the user a direct question in second-person asking for explicit
    permission** (literally include: **"Do you grant explicit permission to
    enable and ingest kube-state-metrics (KSM) in your cluster for this
    alert?"** — never phrase this as a passive statement such as "ensure you
    have approved KSM"), and (d) recommend a filtered `PodMonitoring` allowlist
    (`metricRelabeling` with `action: keep`) that keeps only the required
    metrics (along with any conditional draft HCL clearly marked as pending
    approval).
2.  **Tier 1 Native Metrics (Zero KSM Surcharge)**: For native cAdvisor,
    Kubelet, or Control Plane metrics (`container_memory_working_set_bytes`,
    `container_spec_memory_limit_bytes`,
    `kube_pod_container_status_restarts_total`,
    `kubernetes.io/container/restart_count`, `kube_node_status_condition`,
    `kubelet_volume_stats_available_bytes`, `apiserver_*`, `rest_client_*`),
    explicitly state that the metric is a **Tier 1 native/standard metric with
    zero KSM cost surcharge** (a **Tier 1 Kubelet/cAdvisor metric that does not
    require kube-state-metrics** or a **Tier 1 Control Plane metric with zero
    KSM cost surcharge**), explain that container resource limits
    (`resources.limits`) must be defined in pod specs for saturation alerts to
    resolve, and provide a clear plain-English explanation of the alert and
    thresholds.
3.  **Mandatory Terraform Variables (`project_id`, `cluster_name`, `namespace`)
    and `user_labels`**: In EVERY Kubernetes Terraform HCL configuration
    (including cluster-wide and multi-service latency and SLO alerts), you
    **MUST** define `variable "project_id"`, `variable "cluster_name"`, and
    `variable "namespace"` blocks, interpolate all three (`var.project_id`,
    `${var.cluster_name}`, `${var.namespace}`), and include `user_labels = {
    "created-with-google-skill" = "cloud-monitoring-alert-configuration" }` in
    every `google_monitoring_alert_policy` resource:

```hcl
variable "project_id" {
  type    = string
  default = "my-gcp-project"
}

variable "cluster_name" {
  type    = string
  default = "my-gke-cluster"
}

variable "namespace" {
  type    = string
  default = "default"
}

variable "slo_target" {
  type    = number
  default = 0.99
}

resource "google_monitoring_alert_policy" "k8s_alert_example" {
  project      = var.project_id
  display_name = "[K8s] ${var.cluster_name} - Example Alert"
  combiner     = "OR"

  conditions {
    display_name = "PromQL Condition"
    condition_prometheus_query_language {
      query                     = <<-EOT
        # Insert PromQL query filtering by cluster="${var.cluster_name}" and namespace="${var.namespace}"
      EOT
      duration                  = "300s"
      disable_metric_validation = true
    }
  }

  user_labels = {
    "created-with-google-skill" = "cloud-monitoring-alert-configuration"
  }
}
```

4.  **Validate Kubernetes HCL and PromQL Configurations**: When validating or
    deduplicating existing Kubernetes `.tf` files on disk, run `python3
    scripts/kubernetes/validate_config.py --file <path_to_tf_file>` (for a
    single file) or `python3 scripts/kubernetes/validate_config.py --directory
    <path_to_tf_dir>` (to check a directory for PromQL syntax errors, missing
    Kubernetes resource labels, and duplicate signal targets).

---

## Alert on Latency

Monitors the 95th percentile (P95) of HTTP request duration to detect slow
responses.

### Query Standard Prometheus HTTP Latency Metrics

```promql
histogram_quantile(0.95,
  sum(
    rate(
      http_request_duration_seconds_bucket{
        cluster="${var.cluster_name}",
        namespace="${var.namespace}"
      }[5m]
    )
  ) by (le, service, ingress)
) > 2.0
```

### Query OpenTelemetry HTTP Latency Metrics

If your application is instrumented with OpenTelemetry, it might use
`http_server_request_duration_milliseconds`:

```promql
histogram_quantile(0.95,
  sum(
    rate(
      http_server_request_duration_milliseconds_bucket{
        cluster="${var.cluster_name}",
        namespace="${var.namespace}"
      }[5m]
    )
  ) by (le, service)
) > 2000
```

*   **Threshold**: `2.0` seconds (or `2000` ms). Adjust based on latency target.
*   **Buffer**: Use `duration = "300s"` in the alert policy for instantaneous
    percentiles or `duration = "0s"` when multi-window smoothing is applied.

---

## Alert on Traffic Rate and Outages

Monitors the volume of requests to detect sudden drops (indicating outage) or
overload spikes.

### Query Request Rate

```promql
sum(
  rate(
    http_requests_total{
      cluster="${var.cluster_name}",
      namespace="${var.namespace}"
    }[5m]
  )
) by (service)
```

### Detect Traffic Drops and Outages

> [!WARNING] **The `== 0` Metric Disappearance Gotcha**: When a service
> experiences a total traffic outage, HTTP requests stop entirely and Prometheus
> stops emitting the `http_requests_total` metric series. Evaluating
> `rate(...) == 0` returns an **empty vector** (no data) rather than a `0`
> value, so the alert will **fail to fire**.

To reliably detect a complete traffic loss, use **`default 0`** or
**`absent()`**:

#### Compare Historical Traffic Using Default Zero

Fires if current 5m traffic is zero when historical traffic 1 week ago was
active (> 1 QPS):

```promql
(
  sum(
    rate(
      http_requests_total{
        cluster="${var.cluster_name}",
        namespace="${var.namespace}"
      }[5m]
    )
  ) by (service) default 0
) == 0
and
(
  sum(
    rate(
      http_requests_total{
        cluster="${var.cluster_name}",
        namespace="${var.namespace}"
      }[5m] offset 1w
    )
  ) by (service)
) > 1
```

#### Detect Missing Series Using Absent

Fires if the metric series is completely absent:

```promql
absent(
  http_requests_total{
    cluster="${var.cluster_name}",
    namespace="${var.namespace}"
  }
) == 1
```

---

## Alert on Multi Window Multi Burn Rate SLO Errors

Monitors service reliability against defined Service Level Objectives (SLOs)
using **Multi-Window Multi-Burn-Rate (MWMBR)** alerts.

**Service availability and latency SLOs are owned by the
`google-cloud-slo-alert-configuration` skill.** Delegate to it whenever the user
asks for an SLO, an error budget, or burn-rate alerting on a GKE service. That
skill owns the SLO wizard, the burn-rate templates
(`references/promql_templates.md`), the SLI mapping
(`references/service_metrics.md`), and the App Hub scoping labels
(`references/app_hub_labels.md`).

**Context to hand off** (so the SLO skill does not repeat discovery):

*   **Resource type**: GKE service (`prometheus_target` / App Hub service).
*   **Grouping labels**: `cluster`, `namespace`, `service`.
*   **Availability SLI**: the request metric the workload actually emits — see
    the table below.
*   **SLO target**: the user's target, or `0.999` (99.9%) if they did not give
    one.

**Resolve the SLI source before delegating.** GKE has no single default
availability SLI — which metric exists depends on how the workload is
instrumented:

| SLI source | Metric | When it applies |
| :--- | :--- | :--- |
| App Hub registered service | `service:server_request_count` | Service is registered in an App Hub application |
| OTLP or Prometheus sidecar | `http_requests_total` | Workload exports its own HTTP request counter |
| Istio or Anthos Service Mesh | `istio_requests_total` | Mesh-managed traffic |

> [!IMPORTANT] If you cannot determine which of these the cluster emits, you
> MUST **ask the user which request metric their services expose** and say so
> explicitly in your response. Do not silently assume one.

**Fallback** — only if `google-cloud-slo-alert-configuration` is not installed:
use the burn-rate queries below, which are a complete solution on their own.
Even then, your response MUST name `google-cloud-slo-alert-configuration` as the
owner of SLO configuration, state that what you emitted is a local fallback, and
list the handoff context above. Never silently present SLO policies as if this
skill owned them.

> [!NOTE] **Why SLO Burn Rates over Simple Ratios?** Simple static error ratios
> (such as `rate(5xx)/rate(total) > 5%`) cause severe alert fatigue during
> low-traffic periods (where 1 error out of 2 requests = 50%) and fail to detect
> slow, steady error budget drains. Multi-window burn rates evaluate both a
> short-term window (to ensure the outage is currently active) and a long-term
> window (to ensure significant error budget consumption).

The threshold formula is: \[ \text{Threshold} = (1 - \text{SLO\_TARGET}) \times
\text{BURN\_RATE\_FACTOR} \]

> [!WARNING] **Do not mix up the tiers.** When you emit the standard two-policy
> burn-rate pair, it is **Fast Burn** (factor `14.4`, `1h` and `5m`) plus
> **Slow Burn** (factor `1.0`, `3d` and `6h`). **Medium Burn** (factor `6.0`,
> `6h` and `30m`) is an optional third tier — never substitute it for Slow Burn
> and never label a `6.0` / `6h` and `30m` policy "Slow Burn".

> [!IMPORTANT] **Parameterize the SLO target.** Generated Terraform MUST declare
> a `variable "slo_target"` and substitute `(1 - var.slo_target)` (or `(1 -
> ${var.slo_target})` inside a heredoc) in every burn-rate threshold. Never
> hardcode the error budget in the emitted PromQL.

### Configure a Fast Burn Rate Alert

*   **Burn Rate Factor**: `14.4` (Consumes 2% of a 30-day error budget in 1
    hour)
*   **Windows**: Long window = `1h`, Short window = `5m`
*   **Duration**: `0s` (the dual lookback windows already smooth transient
    spikes)

```promql
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[5m]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[5m]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 14.4
)
and
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[1h]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[1h]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 14.4
)
```

### Configure a Medium Burn Rate Alert

*   **Burn Rate Factor**: `6.0` (Consumes 5% of error budget in 6 hours)
*   **Windows**: Long window = `6h`, Short window = `30m`
*   **Duration**: `0s`

```promql
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[30m]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[30m]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 6.0
)
and
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[6h]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[6h]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 6.0
)
```

### Configure a Slow Burn Rate Alert

*   **Burn Rate Factor**: `1.0` (Consumes 10% of error budget in 3 days)
*   **Windows**: Long window = `3d`, Short window = `6h`
*   **Duration**: Omit the `duration` field entirely (Cloud Monitoring rejects a
    retest buffer when the lookback window exceeds 25 hours).

```promql
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[6h]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[6h]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 1.0
)
and
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[3d]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[3d]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 1.0
)
```

---

## Alert on Memory Saturation

In Kubernetes, CPU is compressible and throttled by CFS quotas rather than
causing container termination. Memory saturation, however, is uncompressible and
directly causes Out-Of-Memory (`OOMKilled`) pod terminations. Therefore,
Kubernetes cluster saturation alerting focuses on **Memory Saturation**. (CPU
saturation alerts and `container_cpu_usage_seconds_total` are not recommended
for cluster alert policies).

### Calculate Memory Utilization Against Limits

Uses `container_memory_working_set_bytes` (active memory plus unevictable
caches) compared to the configured limit `container_spec_memory_limit_bytes`:

```promql
sum(
  container_memory_working_set_bytes{
    cluster="${var.cluster_name}",
    namespace="${var.namespace}",
    container!=""
  }
) by (pod, container)
/
sum(
  container_spec_memory_limit_bytes{
    cluster="${var.cluster_name}",
    namespace="${var.namespace}",
    container!=""
  }
) by (pod, container) > 0.9
```

*   **Cost Tier**: Tier 1 Kubelet/cAdvisor metric that does not require
    kube-state-metrics (Zero KSM cost).
*   **Buffer**: `duration = "300s"` to allow short-lived memory spikes.
*   **Prerequisite**: Workload pod specs MUST configure explicit memory limits
    (`resources.limits.memory`) or this query will return `NaN` and fail to
    resolve.

---

## Monitor Cluster Health and Infrastructure

Critical infrastructure alerts that impact service reliability.

### Alert on Pod CrashLooping and Container Restarts

Alerts if a pod is restarting frequently, indicating crash loops (such as
OOMKilled events, panics, or configuration errors).

```promql
sum(
  increase(
    kube_pod_container_status_restarts_total{
      cluster="${var.cluster_name}",
      namespace="${var.namespace}"
    }[15m]
  )
) by (pod, container) > 3
```

*   **Duration**: Set Terraform `duration = "0s"` (or `"60s"`).
    *   **Crucial Rule**: The `[15m]` lookback window already smooths out
        spikes. Adding a `300s` duration causes a 20-minute delay before
        critical crashloop alerts fire.

### Alert on Unready Kubernetes Nodes

Alerts if a Kubernetes node enters an unhealthy state.

```promql
kube_node_status_condition{
  cluster="${var.cluster_name}",
  condition="Ready",
  status="true"
} == 0
```

*   **Trigger**: When the value is `0`, the node is NotReady.
*   **Buffer**: Use `duration = "300s"` to account for transient network blips
    or node drainage during GKE node pool upgrades.
scripts/agent_platform/
analyze_traffic.py 12.8 KB
#!/usr/bin/env python3
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Traffic metrics analyzer for Agent Platform agents (using OpenTelemetry).

Computes zero-ratio, variance ratio, and 1-week autocorrelation on a 14-day
metrics time series (at 5-minute intervals) and classifies the traffic pattern
to recommend the optimal dynamic PromQL alerting threshold strategy.
"""

import argparse
import json
import math
import statistics
import sys
import time

try:
  from google.auth import exceptions as auth_exceptions  # pytype: disable=import-error  # pyrefly: ignore[missing-import]
  from google.cloud import monitoring_v3  # pytype: disable=import-error  # pyrefly: ignore[missing-import]
except ImportError:
  auth_exceptions = None
  monitoring_v3 = None

# Number of 5-minute data points in a 7-day weekly window
# (12 points/hour * 24 hours/day * 7 days/week)
_POINTS_PER_WEEK = 2016

# Supported metric types and their corresponding resource labels.
_SUPPORTED_METRIC_TYPE_LABEL = {
    "workload.googleapis.com/gen_ai.invoke_agent.duration": (
        "metric.labels.gen_ai_agent_name"
    ),
    "workload.googleapis.com/gen_ai.client.token.usage": (
        "resource.labels.namespace"
    ),
}

_ALIGN_DELTA = (
    monitoring_v3.Aggregation.Aligner.ALIGN_DELTA
    if monitoring_v3 is not None
    else 1
)

# Supported metric types and their corresponding aligners.
_SUPPORTED_METRIC_TYPE_ALIGNER = {
    "workload.googleapis.com/gen_ai.invoke_agent.duration": _ALIGN_DELTA,
    "workload.googleapis.com/gen_ai.client.token.usage": _ALIGN_DELTA,
}

# Supported metric types and their filters for live queries.
_SUPPORTED_METRIC_TYPE_FILTERS = {
    "workload.googleapis.com/gen_ai.invoke_agent.duration": [],
    "workload.googleapis.com/gen_ai.client.token.usage": [],
}


class CredentialsMissingError(Exception):
  """Raised when Google Cloud credentials are not found."""

  pass


def compute_metrics_and_classify(values: list[float]) -> dict[str, float | str]:
  """Computes statistical metrics and classifies the traffic profile.

  Args:
      values: A list of floats representing the 5-minute rate telemetry. Should
        be at least 4032 points (14 days).

  Returns:
      A dictionary with statistical metrics and the classification profile.

  Raises:
      ValueError: If values contains fewer than 4032 points (14 days).
  """
  required_points = 2 * _POINTS_PER_WEEK
  if len(values) < required_points:
    raise ValueError(
        f"Insufficient data points: expected at least {required_points} (14"
        f" days at 5m interval), got {len(values)}"
    )

  # We focus on the last 7 days (latest weekly points) and previous 7 days
  # (weekly points before that)
  last_7_days = values[-_POINTS_PER_WEEK:]
  prev_7_days = values[-required_points:-_POINTS_PER_WEEK]

  # 1. Zero Ratio: proportion of 5m intervals with rate <= 0.01 in the last
  # 7 days
  zero_ratio = sum(x <= 0.01 for x in last_7_days) / _POINTS_PER_WEEK

  # 2. Mean and Standard Deviation of the last 7 days
  mean_last = statistics.mean(last_7_days)
  stddev_last = statistics.pstdev(last_7_days)

  variance_ratio = stddev_last / mean_last if mean_last > 0.0001 else 0.0

  # 3. Autocorrelation at 1-week lag
  mean_prev = statistics.mean(prev_7_days)
  stddev_prev = statistics.pstdev(prev_7_days)

  if stddev_last > 0.0001 and stddev_prev > 0.0001:
    covariance = (
        sum(
            (x - mean_last) * (y - mean_prev)
            for x, y in zip(last_7_days, prev_7_days)
        )
        / _POINTS_PER_WEEK
    )
    autocorr_1w = covariance / (stddev_last * stddev_prev)
  else:
    autocorr_1w = 0.0

  # Decision tree classification
  if mean_last == 0.0 and zero_ratio == 1.0:
    profile = "New Agent / No Traffic"
    algorithm = "Short-Window Z-Score (1h baseline)"
    rationale = (
        "No historical traffic observed. Defaulting to Short-Window Z-Score"
        " (1h baseline) dynamic thresholding to ensure quick activation"
        " (requires 1 hour of traffic history)."
    )
  elif variance_ratio > 2.0:
    profile = "Bursty / Inconsistent"
    algorithm = "Moving Averages"
    rationale = (
        f"Variance ratio is high ({variance_ratio:.2f}), indicating volatile"
        " bursty peaks. Moving averages dynamic baseline thresholds are"
        " recommended to smooth out short-term fluctuations and prevent false"
        " pages."
    )
  elif autocorr_1w > 0.75 and variance_ratio <= 2.0:
    profile = "Seasonal / Cyclical"
    algorithm = "Seasonal Decomposition (average 1w and 1d)"
    rationale = (
        f"Auto-correlation at 1w lag is high ({autocorr_1w:.2f}) with stable"
        f" variance ratio ({variance_ratio:.2f}). Comparing against the average"
        " of 1w and 1d offsets mitigates holiday false positives and prevents"
        " diurnal false alerts during off-peak periods."
    )
  else:
    profile = "Steady / Consistent"
    algorithm = "1w Z-Score Baseline"
    rationale = (
        "Stable regular traffic pattern with low variance ratio"
        f" ({variance_ratio:.2f}) and moderate/low autocorrelation"
        f" ({autocorr_1w:.2f}). 1w Z-Score baseline is ideal."
    )

  return {
      "zero_ratio": round(zero_ratio, 4),
      "variance_ratio": round(variance_ratio, 4),
      "autocorr_1w": round(autocorr_1w, 4),
      "mean": round(mean_last, 4),
      "stddev": round(stddev_last, 4),
      "profile": profile,
      "recommended_algorithm": algorithm,
      "rationale": rationale,
  }


def align_to_grid(
    points: list[tuple[float, float]],
    end_time: float,
    num_points: int = 4032,
    interval_sec: int = 300,
) -> list[float]:
  """Aligns sparse telemetry points to a uniform time grid of fixed size.

  We anchor the grid at end_time aligned to interval_sec and look backward.

  Args:
      points: A list of tuples (timestamp, value).
      end_time: The end timestamp of the grid window.
      num_points: The exact number of points in the target grid.
      interval_sec: The grid interval in seconds.

  Returns:
      A list of floats representing the aligned values in order of time.
  """
  aligned_end = math.floor(end_time / interval_sec) * interval_sec
  aligned_start = aligned_end - num_points * interval_sec

  grid = [0.0] * num_points

  for ts, val in points:
    rounded_ts = round(ts / interval_sec) * interval_sec
    idx = int((rounded_ts - aligned_start) / interval_sec) - 1
    if 0 <= idx < num_points:
      grid[idx] += val

  return grid


def query_live_metrics(
    project_id: str,
    metric_type: str,
    engine_id: str,
) -> list[float]:
  """Queries live metrics (e.g., OTel latency or token usage) for 14 days.

  Args:
      project_id: The GCP project ID.
      metric_type: The metric type to query.
      engine_id: The agent identifier value.

  Returns:
      A list of 4032 floats representing the 5m rate telemetry aligned to grid.

  Raises:
      CredentialsMissingError: If GCP credentials are not found.
  """
  if monitoring_v3 is None or auth_exceptions is None:
    raise CredentialsMissingError(
        "No valid Google Cloud credentials or monitoring client found. Please"
        " run 'gcloud auth application-default login' to authenticate your"
        " local environment."
    )
  try:
    client = monitoring_v3.MetricServiceClient()
    name = f"projects/{project_id}"

    now = time.time()
    seconds_per_day = 24 * 3600
    start_time = now - 14 * seconds_per_day

    interval = monitoring_v3.TimeInterval({
        "end_time": {"seconds": int(now)},
        "start_time": {"seconds": int(start_time)},
    })

    filter_str = (
        f'metric.type = "{metric_type}" AND'
        f" {_SUPPORTED_METRIC_TYPE_LABEL[metric_type]} ="
        f' "{engine_id}"'
    )
    for metric_filter in _SUPPORTED_METRIC_TYPE_FILTERS[metric_type]:
      filter_str += f" AND {metric_filter}"

    results = client.list_time_series(
        request={
            "name": name,
            "filter": filter_str,
            "interval": interval,
            "view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL,
            "aggregation": {
                "alignment_period": {"seconds": 300},
                "per_series_aligner": _SUPPORTED_METRIC_TYPE_ALIGNER[
                    metric_type
                ],
                "cross_series_reducer": (
                    monitoring_v3.Aggregation.Reducer.REDUCE_SUM
                ),
                "group_by_fields": [
                    _SUPPORTED_METRIC_TYPE_LABEL[metric_type]
                ],
            },
        }
    )
  except auth_exceptions.DefaultCredentialsError as e:
    raise CredentialsMissingError(
        "No valid Google Cloud credentials found. Please run 'gcloud auth"
        " application-default login' to authenticate your local environment."
    ) from e

  points = []
  for series in results:
    for point in series.points:
      st = point.interval.start_time
      ts = (
          st.timestamp()
          if hasattr(st, "timestamp")
          else st.ToDatetime().timestamp()
      )
      pb = getattr(point.value, "_pb", point.value)
      val_type = pb.WhichOneof("value")
      if val_type == "distribution_value":
        # Calculate total tokens consumed across all buckets in the interval
        val = float(
            point.value.distribution_value.mean
            * point.value.distribution_value.count
        )
      elif val_type == "int64_value":
        val = float(point.value.int64_value)
      else:
        val = float(point.value.double_value)
      points.append((
          ts,
          val,
      ))

  if not points:
    # No traffic detected at all. Return a 14-day grid filled with 0.0.
    return [0.0] * (2 * _POINTS_PER_WEEK)

  # Align sparse points to the 14-day 5-minute grid
  return align_to_grid(points, now, num_points=2 * _POINTS_PER_WEEK)


def main():
  parser = argparse.ArgumentParser(
      description=(
          "Analyze 14-day traffic metrics to select dynamic thresholding"
          " algorithm."
      )
  )
  parser.add_argument(
      "--metric-type",
      required=True,
      type=str,
      help="The metric type to query.",
  )
  parser.add_argument(
      "--metrics-file",
      type=str,
      help="Path to JSON file containing list of numbers. Use '-' for stdin.",
  )
  parser.add_argument(
      "--live",
      action="store_true",
      help="Force live GCP metrics query validation check.",
  )
  parser.add_argument(
      "--project-id",
      type=str,
      help="GCP project ID (required for live queries).",
  )
  parser.add_argument(
      "--reasoning-engine-id",
      type=str,
      help=(
          "Agent Identifier (e.g., gen_ai_agent_name or namespace) "
          "required for live queries."
      ),
  )
  args = parser.parse_args()

  data = None

  if args.metric_type not in _SUPPORTED_METRIC_TYPE_LABEL:
    print(
        f"Error: Metric type {args.metric_type} is not supported.",
        file=sys.stderr,
    )
    sys.exit(1)

  if args.live:
    if not args.project_id or not args.reasoning_engine_id:
      print(
          "Error: Live GCP queries require --project-id and"
          " --reasoning-engine-id to be specified.",
          file=sys.stderr,
      )
      sys.exit(1)

    try:
      data = query_live_metrics(
          args.project_id, args.metric_type, args.reasoning_engine_id
      )
    except CredentialsMissingError as e:
      print(f"Error: {e}", file=sys.stderr)
      sys.exit(1)
    except Exception as e:
      print(f"Error executing live query: {e}", file=sys.stderr)
      sys.exit(1)

  else:
    # File/Stdin input mode
    if not args.metrics_file and sys.stdin.isatty():
      print(
          "Error: Must specify --metrics-file or pipe metrics data to stdin"
          " when not using --live.",
          file=sys.stderr,
      )
      sys.exit(1)

    try:
      if args.metrics_file == "-" or not args.metrics_file:
        data = json.load(sys.stdin)
      else:
        with open(args.metrics_file, "r") as f:
          data = json.load(f)
    except Exception as e:
      print(f"Error reading metrics data: {e}", file=sys.stderr)
      sys.exit(1)

  if not data or not isinstance(data, list):
    print(
        "Error: Metrics data must be a JSON list of numbers or parsed"
        " successfully from a source",
        file=sys.stderr,
    )
    sys.exit(1)

  try:
    results = compute_metrics_and_classify(data)
    print(json.dumps(results, indent=2))
  except ValueError as e:
    print(f"Error: {e}", file=sys.stderr)
    sys.exit(1)


if __name__ == "__main__":
  main()
analyze_traffic_test.py 7.8 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Unit tests for metrics data time-series parsing.

Also tests decision tree traffic profiling decisions.
"""

import datetime
import json
import os
import sys
import time
import unittest
from unittest import mock

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import analyze_traffic  # pytype: disable=import-error  # pyrefly: ignore[missing-import]
import mock_traffic_data  # pytype: disable=import-error  # pyrefly: ignore[missing-import]


class AnalyzeTrafficTest(unittest.TestCase):

  def test_classify_seasonal(self):
    data = mock_traffic_data.SEASONAL_TRAFFIC
    results = analyze_traffic.compute_metrics_and_classify(data)
    self.assertEqual(results["profile"], "Seasonal / Cyclical")
    self.assertEqual(
        results["recommended_algorithm"],
        "Seasonal Decomposition (average 1w and 1d)",
    )

  def test_classify_steady(self):
    data = mock_traffic_data.STEADY_TRAFFIC
    results = analyze_traffic.compute_metrics_and_classify(data)
    self.assertEqual(results["profile"], "Steady / Consistent")
    self.assertEqual(results["recommended_algorithm"], "1w Z-Score Baseline")

  def test_classify_bursty(self):
    data = mock_traffic_data.BURSTY_TRAFFIC
    results = analyze_traffic.compute_metrics_and_classify(data)
    self.assertEqual(results["profile"], "Bursty / Inconsistent")
    self.assertEqual(results["recommended_algorithm"], "Moving Averages")

  def test_classify_new_agent(self):
    data = [0.0] * 4032
    results = analyze_traffic.compute_metrics_and_classify(data)
    self.assertEqual(results["profile"], "New Agent / No Traffic")
    self.assertEqual(
        results["recommended_algorithm"], "Short-Window Z-Score (1h baseline)"
    )
    self.assertIn("No historical traffic observed", str(results["rationale"]))

  def test_insufficient_data(self):
    with self.assertRaises(ValueError):
      analyze_traffic.compute_metrics_and_classify([1.0] * 100)

  def test_classify_constant_traffic(self):
    # Constant 10.0 traffic should be classified as Steady/Consistent
    data = [10.0] * 4032
    results = analyze_traffic.compute_metrics_and_classify(data)
    self.assertEqual(results["profile"], "Steady / Consistent")
    self.assertEqual(results["recommended_algorithm"], "1w Z-Score Baseline")

  def test_classify_very_low_constant_traffic(self):
    # Constant 0.005 traffic (below 0.01 zero threshold) should still be
    # Steady/Consistent due to mean_last being non-zero (0.005 != 0.0)
    data = [0.005] * 4032
    results = analyze_traffic.compute_metrics_and_classify(data)
    self.assertEqual(results["profile"], "Steady / Consistent")
    self.assertEqual(results["recommended_algorithm"], "1w Z-Score Baseline")

  def test_classify_near_zero_spike_falls_to_steady(self):
    # 4031 zeros and a single 0.05 value. mean_last is 0.05/2016 = 0.0000248,
    # which is <= 0.0001, so variance_ratio is forced to 0.0, and it falls back
    # to Steady/Consistent.
    data = [0.0] * 4031 + [0.05]
    results = analyze_traffic.compute_metrics_and_classify(data)
    self.assertEqual(results["profile"], "Steady / Consistent")
    self.assertEqual(results["recommended_algorithm"], "1w Z-Score Baseline")

  def test_classify_single_spike_bursty(self):
    # 4031 zeros and a single 0.5 value. mean_last is 0.5/2016 = 
    # 0.000248 > 0.0001, so variance_ratio is computed (~44.88 > 2.0) and it
    # classifies as Bursty/Inconsistent.
    data = [0.0] * 4031 + [0.5]
    results = analyze_traffic.compute_metrics_and_classify(data)
    self.assertEqual(results["profile"], "Bursty / Inconsistent")
    self.assertEqual(results["recommended_algorithm"], "Moving Averages")

  @mock.patch("sys.exit")
  @mock.patch("builtins.print")
  @mock.patch("google.cloud.monitoring_v3.MetricServiceClient")
  def test_main_live_query_request_count(
      self, mock_client_cls, mock_print, mock_exit
  ):
    # Ensure google.cloud.monitoring_v3 module import doesn't fail
    mock_client = mock_client_cls.return_value

    class MockTimestamp:

      def __init__(self, seconds):
        self.seconds = seconds

      def timestamp(self):
        return self.seconds

    class MockPoint:

      def __init__(self, seconds, val):
        self.interval = mock.MagicMock()
        self.interval.start_time = MockTimestamp(seconds)
        self.value = mock.MagicMock()
        self.value.double_value = val

    class MockSeries:

      def __init__(self, points):
        self.points = points

    now = time.time()
    start_ts = now - 14 * 24 * 3600
    mock_points = [
        MockPoint(start_ts + (i + 1) * 300, 10.0) for i in range(4032)
    ]
    mock_client.list_time_series.return_value = [MockSeries(mock_points)]

    test_argv = [
        "analyze_traffic.py",
        "--live",
        "--project-id",
        "my-project",
        "--reasoning-engine-id",
        "123",
        "--metric-type",
        "workload.googleapis.com/gen_ai.invoke_agent.duration",
    ]
    with mock.patch.object(sys, "argv", test_argv):
      analyze_traffic.main()

    mock_print.assert_called()
    printed_str = mock_print.call_args[0][0]
    results = json.loads(printed_str)
    self.assertEqual(results["profile"], "Steady / Consistent")
    self.assertEqual(results["recommended_algorithm"], "1w Z-Score Baseline")

  @mock.patch("sys.exit")
  @mock.patch("builtins.print")
  @mock.patch("google.cloud.monitoring_v3.MetricServiceClient")
  def test_main_live_query_token_usage(
      self, mock_client_cls, mock_print, mock_exit
  ):
    # Ensure google.cloud.monitoring_v3 module import doesn't fail
    mock_client = mock_client_cls.return_value

    class MockTimestamp:

      def __init__(self, seconds):
        self.seconds = seconds

      def timestamp(self):
        return self.seconds

    class MockPoint:

      def __init__(self, seconds, val):
        self.interval = mock.MagicMock()
        self.interval.start_time = MockTimestamp(seconds)
        self.value = mock.MagicMock()
        self.value.double_value = val

    class MockSeries:

      def __init__(self, points):
        self.points = points

    now = time.time()
    start_ts = now - 14 * 24 * 3600
    # Simulate high peaks and low baseline to force the Bursty profile.
    mock_points = [
        MockPoint(start_ts + (i + 1) * 300, 1000.0 if i % 50 == 0 else 1.0)
        for i in range(4032)
    ]
    mock_client.list_time_series.return_value = [MockSeries(mock_points)]

    test_argv = [
        "analyze_traffic.py",
        "--live",
        "--project-id",
        "my-project",
        "--reasoning-engine-id",
        "test-engine",
        "--metric-type",
        "workload.googleapis.com/gen_ai.client.token.usage",
    ]
    with mock.patch.object(sys, "argv", test_argv):
      analyze_traffic.main()

    mock_print.assert_called()
    printed_str = mock_print.call_args[0][0]
    results = json.loads(printed_str)
    self.assertEqual(results["profile"], "Bursty / Inconsistent")
    self.assertEqual(results["recommended_algorithm"], "Moving Averages")

  def test_align_to_grid(self):
    points = [
        (0.0, 1.0),
        (10.0, 1.5),
        (600.0, 2.0),
        (2700.0, 3.0),
        (3000.0, 4.0),
    ]
    grid = analyze_traffic.align_to_grid(points, 3000.0, num_points=10)
    self.assertEqual(grid, [0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 4.0])


if __name__ == "__main__":
  unittest.main()
check_telemetry.py 5.8 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Helper script to check telemetry status on a Vertex AI Reasoning Engine."""

import argparse
import datetime
import sys

from google.cloud import monitoring_v3

try:
  from google.cloud import aiplatform_v1beta1  # pytype: disable=import-error  # pyrefly: ignore[missing-module-attribute,missing-import]
except ImportError:
  from google.cloud.aiplatform import aiplatform_v1beta1  # pytype: disable=import-error  # pyrefly: ignore[missing-module-attribute,missing-import]


def check_agent_telemetry(
    project_id: str, location: str, agent_resource_name: str
) -> bool:
  """Verifies if telemetry is correctly enabled on the reasoning engine."""
  client = aiplatform_v1beta1.ReasoningEngineServiceClient(
      client_options={"api_endpoint": f"{location}-aiplatform.googleapis.com"}
  )

  # Check if agent_resource_name is already a full path or needs formatting
  if not agent_resource_name.startswith("projects/"):
    name = (
        f"projects/{project_id}/locations/{location}/"
        f"reasoningEngines/{agent_resource_name}"
    )
  else:
    name = agent_resource_name

  engine = client.get_reasoning_engine(name=name)

  env_vars = {}
  for env_var in engine.spec.deployment_spec.env:
    env_vars[env_var.name] = env_var.value.strip()

  has_telemetry_toggle = (
      env_vars.get("GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY", "").lower()
      == "true"
  )
  has_capture_toggle = bool(
      env_vars.get("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "")
  )
  is_enabled = has_telemetry_toggle and has_capture_toggle

  print(
      f"Agent {engine.display_name} Telemetry Status:"
      f" {'ENABLED' if is_enabled else 'DISABLED'}"
  )
  if not is_enabled:
    val_telemetry = env_vars.get(
        "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY", "MISSING"
    )
    val_capture = env_vars.get(
        "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "MISSING"
    )
    print(
        "Missing/Incorrect variables: "
        f"ENABLE_TELEMETRY={val_telemetry}, "
        f"CAPTURE_MESSAGE_CONTENT={val_capture}"
    )
  return is_enabled


def check_token_usage_monitoring_namespaces(
    project_id: str, days_lookback: int = 1
) -> set[str]:
  """Queries Cloud Monitoring for distinct namespaces.

  Specifically, look for the workload.googleapis.com/gen_ai.client.token.usage
  metric.
  """
  client = monitoring_v3.MetricServiceClient()
  now = datetime.datetime.now(datetime.timezone.utc)
  start_time = now - datetime.timedelta(days=days_lookback)
  interval = monitoring_v3.TimeInterval({
      "end_time": {"seconds": int(now.timestamp())},
      "start_time": {"seconds": int(start_time.timestamp())},
  })
  filter_str = 'metric.type="workload.googleapis.com/gen_ai.client.token.usage"'
  print(f"Filter: {filter_str}")
  namespaces = set()
  try:
    results = client.list_time_series(
        request={
            "name": f"projects/{project_id}",
            "filter": filter_str,
            "interval": interval,
            "view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.HEADERS,
        }
    )
    count = 0
    for ts in results:
      count += 1
      res_labels = ts.resource.labels
      ns = res_labels.get(
          "namespace", "(namespace label not found in this resource)"
      )
      namespaces.add(ns)
    print(f"\nFound {count} matching time series descriptors.")
    return namespaces
  except Exception as e:
    print(f"Error querying Cloud Monitoring metadata: {e}", file=sys.stderr)
    sys.exit(1)


def main():
  parser = argparse.ArgumentParser(
      description=(
          "Check if telemetry is enabled on a Vertex AI Reasoning Engine."
      )
  )
  parser.add_argument("--project-id", required=True, help="The GCP Project ID.")
  parser.add_argument(
      "--location", default="us-central1", help="The GCP Location/Region."
  )
  parser.add_argument(
      "--agent-resource-name",
      required=True,
      help="The agent ID or full resource path of the Reasoning Engine.",
  )
  parser.add_argument(
      "--query-monitoring-metadata",
      action=argparse.BooleanOptionalAction,
      default=True,
      help=(
          "If set, it will also query Cloud Monitoring for related metric"
          " metadata."
      ),
  )

  args = parser.parse_args()
  print(
      f"--- [1] Checking agent {args.agent_resource_name} telemetry status ---"
  )
  try:
    telemetry_ok = check_agent_telemetry(
        project_id=args.project_id,
        location=args.location,
        agent_resource_name=args.agent_resource_name,
    )
    if not telemetry_ok:
      sys.exit(1)
  except Exception as e:
    print(f"Error checking telemetry status: {e}", file=sys.stderr)
    sys.exit(1)

  if args.query_monitoring_metadata:
    print("--- [2] Querying Cloud Monitoring metadata ---")
    try:
      namespaces = check_token_usage_monitoring_namespaces(args.project_id)
      if namespaces:
        print("Distinct namespaces identified in Cloud Monitoring:")
        for ns in sorted(namespaces):
          print(f"==> {ns}")
      else:
        print(
            "No time series found matching the metric filter in the chosen time"
            " window."
        )
    except Exception as e:
      print(f"Error querying Cloud Monitoring metadata: {e}", file=sys.stderr)
      sys.exit(1)


if __name__ == "__main__":
  main()
check_telemetry_test.py 5.4 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Unit tests for check_telemetry.py."""

import os
import sys
import unittest
from unittest import mock

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import check_telemetry  # pytype: disable=import-error  # pyrefly: ignore[missing-import]


class CheckTelemetryTest(unittest.TestCase):

  def setUp(self):
    super().setUp()
    self.project_id = "test-project"
    self.location = "us-central1"
    self.agent_id = "123456789"
    self.agent_resource_name = (
        f"projects/{self.project_id}/locations/{self.location}/"
        f"reasoningEngines/{self.agent_id}"
    )

  @mock.patch("check_telemetry.aiplatform_v1beta1.ReasoningEngineServiceClient")
  def test_check_agent_telemetry_enabled(self, mock_client_class):
    mock_client = mock_client_class.return_value
    mock_engine = mock.Mock()

    env_var_1 = mock.Mock()
    env_var_1.name = "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY"
    env_var_1.value = "true"

    env_var_2 = mock.Mock()
    env_var_2.name = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"
    env_var_2.value = "EVENT_ONLY"

    mock_engine.spec.deployment_spec.env = [env_var_1, env_var_2]
    mock_client.get_reasoning_engine.return_value = mock_engine

    result = check_telemetry.check_agent_telemetry(
        project_id=self.project_id,
        location=self.location,
        agent_resource_name=self.agent_id,
    )

    self.assertTrue(result)
    mock_client.get_reasoning_engine.assert_called_once_with(
        name=self.agent_resource_name
    )

  @mock.patch("check_telemetry.aiplatform_v1beta1.ReasoningEngineServiceClient")
  def test_check_agent_telemetry_disabled_missing_telemetry_toggle(
      self, mock_client_class
  ):
    mock_client = mock_client_class.return_value
    mock_engine = mock.Mock()

    env_var_1 = mock.Mock()
    env_var_1.name = "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY"
    env_var_1.value = "false"

    env_var_2 = mock.Mock()
    env_var_2.name = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"
    env_var_2.value = "EVENT_ONLY"

    mock_engine.spec.deployment_spec.env = [env_var_1, env_var_2]
    mock_client.get_reasoning_engine.return_value = mock_engine

    result = check_telemetry.check_agent_telemetry(
        project_id=self.project_id,
        location=self.location,
        agent_resource_name=self.agent_id,
    )

    self.assertFalse(result)

  @mock.patch("check_telemetry.aiplatform_v1beta1.ReasoningEngineServiceClient")
  def test_check_agent_telemetry_disabled_missing_capture_toggle(
      self, mock_client_class
  ):
    mock_client = mock_client_class.return_value
    mock_engine = mock.Mock()

    env_var_1 = mock.Mock()
    env_var_1.name = "GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY"
    env_var_1.value = "true"

    mock_engine.spec.deployment_spec.env = [env_var_1]
    mock_client.get_reasoning_engine.return_value = mock_engine

    result = check_telemetry.check_agent_telemetry(
        project_id=self.project_id,
        location=self.location,
        agent_resource_name=self.agent_id,
    )

    self.assertFalse(result)

  @mock.patch("check_telemetry.monitoring_v3")
  def test_check_token_usage_monitoring_namespaces_success(
      self, mock_monitoring_v3
  ):
    # Setup mock client and mock time series returns
    mock_client = mock.MagicMock()
    mock_monitoring_v3.MetricServiceClient.return_value = mock_client
    mock_monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.HEADERS = 1

    ts1 = mock.MagicMock()
    ts1.resource.labels = {"namespace": "staging_agent", "node_id": "node-2"}
    mock_client.list_time_series.return_value = [ts1]
    namespaces = check_telemetry.check_token_usage_monitoring_namespaces(
        self.project_id, days_lookback=3
    )
    # Verify return set contains expected unique namespaces
    self.assertEqual(namespaces, {"staging_agent"})

    # Verify exact API request structure passed to list_time_series
    self.assertTrue(mock_client.list_time_series.called)
    call_kwargs = mock_client.list_time_series.call_args[1]["request"]
    self.assertEqual(call_kwargs["name"], f"projects/{self.project_id}")
    self.assertEqual(
        call_kwargs["filter"],
        'metric.type="workload.googleapis.com/gen_ai.client.token.usage"',
    )
    self.assertEqual(call_kwargs["view"], 1)

  @mock.patch("check_telemetry.monitoring_v3")
  def test_check_token_usage_monitoring_namespaces_missing_namespace_label(
      self, mock_monitoring_v3
  ):
    mock_client = mock.MagicMock()
    mock_monitoring_v3.MetricServiceClient.return_value = mock_client
    ts_no_label = mock.MagicMock()
    ts_no_label.resource.labels = {"location": "us-central1"}
    mock_client.list_time_series.return_value = [ts_no_label]
    namespaces = check_telemetry.check_token_usage_monitoring_namespaces(
        self.project_id
    )
    self.assertIn("(namespace label not found in this resource)", namespaces)


if __name__ == "__main__":
  unittest.main()
config_utils.py 9.4 KB
#!/usr/bin/env python3
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Shared utility functions for alert configuration validation."""

import re

def check_balanced_chars(
    query: str, open_char: str, close_char: str
) -> str | None:
  """Checks if parenthesis or braces are balanced."""
  count = 0
  for i, char in enumerate(query):
    if char == open_char:
      count += 1
    elif char == close_char:
      count -= 1
      if count < 0:
        return f"Unbalanced '{close_char}' at position {i}"
  if count != 0:
    return f"Unbalanced '{open_char}' (net count: {count})"
  return None


def parse_promql_duration(duration_str: str) -> float | None:
  """Converts PromQL duration string to hours."""
  match = re.match(r"^(\d+)([smhdw])$", duration_str)
  if not match:
    return None
  val, unit = match.groups()
  val = int(val)
  if unit == "s":
    return val / 3600
  if unit == "m":
    return val / 60
  if unit == "h":
    return val
  if unit == "d":
    return val * 24
  if unit == "w":
    return val * 24 * 7
  return None


def get_max_lookback_hours(query: str) -> float:
  """Calculates the maximum lookback in hours from windows and offsets."""
  max_hours = 0

  # Check windows and subqueries
  window_matches = re.finditer(r"\[([^\]]+)\]", query)
  for match in window_matches:
    window_str = match.group(1)
    range_str = window_str.split(":")[0]
    hours = parse_promql_duration(range_str)
    if hours and hours > max_hours:
      max_hours = hours

  # Check offsets
  offset_matches = re.finditer(r"\boffset\s+(\S+)", query)
  for match in offset_matches:
    offset_str = match.group(1)
    hours = parse_promql_duration(offset_str)
    if hours and hours > max_hours:
      max_hours = hours

  return max_hours


def validate_policy_duration(policy: dict) -> list[str]:
  """Validates duration based on lookback window."""
  errors = []
  max_lookback = 0
  for query in policy["queries"]:
    lookback = get_max_lookback_hours(query)
    if lookback > max_lookback:
      max_lookback = lookback

  quality_metrics = [
      "final_response_quality_v1",
      "tool_use_quality_v1",
      "hallucination_v1",
  ]

  if policy["signal_type"] in quality_metrics:
    if policy["duration"] != "300s":
      errors.append(
          "Duration Error: Quality alerts MUST set duration='300s'."
          f" Found duration='{policy['duration']}'."
      )
  elif max_lookback > 25:
    if policy["duration"] is not None:
      errors.append(
          "Duration Error: Long-lookback alerts (>25h) must NOT set a"
          f" duration. Found duration='{policy['duration']}' for lookback of"
          f" {max_lookback}h."
      )
  elif max_lookback > 0:  # It's a short-lookback PromQL alert
    if policy["duration"] != "300s":
      errors.append(
          "Duration Error: Short-lookback alerts (<=25h) MUST set"
          f" duration='300s'. Found duration='{policy['duration']}'."
      )
  return errors


def lint_query(query: str) -> list[str]:
  """Runs a suite of sanity lint checks on a PromQL query."""
  errors = []

  # 1. Balanced parentheses
  paren_err = check_balanced_chars(query, "(", ")")
  if paren_err:
    errors.append(f"Parentheses error: {paren_err}")

  # 2. Balanced curly braces
  brace_err = check_balanced_chars(query, "{", "}")
  if brace_err:
    errors.append(f"Curly braces error: {brace_err}")

  # 3. Time window validations (e.g., [5m], [1w:5m], [3d], [1h])
  window_matches = re.finditer(r"\[([^\]]+)\]", query)
  for match in window_matches:
    window_str = match.group(1)
    if not re.match(r"^\d+[smhdw](:(\d+[smhdw])?)?$", window_str):
      errors.append(
          "Invalid Prometheus time window/subquery interval:"
          f" '[{window_str}]' at position {match.start()}"
      )

  # 4. Lookback offset range validation (e.g. offset 1w, offset 1d)
  offset_matches = re.finditer(r"\boffset\s+(\S+)", query)
  for match in offset_matches:
    offset_str = match.group(1)
    if not re.match(r"^\d+[smhdw]$", offset_str):
      errors.append(
          f"Invalid lookback offset format: 'offset {offset_str}' at position"
          f" {match.start()}"
      )

  # 5. Ensure the query references a supported group in a label filter
  # or grouping aggregation.
  supported_groups = ["namespace", "gen_ai_agent_name"]
  search_regex = (
      r"\b(by|without)\s*\([^)]*\b("
      + "|".join(supported_groups)
      + r")\b[^)]*\)"
  )
  has_group = bool(re.search(search_regex, query))

  has_filter = False
  brace_matches = re.finditer(r"\{([^}]+)\}", query)
  for match in brace_matches:
    for group in supported_groups:
      if group in match.group(1):
        has_filter = True
        break
    if has_filter:
      break

  if not (has_group or has_filter):
    errors.append(
        "Query is missing agent identifier reference. It must either group"
        " by it using aggregations (e.g., 'by (gen_ai_agent_name)') or filter"
        " on it (e.g., '{gen_ai_agent_name=\"...\"}')."
    )

  return errors


def extract_alert_policies(hcl_content: str) -> list[dict]:
  """Extracts resource 'google_monitoring_alert_policy' blocks and metadata."""
  policies = []
  pattern = re.compile(
      r'resource\s+"google_monitoring_alert_policy"\s+"([^"]+)"\s*\{'
  )

  for match in pattern.finditer(hcl_content):
    resource_name = match.group(1)
    start_pos = match.start()

    brace_count = 0
    end_pos = -1
    in_string = False
    escape = False

    for i in range(match.end() - 1, len(hcl_content)):
      char = hcl_content[i]
      if escape:
        escape = False
        continue
      if char == "\\":
        escape = True
        continue
      if char == '"':
        in_string = not in_string
        continue
      if not in_string:
        if char == "{":
          brace_count += 1
        elif char == "}":
          brace_count -= 1
          if brace_count == 0:
            end_pos = i + 1
            break

    if end_pos == -1:
      continue

    block_content = hcl_content[start_pos:end_pos]

    # Extract display_name
    display_name_match = re.search(
        r'display_name\s*=\s*"([^"]+)"', block_content
    )
    display_name = display_name_match.group(1) if display_name_match else ""

    # Extract duration
    duration_match = re.search(r'duration\s*=\s*"([^"]+)"', block_content)
    duration = duration_match.group(1) if duration_match else None

    # Extract PromQL queries
    queries = [
        q.group(1)
        for q in re.finditer(
            r"query\s*=\s*<<-?EOT\n(.*?)\n\s*EOT",
            block_content,
            re.DOTALL,
        )
    ]
    if not queries:
      for match in re.finditer(
          r"query\s*=\s*\"((?:[^\"\\]|\\[\s\S])*)\"", block_content
      ):
        raw_query = match.group(1)
        clean_query = re.sub(r"\\+\"", '"', raw_query).replace("\\\\", "\\")
        queries.append(clean_query)

    # Extract threshold filters
    filters = []
    filter_matches = re.finditer(
        r'filter\s*=\s*"((?:[^"\\]|\\.)*)"', block_content
    )
    for f_match in filter_matches:
      filters.append(f_match.group(1))

    # Infer signal type
    signal_type = "unknown"
    res_lower, disp_lower = resource_name.lower(), display_name.lower()
    rules = [
        ("latency", "latency", "latency"),
        ("slo_burn_rate_fast", "fast", "slo_fast"),
        ("slo_burn_rate_slow", "slow", "slo_slow"),
    ]
    for res_pat, disp_pat, sig in rules:
      if res_pat in res_lower or disp_pat in disp_lower:
        signal_type = sig
        break
    else:
      # Check threshold filters for quality metric name
      for flt in filters:
        metric_match = re.search(
            r"metric\.labels\.evaluation_metric_name"
            r"\s*=\s*\\*\"([^\"\\]+)\\*\"",
            flt,
        )
        if metric_match:
          signal_type = metric_match.group(1)
          break

    engine_ids = []
    for query in queries:
      for engine_id in re.findall(
          r'(?:reasoning_engine_id|gen_ai_agent_name|namespace)'
          r'\s*=\s*"([^"]+)"',
          query,
      ):
        if engine_id not in engine_ids:
          engine_ids.append(engine_id)
    for flt in filters:
      id_matches = re.findall(
          r'(?:reasoning_engine_id|gen_ai_agent_name|namespace)'
          r'\s*=\s*\\*"([^"\\]+)\\*"',
          flt,
      )
      for engine_id in id_matches:
        if engine_id not in engine_ids:
          engine_ids.append(engine_id)
      resource_matches = re.findall(r"reasoningEngines/([0-9]+)", flt)
      for engine_id in resource_matches:
        if engine_id not in engine_ids:
          engine_ids.append(engine_id)

    policies.append({
        "resource_name": resource_name,
        "display_name": display_name,
        "signal_type": signal_type,
        "engine_ids": engine_ids,
        "queries": queries,
        "filters": filters,
        "duration": duration,
        "is_sql": "condition_sql" in block_content,
        "start_pos": start_pos,
        "end_pos": end_pos,
        "block_content": block_content,
    })

  return policies
config_utils_test.py 10.2 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import config_utils  # pytype: disable=import-error  # pyrefly: ignore[missing-import]


class ConfigUtilsTest(unittest.TestCase):

  def test_lint_query_valid(self):
    query = (
        "sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count[5m]))"
        " by (gen_ai_agent_name)"
    )
    self.assertEqual(config_utils.lint_query(query), [])

  def test_lint_query_unbalanced_parentheses(self):
    query = (
        "sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count[5m]))"
        " by (gen_ai_agent_name"
    )
    errors = config_utils.lint_query(query)
    self.assertTrue(any("Parentheses error" in e for e in errors))

  def test_lint_query_unbalanced_braces(self):
    query = (
        'sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{error_type!=""[5m]))'
        " by (gen_ai_agent_name)"
    )
    errors = config_utils.lint_query(query)
    self.assertTrue(any("Curly braces error" in e for e in errors))

  def test_lint_query_invalid_window(self):
    for invalid_suffix in ("5x", "5y"):
      query = (
          "sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count"
          f"[{invalid_suffix}])) by (gen_ai_agent_name)"
      )
      errors = config_utils.lint_query(query)
      self.assertTrue(
          any("Invalid Prometheus time window" in e for e in errors)
      )

  def test_lint_query_valid_subquery_intervals(self):
    queries = [
        # With resolution
        (
            "avg_over_time((sum(rate("
            "workload_googleapis_com:gen_ai_invoke_agent_duration_count[5m]"
            ")) by (gen_ai_agent_name))[1w:5m])"
        ),
        # Without resolution
        (
            "avg_over_time((sum(rate("
            "workload_googleapis_com:gen_ai_invoke_agent_duration_count[5m]"
            ")) by (gen_ai_agent_name))[1w:])"
        ),
    ]
    for query in queries:
      self.assertEqual(config_utils.lint_query(query), [])

  def test_lint_query_invalid_subquery_intervals(self):
    queries = [
        # Invalid resolution format: number only (no unit)
        (
            "avg_over_time((sum(rate("
            "workload_googleapis_com:gen_ai_invoke_agent_duration_count[5m]"
            ")) by (gen_ai_agent_name))[1w:5])"
        ),
        # Invalid resolution format: unit only (no number)
        (
            "avg_over_time((sum(rate("
            "workload_googleapis_com:gen_ai_invoke_agent_duration_count[5m]"
            ")) by (gen_ai_agent_name))[1w:m])"
        ),
    ]
    for query in queries:
      errors = config_utils.lint_query(query)
      self.assertTrue(
          any("Invalid Prometheus time window" in e for e in errors)
      )

  def test_lint_query_missing_reference(self):
    query = "sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count[5m]))"
    errors = config_utils.lint_query(query)
    self.assertTrue(
        any("missing agent identifier reference" in e for e in errors)
    )

  def test_lint_query_valid_with_filter(self):
    query = (
        'sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count'
        '{gen_ai_agent_name="my-agent"}[5m]))'
    )
    self.assertEqual(config_utils.lint_query(query), [])

  def test_lint_query_valid_with_regex_or_prefix_filter(self):
    query = (
        'sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count'
        '{gen_ai_agent_name!~"dev-.*"}[5m]))'
        " by (gen_ai_agent_name)"
    )
    self.assertEqual(config_utils.lint_query(query), [])

  def test_scanner_extract_valid_hcl(self):
    hcl_content = """
        resource "google_monitoring_alert_policy" "agent_latency_anomaly" {
          project      = var.project_id
          display_name = "[Agent Alert] Latency Anomaly - ${var.agent_name}"
          combiner     = "OR"

          conditions {
            display_name = "p95 Latency exceeds 3x Standard Deviation (1w baseline)"
            condition_prometheus_query_language {
              query    = <<-EOT
                sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count[5m])) by (gen_ai_agent_name)
              EOT
              duration = "300s"
            }
          }
        }
        """
    policies = config_utils.extract_alert_policies(hcl_content)
    self.assertEqual(len(policies), 1)
    self.assertEqual(policies[0]["resource_name"], "agent_latency_anomaly")
    self.assertEqual(policies[0]["signal_type"], "latency")

  def test_scanner_extract_escaped_inline_query(self):
    hcl_content = r"""
        resource "google_monitoring_alert_policy" "agent_latency_anomaly" {
          display_name = "[Agent Alert] Latency Anomaly - ${var.agent_name}"
          conditions {
            condition_prometheus_query_language {
              query = "sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{gen_ai_agent_name=\"12345\"}[5m]))"
            }
          }
        }
        """
    policies = config_utils.extract_alert_policies(hcl_content)
    self.assertEqual(len(policies), 1)
    self.assertEqual(len(policies[0]["queries"]), 1)
    self.assertEqual(
        policies[0]["queries"][0],
        'sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{gen_ai_agent_name="12345"}[5m]))',
    )
    self.assertEqual(policies[0]["engine_ids"], ["12345"])

    hcl_content_three_backslash = r"""
        resource "google_monitoring_alert_policy" "agent_latency_anomaly" {
          display_name = "[Agent Alert] Latency Anomaly - ${var.agent_name}"
          conditions {
            condition_prometheus_query_language {
              query = "sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{gen_ai_agent_name=\\\"12345\\\"}[5m]))"
            }
          }
        }
        """
    policies_three = config_utils.extract_alert_policies(
        hcl_content_three_backslash
    )
    self.assertEqual(len(policies_three), 1)
    self.assertEqual(len(policies_three[0]["queries"]), 1)
    self.assertEqual(
        policies_three[0]["queries"][0],
        'sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count{gen_ai_agent_name="12345"}[5m]))',
    )
    self.assertEqual(policies_three[0]["engine_ids"], ["12345"])

  def test_scanner_extracts_quality_metric_signal_type(self):
    hcl_content = """
        resource "google_monitoring_alert_policy" "agent_final_response_quality" {
          project      = var.project_id
          display_name = "Agent Final Response Quality (Median < 0.8)"
          combiner     = "OR"
          enabled      = true

          conditions {
            display_name = "Final Response Quality Score"
            condition_threshold {
              filter          = "resource.type=\\"aiplatform.googleapis.com/OnlineEvaluator\\" AND metric.type=\\"aiplatform.googleapis.com/online_evaluator/scores\\" AND metric.labels.evaluation_metric_name=\\"final_response_quality_v1\\""
              comparison      = "COMPARISON_LT"
              threshold_value = 0.8
              duration        = "300s"
              aggregations {
                alignment_period   = "300s"
                per_series_aligner = "ALIGN_PERCENTILE_50"
              }
              trigger {
                count = 1
              }
            }
          }
        }
        """
    policies = config_utils.extract_alert_policies(hcl_content)
    self.assertEqual(len(policies), 1)
    self.assertEqual(
        policies[0]["resource_name"], "agent_final_response_quality"
    )
    self.assertEqual(policies[0]["signal_type"], "final_response_quality_v1")

  def test_validate_policy_duration_quality(self):
    # Quality metrics alerts: MUST set duration="300s".
    policy_ok = {
        "signal_type": "final_response_quality_v1",
        "queries": [],
        "duration": "300s",
    }
    self.assertEqual(config_utils.validate_policy_duration(policy_ok), [])

    policy_err = {
        "signal_type": "final_response_quality_v1",
        "queries": [],
        "duration": "600s",
    }
    self.assertEqual(
        config_utils.validate_policy_duration(policy_err),
        [
            "Duration Error: Quality alerts MUST set duration='300s'. Found"
            " duration='600s'."
        ],
    )

  def test_validate_policy_duration_long_lookback(self):
    # Long-lookback alerts (>25h): must NOT set a duration (duration is None).
    query = "sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count[2d]))"
    policy_ok = {
        "signal_type": "latency",
        "queries": [query],
        "duration": None,
    }
    self.assertEqual(config_utils.validate_policy_duration(policy_ok), [])

    policy_err = {
        "signal_type": "latency",
        "queries": [query],
        "duration": "300s",
    }
    self.assertEqual(
        config_utils.validate_policy_duration(policy_err),
        [
            "Duration Error: Long-lookback alerts (>25h) must NOT set a"
            " duration. Found duration='300s' for lookback of 48h."
        ],
    )

  def test_validate_policy_duration_short_lookback(self):
    # Short-lookback alerts (<=25h): MUST set duration="300s".
    query = "sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count[5m]))"
    policy_ok = {
        "signal_type": "latency",
        "queries": [query],
        "duration": "300s",
    }
    self.assertEqual(config_utils.validate_policy_duration(policy_ok), [])

    policy_err = {
        "signal_type": "latency",
        "queries": [query],
        "duration": None,
    }
    self.assertEqual(
        config_utils.validate_policy_duration(policy_err),
        [
            "Duration Error: Short-lookback alerts (<=25h) MUST set"
            " duration='300s'. Found duration='None'."
        ],
    )


if __name__ == "__main__":
  unittest.main()
create_online_monitor.py 5.8 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Helper script to create a Vertex AI Reasoning Engine Online Monitor."""

import argparse
import sys
import typing

try:
  from google.cloud import aiplatform_v1beta1  # pytype: disable=import-error  # pyrefly: ignore[missing-module-attribute,missing-import]
except ImportError:
  from google.cloud.aiplatform import aiplatform_v1beta1  # pytype: disable=import-error  # pyrefly: ignore[missing-module-attribute,missing-import]


EXPECTED_METRICS = {
    "hallucination_v1",
    "final_response_quality_v1",
    "tool_use_quality_v1",
}


def _verify_configuration(
    evaluator: typing.Any, target_sampling_percentage: int
) -> bool:
  """Checks if the existing monitor config matches the desired settings.

  Args:
      evaluator: The OnlineEvaluator instance to verify.
      target_sampling_percentage: The expected sampling percentage.

  Returns:
      True if the configuration matches, False otherwise.
  """
  actual_metrics = set()
  for metric_source in evaluator.metric_sources:
    spec = metric_source.metric.predefined_metric_spec
    if spec and spec.metric_spec_name:
      actual_metrics.add(spec.metric_spec_name)

  if actual_metrics != EXPECTED_METRICS:
    return False

  config = evaluator.config
  actual_sampling = 10  # Platform Default
  if config and config.random_sampling:
    actual_sampling = config.random_sampling.percentage

  if int(actual_sampling) != int(target_sampling_percentage):
    return False

  return True


def create_agent_online_monitor(
    project_id: str,
    location: str,
    agent_resource_name: str,
    sampling_percentage: int = 10,
) -> str:
  """Checks for matching monitor and creates one if none exists.

  Args:
      project_id: The GCP project ID.
      location: The GCP location (region).
      agent_resource_name: The full resource name of the agent.
      sampling_percentage: The desired sampling percentage (default 10).

  Returns:
      The resource name of the matching or created Online Evaluator.
  """
  client = aiplatform_v1beta1.OnlineEvaluatorServiceClient(
      client_options={"api_endpoint": f"{location}-aiplatform.googleapis.com"}
  )

  parent = f"projects/{project_id}/locations/{location}"

  # 1. Look for a monitor that matches our config exactly
  request = aiplatform_v1beta1.ListOnlineEvaluatorsRequest(parent=parent)
  page_result = client.list_online_evaluators(request=request)

  matching_evaluator = None
  for evaluator in page_result:
    if evaluator.agent_resource == agent_resource_name:
      if _verify_configuration(evaluator, sampling_percentage):
        matching_evaluator = evaluator
        break

  if matching_evaluator:
    print(
        f"Found matching Online Monitor: {matching_evaluator.name}. No action"
        " needed."
    )
    return matching_evaluator.name

  # 2. If no matching monitor is found, create a new one
  print("No matching Online Monitor found for agent. Creating a new one...")
  cloud_obs_spec = aiplatform_v1beta1.OnlineEvaluator.CloudObservability
  online_evaluator = aiplatform_v1beta1.OnlineEvaluator(
      display_name="agent-quality-monitor",
      agent_resource=agent_resource_name,
      cloud_observability=cloud_obs_spec(
          open_telemetry=cloud_obs_spec.OpenTelemetry(
              semconv_version="gen_ai_latest_experimental"
          ),
          trace_scope=cloud_obs_spec.TraceScope(),
      ),
      metric_sources=[
          aiplatform_v1beta1.MetricSource(
              metric=aiplatform_v1beta1.Metric(
                  predefined_metric_spec=aiplatform_v1beta1.PredefinedMetricSpec(
                      metric_spec_name=m
                  )
              )
          )
          for m in EXPECTED_METRICS
      ],
      config=aiplatform_v1beta1.OnlineEvaluator.Config(
          random_sampling=(
              aiplatform_v1beta1.OnlineEvaluator.Config.RandomSampling(
                  percentage=sampling_percentage
              )
          )
      ),
  )

  request = aiplatform_v1beta1.CreateOnlineEvaluatorRequest(
      parent=parent,
      online_evaluator=online_evaluator,
  )

  print(f"Creating Online Monitor for agent: {agent_resource_name}...")
  operation = client.create_online_evaluator(request=request)
  response = operation.result()
  print(f"Online Monitor created successfully: {response.name}")
  return response.name


def main():
  parser = argparse.ArgumentParser(
      description="Provision a Vertex AI Reasoning Engine Online Monitor."
  )
  parser.add_argument("--project-id", required=True, help="The GCP Project ID.")
  parser.add_argument(
      "--location", default="us-central1", help="The GCP Location/Region."
  )
  parser.add_argument(
      "--agent-resource-name",
      required=True,
      help="The full resource path of the Reasoning Engine agent.",
  )
  parser.add_argument(
      "--sampling-percentage",
      type=int,
      default=10,
      help=(
          "The percentage of incoming traces to evaluate (1-100). Default"
          " is 10."
      ),
  )

  args = parser.parse_args()
  try:
    create_agent_online_monitor(
        project_id=args.project_id,
        location=args.location,
        agent_resource_name=args.agent_resource_name,
        sampling_percentage=args.sampling_percentage,
    )
  except Exception as e:
    print(f"Error creating online monitor: {e}", file=sys.stderr)
    sys.exit(1)


if __name__ == "__main__":
  main()
create_online_monitor_test.py 5.7 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Unit tests for Vertex AI Reasoning Engine Online Monitor creation."""

import os
import sys
import unittest
from unittest import mock

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import create_online_monitor  # pytype: disable=import-error  # pyrefly: ignore[missing-import]


class CreateOnlineMonitorTest(unittest.TestCase):

  @mock.patch(
      "create_online_monitor.aiplatform_v1beta1.OnlineEvaluatorServiceClient"
  )
  def test_create_agent_online_monitor_already_exists_noop(
      self, mock_client_class
  ):
    mock_client = mock_client_class.return_value

    mock_evaluator = mock.Mock()
    mock_evaluator.name = (
        "projects/my-project/locations/us-central-test/onlineEvaluators/999"
    )
    mock_evaluator.agent_resource = (
        "projects/my-project/locations/us-central-test/reasoningEngines/123"
    )

    mock_metric_sources = []
    for metric_name in [
        "hallucination_v1",
        "final_response_quality_v1",
        "tool_use_quality_v1",
    ]:
      m = mock.Mock()
      m.metric.predefined_metric_spec.metric_spec_name = metric_name
      mock_metric_sources.append(m)
    mock_evaluator.metric_sources = mock_metric_sources
    mock_evaluator.config.random_sampling.percentage = 15

    mock_client.list_online_evaluators.return_value = [mock_evaluator]

    evaluator_name = create_online_monitor.create_agent_online_monitor(
        project_id="my-project",
        location="us-central-test",
        agent_resource_name=(
            "projects/my-project/locations/us-central-test/reasoningEngines/123"
        ),
        sampling_percentage=15,
    )

    self.assertEqual(evaluator_name, mock_evaluator.name)
    mock_client.create_online_evaluator.assert_not_called()

  @mock.patch(
      "create_online_monitor.aiplatform_v1beta1.OnlineEvaluatorServiceClient"
  )
  def test_create_agent_online_monitor_not_exists_creates_new(
      self, mock_client_class
  ):
    mock_client = mock_client_class.return_value
    mock_client.list_online_evaluators.return_value = []

    mock_operation = mock.Mock()
    mock_client.create_online_evaluator.return_value = mock_operation

    mock_response = mock.Mock()
    mock_response.name = (
        "projects/my-project/locations/us-central-test/onlineEvaluators/999"
    )
    mock_operation.result.return_value = mock_response

    evaluator_name = create_online_monitor.create_agent_online_monitor(
        project_id="my-project",
        location="us-central-test",
        agent_resource_name=(
            "projects/my-project/locations/us-central-test/reasoningEngines/123"
        ),
        sampling_percentage=15,
    )

    # Verify Endpoint and Instantiation
    mock_client_class.assert_called_once_with(
        client_options={
            "api_endpoint": "us-central-test-aiplatform.googleapis.com"
        }
    )

    # Verify API Call
    mock_client.create_online_evaluator.assert_called_once()
    call_args = mock_client.create_online_evaluator.call_args[1]
    request = call_args["request"]

    self.assertEqual(
        request.parent, "projects/my-project/locations/us-central-test"
    )
    self.assertEqual(
        request.online_evaluator.display_name, "agent-quality-monitor"
    )
    self.assertEqual(
        request.online_evaluator.agent_resource,
        "projects/my-project/locations/us-central-test/reasoningEngines/123",
    )
    self.assertEqual(
        request.online_evaluator.config.random_sampling.percentage, 15
    )

    # Verify Metric Names are set
    metrics = [
        m.metric.predefined_metric_spec.metric_spec_name
        for m in request.online_evaluator.metric_sources
    ]
    self.assertIn("hallucination_v1", metrics)
    self.assertIn("final_response_quality_v1", metrics)
    self.assertIn("tool_use_quality_v1", metrics)

    self.assertEqual(evaluator_name, mock_response.name)

  @mock.patch(
      "create_online_monitor.aiplatform_v1beta1.OnlineEvaluatorServiceClient"
  )
  def test_create_agent_online_monitor_failure(self, mock_client_class):
    mock_client = mock_client_class.return_value
    mock_client.list_online_evaluators.return_value = []
    mock_client.create_online_evaluator.side_effect = Exception("API error")

    with self.assertRaises(Exception) as context:
      create_online_monitor.create_agent_online_monitor(
          project_id="my-project",
          location="us-central-test",
          agent_resource_name=(
              "projects/my-project/locations/us-central-test/"
              "reasoningEngines/123"
          ),
      )
    self.assertIn("API error", str(context.exception))

  @mock.patch("create_online_monitor.create_agent_online_monitor")
  def test_main_cli_parsing(self, mock_create):
    test_args = [
        "create_online_monitor.py",
        "--project-id",
        "cli-proj",
        "--agent-resource-name",
        "cli-agent",
        "--sampling-percentage",
        "30",
        "--location",
        "us-east4",
    ]
    with mock.patch.object(sys, "argv", test_args):
      create_online_monitor.main()

    mock_create.assert_called_once_with(
        project_id="cli-proj",
        location="us-east4",
        agent_resource_name="cli-agent",
        sampling_percentage=30,
    )


if __name__ == "__main__":
  unittest.main()
gather_agent_info.py 14.8 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Gathers all necessary information about an agent to build alerts.

Usage: python3 gather_agent_info.py --project-id {PROJECT_ID} --agent-name
{AGENT_NAME}
"""

import argparse
import json
import os
import subprocess
import sys
from collections.abc import Sequence
from typing import Any

try:
  from google.cloud import aiplatform_v1beta1  # pytype: disable=import-error  # pyrefly: ignore[missing-module-attribute,missing-import]
except ImportError:
  try:
    from google.cloud.aiplatform import aiplatform_v1beta1  # pytype: disable=import-error  # pyrefly: ignore[missing-module-attribute,missing-import]
  except ImportError:
    print("Error: google-cloud-aiplatform is not installed.", file=sys.stderr)
    print(
        "Please install it: pip install google-cloud-aiplatform",
        file=sys.stderr,
    )
    sys.exit(1)


DEFAULT_VERTEX_REGIONS = ["us-central1", "us-east1", "us-west1", "europe-west1"]


def run_command(
    cmd: Sequence[str] | str, shell: bool = False
) -> str | None:
  """Runs a command and returns output, or None if error."""
  try:
    result = subprocess.run(
        cmd, capture_output=True, text=True, check=True, shell=shell
    )
    return result.stdout.strip()
  except subprocess.CalledProcessError as e:
    print(
        "Warning: Command failed:"
        f" {' '.join(cmd) if not isinstance(cmd, str) else cmd}",
        file=sys.stderr,
    )
    print(f"Error output: {e.stderr.strip()}", file=sys.stderr)
    return None
  except FileNotFoundError as e:
    cmd_name = cmd[0] if not isinstance(cmd, str) else cmd.split()[0]
    print(f"Warning: Command not found: {cmd_name}", file=sys.stderr)
    return None


def find_agent_via_cais(
    project_id: str, agent_name: str
) -> dict[str, str] | None:
  """Searches for the agent using Cloud Asset Inventory (CAIS)."""
  print("Attempting fast lookup via Cloud Asset Inventory (CAIS)...")
  cmd = [
      "gcloud",
      "asset",
      "search-all-resources",
      f"--scope=projects/{project_id}",
      (
          "--asset-types=aiplatform.googleapis.com/ReasoningEngine,"
          "run.googleapis.com/Service"
      ),
      f"--query={agent_name}",
      "--format=json",
  ]
  output = run_command(cmd)
  if not output:
    return None

  try:
    assets = json.loads(output)
    for asset in assets:
      if asset.get("displayName") == agent_name:
        location = asset.get("location", "unknown")
        asset_type = asset.get("assetType")

        if asset_type == "aiplatform.googleapis.com/ReasoningEngine":
          print(f"FOUND via CAIS: Reasoning Engine in {location}")
          full_name = asset.get("name", "")
          engine_id = full_name.split("/")[-1] if full_name else agent_name

          return {
              "runtime": "Vertex AI Reasoning Engine",
              "id": engine_id,
              "display_name": agent_name,
              "location": location,
              "resource_name": (
                  full_name.split("//aiplatform.googleapis.com/")[-1]
                  if "//aiplatform.googleapis.com/" in full_name
                  else full_name
              ),
          }
        elif asset_type == "run.googleapis.com/Service":
          print(f"FOUND via CAIS: Cloud Run service in {location}")
          return {
              "runtime": "Cloud Run",
              "id": agent_name,
              "display_name": agent_name,
              "location": location,
              "resource_name": agent_name,
          }
  except json.JSONDecodeError:
    print("Warning: Error parsing CAIS output", file=sys.stderr)

  return None


def find_reasoning_engine(
    project_id: str, agent_name: str, regions: Sequence[str] | None = None
) -> dict[str, str] | None:
  """Searches for a Reasoning Engine by display name in common regions."""
  if not regions:
    regions = DEFAULT_VERTEX_REGIONS
  print(f"Scanning Vertex AI Reasoning Engines in {regions}...")

  for location in regions:
    try:
      client = aiplatform_v1beta1.ReasoningEngineServiceClient(
          client_options={
              "api_endpoint": f"{location}-aiplatform.googleapis.com"
          }
      )
      parent = f"projects/{project_id}/locations/{location}"
      engines = list(client.list_reasoning_engines(parent=parent))

      for engine in engines:
        if engine.display_name == agent_name:
          print(f"FOUND: Reasoning Engine in {location}")
          return {
              "runtime": "Vertex AI Reasoning Engine",
              "id": engine.name.split("/")[-1],
              "display_name": engine.display_name,
              "location": location,
              "resource_name": engine.name,
          }
    except Exception as e:
      # Might be permission error or API not enabled in this region, continue to
      # next
      continue
  return None


def find_cloud_run_service(
    project_id: str, agent_name: str
) -> dict[str, str] | None:
  """Searches for a Cloud Run service by name."""
  print("Checking Cloud Run services...")
  cmd = [
      "gcloud",
      "run",
      "services",
      "list",
      f"--project={project_id}",
      "--format=json",
  ]
  output = run_command(cmd)
  if not output:
    return None

  try:
    services = json.loads(output)
    for svc in services:
      if svc.get("metadata", {}).get("name") == agent_name:
        location = (
            svc.get("metadata", {})
            .get("labels", {})
            .get("cloud.googleapis.com/location", "unknown")
        )
        print(f"FOUND: Cloud Run service in {location}")
        return {
            "runtime": "Cloud Run",
            "id": agent_name,
            "display_name": agent_name,
            "location": location,
            "resource_name": agent_name,
        }
  except json.JSONDecodeError:
    print("Error parsing Cloud Run services output", file=sys.stderr)
  return None


def check_metric_scope(project_id: str) -> str | list[dict[str, Any]]:
  """Checks if the project is part of a multi-project metric scope."""
  print("Checking Metric Scope...")
  cmd = [
      "gcloud",
      "beta",
      "monitoring",
      "metrics-scopes",
      "list",
      f"projects/{project_id}",
      "--format=json",
  ]
  output = run_command(cmd)
  if output:
    try:
      scopes = json.loads(output)
      return scopes
    except json.JSONDecodeError:
      pass
  return "Standard Self-Scoped"


def check_bq_datasets(project_id: str) -> list[dict[str, Any]]:
  """Lists linked BQ datasets."""
  print("Checking BigQuery Datasets...")
  cmd = ["bq", "ls", "--format=prettyjson", f"--project_id={project_id}"]
  output = run_command(cmd)
  if output:
    try:
      datasets = json.loads(output)
      linked = [d for d in datasets if d.get("type") == "LINKED"]
      return linked
    except json.JSONDecodeError:
      pass
  return []


def get_notification_channels(project_id: str) -> list[dict[str, Any]]:
  """Lists notification channels."""
  print("Checking Notification Channels...")
  cmd = [
      "gcloud",
      "beta",
      "monitoring",
      "channels",
      "list",
      f"--project={project_id}",
      "--format=json",
  ]
  output = run_command(cmd)
  if output:
    try:
      return json.loads(output)
    except json.JSONDecodeError:
      pass
  return []


def check_telemetry_status(
    project_id: str, location: str, agent_id: str, skill_path: str
) -> str | None:
  """Runs check_telemetry.py script."""
  local_dir = os.path.dirname(os.path.abspath(__file__))
  check_script = os.path.join(local_dir, "check_telemetry.py")
  if not os.path.exists(check_script):
    check_script = os.path.join(
        skill_path, "scripts", "agent_platform", "check_telemetry.py"
    )

  if os.path.exists(check_script):
    cmd = [
        "python3",
        check_script,
        "--project-id",
        project_id,
        "--location",
        location,
        "--agent-resource-name",
        agent_id,
    ]
    return run_command(cmd)
  print(
      f"Warning: check_telemetry.py not found at {check_script}",
      file=sys.stderr,
  )
  return None


def check_online_evaluators(
    project_id: str, location: str, agent_resource_name: str
) -> list[dict[str, Any]]:
  """Checks if Online Evaluators exist for the agent."""
  try:
    client = aiplatform_v1beta1.OnlineEvaluatorServiceClient(
        client_options={"api_endpoint": f"{location}-aiplatform.googleapis.com"}
    )
    parent = f"projects/{project_id}/locations/{location}"
    request = aiplatform_v1beta1.ListOnlineEvaluatorsRequest(parent=parent)
    page_result = client.list_online_evaluators(request=request)
    matching_evaluators = []
    for evaluator in page_result:
      if evaluator.agent_resource == agent_resource_name:
        evaluator_info = {
            "name": evaluator.name,
            "display_name": evaluator.display_name,
        }
        if hasattr(evaluator, "metrics"):
          evaluator_info["metrics"] = [m.metric for m in evaluator.metrics]
        matching_evaluators.append(evaluator_info)
    return matching_evaluators
  except Exception as e:
    print(f"Warning: Error checking Online Evaluators: {e}", file=sys.stderr)
    return []


def derive_trace_table(project_id: str, skill_path: str) -> str | None:
  """Runs list_trace_scope_table_names.py script."""
  local_dir = os.path.dirname(os.path.abspath(__file__))
  list_trace_script = os.path.join(local_dir, "list_trace_scope_table_names.py")
  if not os.path.exists(list_trace_script):
    list_trace_script = os.path.join(
        skill_path,
        "scripts",
        "agent_platform",
        "list_trace_scope_table_names.py",
    )

  if os.path.exists(list_trace_script):
    cmd = ["python3", list_trace_script, "--project_id", project_id]
    return run_command(cmd)
  print(
      "Warning: list_trace_scope_table_names.py not found at"
      f" {list_trace_script}",
      file=sys.stderr,
  )
  return None


def derive_log_table(project_id: str, skill_path: str) -> str | None:
  """Runs list_log_scope_table_names.py script."""
  local_dir = os.path.dirname(os.path.abspath(__file__))
  list_log_script = os.path.join(local_dir, "list_log_scope_table_names.py")
  if not os.path.exists(list_log_script):
    list_log_script = os.path.join(
        skill_path,
        "scripts",
        "agent_platform",
        "list_log_scope_table_names.py",
    )

  if os.path.exists(list_log_script):
    cmd = ["python3", list_log_script, "--project_id", project_id]
    return run_command(cmd)
  print(
      f"Warning: list_log_scope_table_names.py not found at {list_log_script}",
      file=sys.stderr,
  )
  return None


def main():
  parser = argparse.ArgumentParser(description="Gather Agent Info for Alerting")
  parser.add_argument("--project-id", required=True, help="GCP Project ID")
  parser.add_argument(
      "--agent-name", required=True, help="Agent Display Name or Service Name"
  )
  default_skill_path = os.path.dirname(
      os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  )
  parser.add_argument(
      "--skill-path",
      help="Path to agent-platform-alert-configuration skill",
      default=default_skill_path,
  )
  parser.add_argument(
      "--regions",
      help=(
          "Comma-separated list of regions to scan (e.g., us-central1,us-east1)"
      ),
      default=None,
  )
  args = parser.parse_args()

  project_id = args.project_id
  agent_name = args.agent_name
  skill_path = args.skill_path
  regions = args.regions.split(",") if args.regions else None

  print(
      f"=== GATHERING INFO FOR AGENT: {agent_name} IN PROJECT: {project_id} ==="
  )

  # 1. Try to find agent
  agent_info = find_agent_via_cais(project_id, agent_name)

  if not agent_info:
    print(
        "Fast lookup failed or returned no results. Falling back to regional"
        " polling..."
    )
    agent_info = find_reasoning_engine(project_id, agent_name, regions)
    if not agent_info:
      agent_info = find_cloud_run_service(project_id, agent_name)

  if not agent_info:
    print(
        f"\n❌ CRITICAL: Agent '{agent_name}' not found as Reasoning Engine or"
        f" Cloud Run service in project '{project_id}'."
    )
    print("Please verify the name and project.")
    sys.exit(1)

  print("\n=== AGENT IDENTIFICATION ===")
  print(json.dumps(agent_info, indent=2))

  # 2. Check Telemetry and Online Evaluators if Vertex AI
  if agent_info["runtime"] == "Vertex AI Reasoning Engine":
    print("\n=== TELEMETRY STATUS ===")
    output = check_telemetry_status(
        project_id, agent_info["location"], agent_info["id"], skill_path
    )
    if output:
      print(output)

    print("\n=== ONLINE EVALUATORS ===")
    evaluators = check_online_evaluators(
        project_id, agent_info["location"], agent_info["resource_name"]
    )
    print(f"Found {len(evaluators)} Online Evaluators for this agent.")
    if evaluators:
      print(json.dumps(evaluators[:5], indent=2))
      if len(evaluators) > 5:
        print(f"... and {len(evaluators) - 5} more evaluators.")

  # 3. Environment Checks
  print("\n=== ENVIRONMENT CHECKS ===")

  # Metric Scope
  scopes = check_metric_scope(project_id)
  print(
      "Metric Scope Status:"
      f" {scopes if isinstance(scopes, str) else 'Multi-Project'}"
  )
  if isinstance(scopes, list):
    print(json.dumps(scopes[:5], indent=2))
    if len(scopes) > 5:
      print(f"... and {len(scopes) - 5} more scope projects.")

  # BQ Datasets
  linked_datasets = check_bq_datasets(project_id)
  print(f"Linked BigQuery Datasets: {len(linked_datasets)} found")
  if linked_datasets:
    print(json.dumps(linked_datasets[:5], indent=2))
    if len(linked_datasets) > 5:
      print(f"... and {len(linked_datasets) - 5} more datasets.")

  # Trace Table Name
  print("\n=== TRACE TABLE ===")
  output = derive_trace_table(project_id, skill_path)
  if output:
    print(f"Derived Trace Table(s):\n{output}")

  # Log Table Name
  print("\n=== LOG TABLE ===")
  output = derive_log_table(project_id, skill_path)
  if output:
    print(f"Derived Log Table(s):\n{output}")

  # Notification Channels
  channels = get_notification_channels(project_id)
  print("\n=== NOTIFICATION CHANNELS ===")
  print(f"{len(channels)} found")
  if channels:
    # Print a summary of types/names
    summary = [
        {"displayName": c.get("displayName"), "type": c.get("type")}
        for c in channels
    ]
    print(json.dumps(summary[:5], indent=2))
    if len(channels) > 5:
      print(f"... and {len(channels) - 5} more channels.")

  print("\n=== SUMMARY COMPLETE ===")


if __name__ == "__main__":
  main()
gather_agent_info_test.py 11.0 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests for gather_agent_info.py."""

import json
import os
import subprocess
import sys
import unittest
from unittest import mock

# Mock the import of aiplatform_v1beta1 in case it's not installed in the test
# environment. This allows the module to be executed/parsed without failing on
# import
try:
  import google.cloud.aiplatform_v1beta1  # pytype: disable=import-error  # pyrefly: ignore[missing-import]
except ImportError:
  mock_aiplatform = mock.MagicMock()
  sys.modules["google.cloud.aiplatform_v1beta1"] = mock_aiplatform
  sys.modules["google.cloud"] = mock.MagicMock()

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import gather_agent_info  # pytype: disable=import-error  # pyrefly: ignore[missing-import]


class GatherAgentInfoTest(unittest.TestCase):

  def setUp(self):
    super().setUp()
    self.project_id = "test-project"
    self.agent_name = "test-agent"

  @mock.patch("gather_agent_info.subprocess.run")
  def test_run_command_success(self, mock_run):
    mock_result = mock.Mock()
    mock_result.stdout = "success_output\n"
    mock_result.returncode = 0
    mock_run.return_value = mock_result

    result = gather_agent_info.run_command(["echo", "hello"])
    self.assertEqual(result, "success_output")
    mock_run.assert_called_once()

  @mock.patch("gather_agent_info.subprocess.run")
  def test_run_command_failure(self, mock_run):
    mock_run.side_effect = subprocess.CalledProcessError(
        returncode=1, cmd="fail", stderr="error_output\n"
    )

    result = gather_agent_info.run_command(["fail_cmd"])
    self.assertIsNone(result)

  @mock.patch(
      "gather_agent_info.aiplatform_v1beta1.ReasoningEngineServiceClient"
  )
  def test_find_reasoning_engine_found(self, mock_client_class):
    mock_client = mock_client_class.return_value
    mock_engine = mock.Mock()
    mock_engine.display_name = self.agent_name
    mock_engine.name = (
        f"projects/{self.project_id}/locations/us-central1/reasoningEngines/"
        "12345"
    )
    mock_client.list_reasoning_engines.return_value = [mock_engine]

    result = gather_agent_info.find_reasoning_engine(
        self.project_id, self.agent_name
    )

    self.assertIsNotNone(result)
    self.assertEqual(result["runtime"], "Vertex AI Reasoning Engine")
    self.assertEqual(result["id"], "12345")
    self.assertEqual(result["display_name"], self.agent_name)
    self.assertEqual(result["location"], "us-central1")

  @mock.patch(
      "gather_agent_info.aiplatform_v1beta1.ReasoningEngineServiceClient"
  )
  def test_find_reasoning_engine_not_found(self, mock_client_class):
    mock_client = mock_client_class.return_value
    mock_engine = mock.Mock()
    mock_engine.display_name = "other-agent"
    mock_client.list_reasoning_engines.return_value = [mock_engine]

    result = gather_agent_info.find_reasoning_engine(
        self.project_id, self.agent_name
    )

    self.assertIsNone(result)

  @mock.patch(
      "gather_agent_info.aiplatform_v1beta1.ReasoningEngineServiceClient"
  )
  def test_find_reasoning_engine_custom_regions(self, mock_client_class):
    mock_client = mock_client_class.return_value
    mock_engine = mock.Mock()
    mock_engine.display_name = self.agent_name
    mock_engine.name = (
        f"projects/{self.project_id}/locations/us-east4/reasoningEngines/12345"
    )
    mock_client.list_reasoning_engines.return_value = [mock_engine]

    custom_regions = ["us-east4", "us-west2"]
    result = gather_agent_info.find_reasoning_engine(
        self.project_id, self.agent_name, custom_regions
    )

    self.assertIsNotNone(result)
    self.assertEqual(result["location"], "us-east4")
    mock_client_class.assert_any_call(
        client_options={"api_endpoint": "us-east4-aiplatform.googleapis.com"}
    )

  @mock.patch("gather_agent_info.run_command")
  def test_find_cloud_run_service_found(self, mock_run_command):
    mock_services = [
        {
            "metadata": {
                "name": "other-agent",
                "labels": {"cloud.googleapis.com/location": "us-east1"},
            }
        },
        {
            "metadata": {
                "name": self.agent_name,
                "labels": {"cloud.googleapis.com/location": "us-central1"},
            }
        },
    ]
    mock_run_command.return_value = json.dumps(mock_services)

    result = gather_agent_info.find_cloud_run_service(
        self.project_id, self.agent_name
    )

    self.assertIsNotNone(result)
    self.assertEqual(result["runtime"], "Cloud Run")
    self.assertEqual(result["id"], self.agent_name)
    self.assertEqual(result["location"], "us-central1")

  @mock.patch("gather_agent_info.run_command")
  def test_find_cloud_run_service_not_found(self, mock_run_command):
    mock_services = [{"metadata": {"name": "other-agent"}}]
    mock_run_command.return_value = json.dumps(mock_services)

    result = gather_agent_info.find_cloud_run_service(
        self.project_id, self.agent_name
    )

    self.assertIsNone(result)

  @mock.patch("gather_agent_info.run_command")
  def test_check_metric_scope(self, mock_run_command):
    mock_scopes = [{"name": "locations/global/metricsScopes/12345"}]
    mock_run_command.return_value = json.dumps(mock_scopes)

    result = gather_agent_info.check_metric_scope(self.project_id)
    self.assertEqual(result, mock_scopes)

  @mock.patch("gather_agent_info.run_command")
  def test_check_bq_datasets(self, mock_run_command):
    mock_datasets = [
        {"datasetReference": {"datasetId": "a"}, "type": "DEFAULT"},
        {"datasetReference": {"datasetId": "b"}, "type": "LINKED"},
    ]
    mock_run_command.return_value = json.dumps(mock_datasets)

    result = gather_agent_info.check_bq_datasets(self.project_id)
    self.assertEqual(len(result), 1)
    self.assertEqual(result[0]["type"], "LINKED")

  @mock.patch("gather_agent_info.run_command")
  def test_get_notification_channels(self, mock_run_command):
    mock_channels = [{"displayName": "Email", "type": "email"}]
    mock_run_command.return_value = json.dumps(mock_channels)

    result = gather_agent_info.get_notification_channels(self.project_id)
    self.assertEqual(result, mock_channels)

  @mock.patch("gather_agent_info.run_command")
  @mock.patch("gather_agent_info.os.path.exists")
  def test_check_telemetry_status(self, mock_exists, mock_run_command):
    mock_exists.return_value = True
    mock_run_command.return_value = "telemetry_ok"
    result = gather_agent_info.check_telemetry_status(
        self.project_id, "us-central1", "12345", "/tmp"
    )
    self.assertEqual(result, "telemetry_ok")
    mock_run_command.assert_called_once()

  @mock.patch(
      "gather_agent_info.aiplatform_v1beta1.OnlineEvaluatorServiceClient"
  )
  def test_check_online_evaluators(self, mock_client_class):
    mock_client = mock_client_class.return_value
    mock_evaluator = mock.Mock()
    mock_evaluator.name = "eval-1"
    mock_evaluator.display_name = "Eval 1"
    mock_evaluator.agent_resource = (
        f"projects/{self.project_id}/locations/us-central1/reasoningEngines/"
        "12345"
    )
    mock_metric = mock.Mock()
    mock_metric.metric = "quality"
    mock_evaluator.metrics = [mock_metric]
    mock_client.list_online_evaluators.return_value = [mock_evaluator]

    result = gather_agent_info.check_online_evaluators(
        self.project_id, "us-central1", mock_evaluator.agent_resource
    )
    self.assertEqual(len(result), 1)
    self.assertEqual(result[0]["name"], "eval-1")
    self.assertEqual(result[0]["metrics"], ["quality"])

  @mock.patch("gather_agent_info.run_command")
  @mock.patch("gather_agent_info.os.path.exists")
  def test_derive_trace_table(self, mock_exists, mock_run_command):
    mock_exists.return_value = True
    mock_run_command.return_value = "trace_table_name"
    result = gather_agent_info.derive_trace_table(self.project_id, "/tmp")
    self.assertEqual(result, "trace_table_name")

  @mock.patch("gather_agent_info.run_command")
  @mock.patch("gather_agent_info.os.path.exists")
  def test_derive_log_table(self, mock_exists, mock_run_command):
    mock_exists.return_value = True
    mock_run_command.return_value = "log_table_name"
    result = gather_agent_info.derive_log_table(self.project_id, "/tmp")
    self.assertEqual(result, "log_table_name")

  @mock.patch("gather_agent_info.run_command")
  def test_find_agent_via_cais_reasoning_engine(self, mock_run_command):
    mock_assets = [{
        "assetType": "aiplatform.googleapis.com/ReasoningEngine",
        "displayName": self.agent_name,
        "location": "us-central1",
        "name": (
            "//aiplatform.googleapis.com/projects/755054710983/locations/"
            "us-central1/reasoningEngines/12345"
        ),
    }]
    mock_run_command.return_value = json.dumps(mock_assets)

    result = gather_agent_info.find_agent_via_cais(
        self.project_id, self.agent_name
    )

    self.assertIsNotNone(result)
    self.assertEqual(result["runtime"], "Vertex AI Reasoning Engine")
    self.assertEqual(result["id"], "12345")
    self.assertEqual(result["location"], "us-central1")
    self.assertEqual(
        result["resource_name"],
        "projects/755054710983/locations/us-central1/reasoningEngines/12345",
    )

  @mock.patch("gather_agent_info.run_command")
  def test_find_agent_via_cais_cloud_run(self, mock_run_command):
    mock_assets = [{
        "assetType": "run.googleapis.com/Service",
        "displayName": self.agent_name,
        "location": "us-central1",
        "name": (
            "//run.googleapis.com/projects/755054710983/locations/"
            "us-central1/services/test-agent"
        ),
    }]
    mock_run_command.return_value = json.dumps(mock_assets)

    result = gather_agent_info.find_agent_via_cais(
        self.project_id, self.agent_name
    )

    self.assertIsNotNone(result)
    self.assertEqual(result["runtime"], "Cloud Run")
    self.assertEqual(result["id"], self.agent_name)
    self.assertEqual(result["location"], "us-central1")

  @mock.patch("gather_agent_info.run_command")
  def test_find_agent_via_cais_not_found(self, mock_run_command):
    mock_assets = [{
        "assetType": "aiplatform.googleapis.com/ReasoningEngine",
        "displayName": "other-agent",
        "location": "us-central1",
        "name": (
            "//aiplatform.googleapis.com/projects/755054710983/locations/"
            "us-central1/reasoningEngines/other"
        ),
    }]
    mock_run_command.return_value = json.dumps(mock_assets)

    result = gather_agent_info.find_agent_via_cais(
        self.project_id, self.agent_name
    )

    self.assertIsNone(result)


if __name__ == "__main__":
  unittest.main()
lint_syntax.py 1.9 KB
#!/usr/bin/env python3
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Lints a single specific HCL file for PromQL syntax and duration compliance."""

import argparse
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from config_utils import extract_alert_policies, lint_query, validate_policy_duration  # pytype: disable=import-error  # pyrefly: ignore[missing-import]

def main():
  parser = argparse.ArgumentParser(
      description="Lints a single specific HCL file for PromQL syntax and duration compliance."
  )
  parser.add_argument(
      "file",
      type=str,
      help="Path to the HCL file to lint.",
  )
  args = parser.parse_args()

  try:
    with open(args.file, "r") as f:
      content = f.read()
    policies = extract_alert_policies(content)
    errors = []
    for p in policies:
      if not p.get("is_sql"):
        for q in p["queries"]:
          errors.extend(lint_query(q))
        errors.extend(validate_policy_duration(p))
    if errors:
      print(f"Validation failed for '{args.file}':", file=sys.stderr)
      for err in errors:
        print(f"  - {err}", file=sys.stderr)
      sys.exit(1)
    else:
      print(f"Validation passed for '{args.file}'!")
      sys.exit(0)
  except Exception as e:
    print(f"Error reading file '{args.file}': {e}", file=sys.stderr)
    sys.exit(1)

if __name__ == "__main__":
  main()
list_log_scope_table_names.py 4.7 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Helper script to derive Observability Analytics table names.

This script identifies tables containing log data for a given GCP project.
"""

import argparse
import re
import sys

import google.auth
import google.auth.exceptions
import google.auth.transport.requests
import requests


def get_access_token() -> str:
  """Gets an OAuth2 access token using Google Application Default Credentials.

  Returns:
      A string containing the OAuth2 access token.
  """
  credentials, _ = google.auth.default(
      scopes=['https://www.googleapis.com/auth/cloud-platform']
  )
  auth_req = google.auth.transport.requests.Request()
  credentials.refresh(auth_req)
  return credentials.token


def list_log_buckets_names(project_id: str, token: str) -> list[str]:
  """Lists all log bucket names for the given GCP project.

  Args:
      project_id: The GCP project ID.
      token: OAuth2 access token.

  Returns:
      A list of log bucket resource names.
  """
  url = (
      'https://logging.googleapis.com/v2/projects/'
      f'{project_id}/locations/-/buckets'
  )
  headers = {'Authorization': f'Bearer {token}'}
  response = requests.get(url, headers=headers, timeout=10)
  if response.status_code != 200:
    print(f'Error listing log scopes: {response.text}', file=sys.stderr)
    return []
  bucket_names = []
  for bucket in response.json().get('buckets', []):
    bucket_names.append(bucket.get('name', ''))
  return bucket_names


def get_bucket_all_logs_views(bucket_name: str, token: str) -> str | None:
  """Finds the location of the '_AllLogs' log bucket for the given GCP project.

  Args:
      bucket_name: The name of the log bucket to query the views for.
      token: OAuth2 access token.

  Returns:
      The name of the '_AllLogs' log bucket view if found, otherwise None.
  """
  url = f'https://logging.googleapis.com/v2/{bucket_name}/views'
  headers = {'Authorization': f'Bearer {token}'}
  response = requests.get(url, headers=headers, timeout=10)
  if response.status_code != 200:
    print(
        f'Error listing bucket views for {bucket_name}: {response.text}',
        file=sys.stderr,
    )
    return None
  views = response.json().get('views', [])
  for view in views:
    if view.get('name', '').endswith('/views/_AllLogs'):
      match = re.match(
          r'projects/[^/]+/locations/([^/]+)/buckets/([^/]+)/views/_AllLogs',
          view['name'],
      )
      if match:
        return view['name']
  return None


def parse_table_name_from_bucket_view(view_path: str | None) -> str | None:
  """Parses the table name from the log bucket view name.

  Args:
      view_path: The full resource path of the log bucket view.

  Returns:
      The derived table name for use in Observability Analytics queries, or None
      if parsing fails.
  """
  if not view_path:
    return None
  match = re.match(
      r'projects/([^/]+)/locations/([^/]+)/buckets/([^/]+)/views/([^/]+)',
      view_path,
  )
  if match:
    return (
        f'{match.group(1)}.{match.group(2)}.{match.group(3)}.{match.group(4)}'
    )
  return None


def main():
  parser = argparse.ArgumentParser(
      description=(
          'Derive Observability Analytics log table names for a project.'
      )
  )
  parser.add_argument(
      '--project_id', required=True, help='GCP Project ID to query.'
  )
  args = parser.parse_args()
  project_id = args.project_id

  try:
    token = get_access_token()
  except google.auth.exceptions.GoogleAuthError as e:
    print(f'Failed to get credentials: {e}', file=sys.stderr)
    sys.exit(1)

  buckets = list_log_buckets_names(project_id, token)
  if not buckets:
    print(f'No log buckets found for project {project_id}')
    sys.exit(0)

  table_names = []
  for bucket in buckets:
    all_logs_view_location = get_bucket_all_logs_views(bucket, token)
    if all_logs_view_location:
      table_name = parse_table_name_from_bucket_view(all_logs_view_location)
      if table_name:
        table_names.append(table_name)
    else:
      print(
          f'Could not find _AllLogs bucket view location for bucket {bucket}',
          file=sys.stderr,
      )

  if table_names:
    for table_name in table_names:
      print(table_name)
  else:
    print('No table names found.')


if __name__ == '__main__':
  main()
list_log_scope_table_names_test.py 8.6 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Unit tests for list_log_scope_table_names.py."""

import io
import os
import sys
import unittest
from unittest import mock

import google.auth.exceptions


# pylint: disable=g-import-not-at-top
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import list_log_scope_table_names  # pytype: disable=import-error  # pyrefly: ignore[missing-import]


class TestListLogScopeTableNames(unittest.TestCase):

  @mock.patch("google.auth.default")
  @mock.patch("google.auth.transport.requests.Request")
  def test_get_access_token_success(self, _, mock_auth_default):
    mock_credentials = mock.Mock()
    mock_credentials.token = "test-token"
    mock_auth_default.return_value = (mock_credentials, "test-project")

    token = list_log_scope_table_names.get_access_token()

    self.assertEqual(token, "test-token")
    mock_credentials.refresh.assert_called_once()

  @mock.patch("requests.get")
  def test_list_log_buckets_names_success(self, mock_get):
    mock_response = mock.Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "buckets": [
            {"name": "projects/test-project/locations/global/buckets/_Default"},
            {"name": "projects/test-project/locations/us-central1/buckets/b1"},
        ]
    }
    mock_get.return_value = mock_response

    bucket_names = list_log_scope_table_names.list_log_buckets_names(
        "test-project", "test-token"
    )

    self.assertEqual(
        bucket_names,
        [
            "projects/test-project/locations/global/buckets/_Default",
            "projects/test-project/locations/us-central1/buckets/b1",
        ],
    )
    mock_get.assert_called_once_with(
        "https://logging.googleapis.com/v2/projects/test-project/locations/-/buckets",
        headers={"Authorization": "Bearer test-token"},
        timeout=10,
    )

  @mock.patch("requests.get")
  def test_list_log_buckets_names_failure(self, mock_get):
    mock_response = mock.Mock()
    mock_response.status_code = 403
    mock_response.text = "Permission Denied"
    mock_get.return_value = mock_response

    with mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr:
      bucket_names = list_log_scope_table_names.list_log_buckets_names(
          "test-project", "test-token"
      )

    self.assertEqual(bucket_names, [])
    self.assertIn("Error listing log scopes:", mock_stderr.getvalue())

  @mock.patch("requests.get")
  def test_get_bucket_all_logs_views_found(self, mock_get):
    mock_response = mock.Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "views": [
            {
                "name": (
                    "projects/test-project/locations/global/buckets/_Default/views/_AllLogs"
                )
            },
            {
                "name": (
                    "projects/test-project/locations/global/buckets/_Default/views/custom"
                )
            },
        ]
    }
    mock_get.return_value = mock_response

    view_name = list_log_scope_table_names.get_bucket_all_logs_views(
        "projects/test-project/locations/global/buckets/_Default", "test-token"
    )

    self.assertEqual(
        view_name,
        "projects/test-project/locations/global/buckets/_Default/views/_AllLogs",
    )
    mock_get.assert_called_once_with(
        "https://logging.googleapis.com/v2/projects/test-project/locations/global/buckets/_Default/views",
        headers={"Authorization": "Bearer test-token"},
        timeout=10,
    )

  @mock.patch("requests.get")
  def test_get_bucket_all_logs_views_not_found(self, mock_get):
    mock_response = mock.Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "views": [{
            "name": (
                "projects/test-project/locations/global/buckets/_Default/views/custom"
            )
        }]
    }
    mock_get.return_value = mock_response

    view_name = list_log_scope_table_names.get_bucket_all_logs_views(
        "projects/test-project/locations/global/buckets/_Default", "test-token"
    )

    self.assertIsNone(view_name)

  @mock.patch("requests.get")
  def test_get_bucket_all_logs_views_error(self, mock_get):
    mock_response = mock.Mock()
    mock_response.status_code = 500
    mock_response.text = "Internal Server Error"
    mock_get.return_value = mock_response

    with mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr:
      view_name = list_log_scope_table_names.get_bucket_all_logs_views(
          "projects/test-project/locations/global/buckets/_Default",
          "test-token",
      )

    self.assertIsNone(view_name)
    self.assertIn("Error listing bucket views for", mock_stderr.getvalue())

  def test_parse_table_name_from_bucket_view_success(self):
    table_name = list_log_scope_table_names.parse_table_name_from_bucket_view(
        "projects/test-project/locations/global/buckets/_Default/views/_AllLogs"
    )
    self.assertEqual(table_name, "test-project.global._Default._AllLogs")

  def test_parse_table_name_from_bucket_view_none(self):
    table_name = list_log_scope_table_names.parse_table_name_from_bucket_view(
        None
    )
    self.assertIsNone(table_name)

  def test_parse_table_name_from_bucket_view_no_match(self):
    table_name = list_log_scope_table_names.parse_table_name_from_bucket_view(
        "invalid-view-string"
    )
    self.assertIsNone(table_name)

  @mock.patch("list_log_scope_table_names.get_access_token")
  @mock.patch("list_log_scope_table_names.list_log_buckets_names")
  @mock.patch("list_log_scope_table_names.get_bucket_all_logs_views")
  def test_main_success(
      self, mock_get_views, mock_list_buckets, mock_get_token
  ):
    mock_get_token.return_value = "test-token"
    mock_list_buckets.return_value = [
        "projects/test-project/locations/global/buckets/_Default",
        "projects/test-project/locations/global/buckets/missing",
    ]
    mock_get_views.side_effect = lambda bucket, token: (
        f"{bucket}/views/_AllLogs" if "_Default" in bucket else None
    )

    with (
        mock.patch(
            "sys.argv",
            ["list_log_scope_table_names.py", "--project_id", "test-project"],
        ),
        mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout,
        mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr,
    ):
      list_log_scope_table_names.main()

    output = mock_stdout.getvalue()
    err_output = mock_stderr.getvalue()

    self.assertIn("test-project.global._Default._AllLogs", output)
    self.assertIn(
        "Could not find _AllLogs bucket view location for bucket"
        " projects/test-project/locations/global/buckets/missing",
        err_output,
    )

  @mock.patch("list_log_scope_table_names.get_access_token")
  @mock.patch("list_log_scope_table_names.list_log_buckets_names")
  def test_main_no_buckets(self, mock_list_buckets, mock_get_token):
    mock_get_token.return_value = "test-token"
    mock_list_buckets.return_value = []

    with (
        mock.patch(
            "sys.argv",
            ["list_log_scope_table_names.py", "--project_id", "test-project"],
        ),
        mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout,
        self.assertRaises(SystemExit) as cm,
    ):
      list_log_scope_table_names.main()

    self.assertEqual(cm.exception.code, 0)
    self.assertIn(
        "No log buckets found for project test-project", mock_stdout.getvalue()
    )

  @mock.patch("list_log_scope_table_names.get_access_token")
  def test_main_token_failure(self, mock_get_token):
    mock_get_token.side_effect = google.auth.exceptions.GoogleAuthError(
        "Auth failed"
    )

    with (
        mock.patch(
            "sys.argv",
            ["list_log_scope_table_names.py", "--project_id", "test-project"],
        ),
        mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr,
        self.assertRaises(SystemExit) as cm,
    ):
      list_log_scope_table_names.main()

    self.assertEqual(cm.exception.code, 1)
    self.assertIn(
        "Failed to get credentials: Auth failed", mock_stderr.getvalue()
    )


if __name__ == "__main__":
  unittest.main()
list_trace_scope_table_names.py 4.3 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Helper script to derive Observability Analytics table names.

This script identifies tables containing trace span data for a given GCP
project.
"""

import argparse
import re
import sys

import google.auth
import google.auth.exceptions
import google.auth.transport.requests
import requests


def get_access_token() -> str:
  """Gets an OAuth2 access token using Google Application Default Credentials.

  Returns:
      A string containing the OAuth2 access token.
  """
  credentials, _ = google.auth.default(
      scopes=['https://www.googleapis.com/auth/cloud-platform']
  )
  auth_req = google.auth.transport.requests.Request()
  credentials.refresh(auth_req)
  return credentials.token


def list_trace_scopes(project_id: str, token: str) -> list[dict]:
  """Lists all trace scopes for the given GCP project.

  Args:
      project_id: The GCP project ID.
      token: OAuth2 access token.

  Returns:
      A list of dictionaries representing trace scopes.
  """
  url = (
      'https://observability.googleapis.com/v1/projects/'
      f'{project_id}/locations/global/traceScopes'
  )
  headers = {'Authorization': f'Bearer {token}'}
  response = requests.get(url, headers=headers, timeout=10)
  if response.status_code != 200:
    print(f'Error listing trace scopes: {response.text}', file=sys.stderr)
    return []
  return response.json().get('traceScopes', [])


def get_bucket_location(project_id: str, token: str) -> str | None:
  """Finds the location of the '_Trace' log bucket for the given GCP project.

  Args:
      project_id: The ID of the GCP project to query.
      token: OAuth2 access token.

  Returns:
      The location string (e.g., 'us-central1') of the '_Trace' bucket, or None
      if it cannot be found or an error occurs.
  """
  url = (
      'https://observability.googleapis.com/v1/projects/'
      f'{project_id}/locations/-/buckets'
  )
  headers = {'Authorization': f'Bearer {token}'}
  response = requests.get(url, headers=headers, timeout=10)
  if response.status_code != 200:
    print(
        f'Error listing buckets for {project_id}: {response.text}',
        file=sys.stderr,
    )
    return None
  buckets = response.json().get('buckets', [])
  for bucket in buckets:
    if bucket.get('name', '').endswith('/buckets/_Trace'):
      match = re.match(
          r'projects/[^/]+/locations/([^/]+)/buckets/_Trace', bucket['name']
      )
      if match:
        return match.group(1)
  return None


def main():
  parser = argparse.ArgumentParser(
      description='Derive Observability Analytics table names for a project.'
  )
  parser.add_argument(
      '--project_id', required=True, help='GCP Project ID to query.'
  )
  args = parser.parse_args()
  project_id = args.project_id

  try:
    token = get_access_token()
  except google.auth.exceptions.GoogleAuthError as e:
    print(f'Failed to get credentials: {e}', file=sys.stderr)
    sys.exit(1)

  scopes = list_trace_scopes(project_id, token)
  if not scopes:
    print(f'No trace scopes found for project {project_id}')
    sys.exit(0)

  target_projects = set()
  for scope in scopes:
    resources = scope.get('resourceNames', [])
    for resource in resources:
      if resource.startswith('projects/'):
        target_projects.add(resource.split('/')[1])
  if not target_projects:
    target_projects.add(project_id)

  table_names = []
  for proj in target_projects:
    location = get_bucket_location(proj, token)
    if location:
      table_name = f'{proj}.{location}._Trace.Spans._AllSpans'
      table_names.append(table_name)
    else:
      print(
          f'Could not find _Trace bucket location for project {proj}',
          file=sys.stderr,
      )

  if table_names:
    for table_name in table_names:
      print(table_name)
  else:
    print('No table names found.')


if __name__ == '__main__':
  main()
list_trace_scope_table_names_test.py 6.4 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Unit tests for list_trace_scope_table_names.py."""

import io
import os
import sys
import unittest
from unittest import mock

import google.auth.exceptions


# pylint: disable=g-import-not-at-top
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import list_trace_scope_table_names  # pytype: disable=import-error  # pyrefly: ignore[missing-import]


class TestListTraceScopeTableNames(unittest.TestCase):

  @mock.patch("google.auth.default")
  @mock.patch("google.auth.transport.requests.Request")
  def test_get_access_token_success(self, mock_request, mock_auth_default):
    mock_credentials = mock.Mock()
    mock_credentials.token = "test-token"
    mock_auth_default.return_value = (mock_credentials, "test-project")

    token = list_trace_scope_table_names.get_access_token()

    self.assertEqual(token, "test-token")
    mock_credentials.refresh.assert_called_once()

  @mock.patch("requests.get")
  def test_list_trace_scopes_success(self, mock_get):
    mock_response = mock.Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "traceScopes": [{"resourceNames": ["projects/test-project"]}]
    }
    mock_get.return_value = mock_response

    scopes = list_trace_scope_table_names.list_trace_scopes(
        "test-project", "test-token"
    )

    self.assertEqual(scopes, [{"resourceNames": ["projects/test-project"]}])
    mock_get.assert_called_once_with(
        "https://observability.googleapis.com/v1/projects/test-project/locations/global/traceScopes",
        headers={"Authorization": "Bearer test-token"},
        timeout=10,
    )

  @mock.patch("requests.get")
  def test_list_trace_scopes_failure(self, mock_get):
    mock_response = mock.Mock()
    mock_response.status_code = 403
    mock_response.text = "Permission Denied"
    mock_get.return_value = mock_response

    with mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr:
      scopes = list_trace_scope_table_names.list_trace_scopes(
          "test-project", "test-token"
      )

    self.assertEqual(scopes, [])
    self.assertIn("Error listing trace scopes:", mock_stderr.getvalue())

  @mock.patch("requests.get")
  def test_get_bucket_location_found(self, mock_get):
    mock_response = mock.Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "buckets": [
            {
                "name": (
                    "projects/test-project/locations/us-central1/buckets/other"
                )
            },
            {"name": "projects/test-project/locations/us-west1/buckets/_Trace"},
        ]
    }
    mock_get.return_value = mock_response

    location = list_trace_scope_table_names.get_bucket_location(
        "test-project", "test-token"
    )

    self.assertEqual(location, "us-west1")
    mock_get.assert_called_once_with(
        "https://observability.googleapis.com/v1/projects/test-project/locations/-/buckets",
        headers={"Authorization": "Bearer test-token"},
        timeout=10,
    )

  @mock.patch("requests.get")
  def test_get_bucket_location_not_found(self, mock_get):
    mock_response = mock.Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "buckets": [{
            "name": "projects/test-project/locations/us-central1/buckets/other"
        }]
    }
    mock_get.return_value = mock_response

    location = list_trace_scope_table_names.get_bucket_location(
        "test-project", "test-token"
    )

    self.assertIsNone(location)

  @mock.patch("requests.get")
  def test_get_bucket_location_error(self, mock_get):
    mock_response = mock.Mock()
    mock_response.status_code = 500
    mock_response.text = "Internal Server Error"
    mock_get.return_value = mock_response

    with mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr:
      location = list_trace_scope_table_names.get_bucket_location(
          "test-project", "test-token"
      )

    self.assertIsNone(location)
    self.assertIn(
        "Error listing buckets for test-project", mock_stderr.getvalue()
    )

  @mock.patch("list_trace_scope_table_names.get_access_token")
  @mock.patch("list_trace_scope_table_names.list_trace_scopes")
  @mock.patch("list_trace_scope_table_names.get_bucket_location")
  def test_main_success(
      self, mock_get_bucket, mock_list_scopes, mock_get_token
  ):
    mock_get_token.return_value = "test-token"
    mock_list_scopes.return_value = [
        {"resourceNames": ["projects/p1", "projects/p2"]}
    ]
    mock_get_bucket.side_effect = lambda proj, token: (
        "us-central1" if proj == "p1" else None
    )

    with (
        mock.patch(
            "sys.argv",
            ["list_trace_scope_table_names.py", "--project_id", "test-project"],
        ),
        mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout,
        mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr,
    ):
      list_trace_scope_table_names.main()

    output = mock_stdout.getvalue()
    err_output = mock_stderr.getvalue()

    self.assertIn("p1.us-central1._Trace.Spans._AllSpans", output)
    self.assertIn(
        "Could not find _Trace bucket location for project p2", err_output
    )

  @mock.patch("list_trace_scope_table_names.get_access_token")
  def test_main_token_failure(self, mock_get_token):
    mock_get_token.side_effect = google.auth.exceptions.GoogleAuthError(
        "Auth failed"
    )

    with (
        mock.patch(
            "sys.argv",
            ["list_trace_scope_table_names.py", "--project_id", "test-project"],
        ),
        mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr,
        self.assertRaises(SystemExit) as cm,
    ):
      list_trace_scope_table_names.main()

    self.assertEqual(cm.exception.code, 1)
    self.assertIn(
        "Failed to get credentials: Auth failed", mock_stderr.getvalue()
    )


if __name__ == "__main__":
  unittest.main()
mock_traffic_data.py 100.4 KB
# This file contains mock traffic data embedded as Python lists.
# It is used by analyze_traffic_test.py to avoid external dependencies.

STEADY_TRAFFIC = [50.1774, 50.1621, 48.2776, 47.481, 49.2367, 51.7367, 51.6358, 52.3998, 49.9103, 53.9292, 48.3077, 50.8816, 49.5168, 52.9828, 50.0645, 47.9358, 50.4837, 47.756, 48.2555, 51.8527, 49.9594, 51.7112, 48.2527, 52.5936, 49.6494, 46.0853, 48.2086, 47.2051, 47.0724, 51.021, 50.7313, 51.1816, 48.5254, 51.0634, 47.0639, 49.0342, 49.6825, 48.8594, 50.2009, 49.9545, 50.9422, 50.607, 51.9106, 49.0395, 51.303, 50.555, 50.4862, 50.2674, 45.687, 53.835, 48.1694, 48.4071, 49.3554, 47.38, 53.4918, 48.7606, 48.6324, 48.3406, 50.8741, 52.7917, 50.5455, 48.4516, 52.6456, 50.5671, 48.5552, 49.856, 50.2627, 50.4742, 50.0032, 50.0478, 53.7256, 55.6674, 50.346, 48.1656, 47.8995, 51.6263, 46.7519, 49.6364, 50.7899, 50.3633, 49.1907, 53.6755, 51.5925, 49.0583, 51.5665, 49.6321, 48.9675, 49.1848, 52.365, 48.8819, 49.8574, 52.0401, 50.6082, 50.4808, 48.6694, 54.6617, 51.6366, 45.2629, 52.6084, 47.4279, 47.2559, 48.6041, 52.5157, 49.4552, 50.4212, 46.66, 52.151, 49.4655, 47.4214, 50.6496, 50.9797, 50.17, 52.5828, 51.1673, 53.0044, 49.8904, 50.2191, 51.7284, 52.3173, 49.3338, 53.7717, 50.2307, 50.0097, 50.8837, 48.2886, 46.708, 54.1115, 52.1285, 48.1521, 50.2742, 51.2471, 49.0241, 52.8662, 49.011, 51.9848, 48.7391, 51.0143, 53.0997, 50.9489, 49.0238, 50.4433, 51.4497, 49.1439, 49.2101, 53.524, 52.7939, 48.6735, 47.3634, 47.4332, 47.7704, 49.4321, 49.8486, 47.2325, 50.3092, 44.1936, 50.2797, 53.2156, 47.5698, 44.2406, 50.3331, 51.4013, 49.1832, 50.4575, 52.5821, 53.3787, 51.196, 47.528, 50.3388, 47.9994, 49.9689, 49.5172, 48.8581, 53.0623, 49.5447, 47.0381, 50.7591, 51.3722, 50.1021, 48.4503, 49.1352, 48.8224, 48.9906, 48.5964, 49.5579, 47.2884, 50.4935, 48.4353, 51.7542, 50.7625, 53.0115, 47.2714, 52.8224, 49.7669, 51.2378, 51.7795, 51.9224, 50.1232, 50.9091, 49.8166, 51.4553, 48.2165, 50.8091, 53.0788, 54.0129, 52.1362, 52.9227, 51.0472, 52.1076, 53.8901, 49.8915, 46.8245, 49.6594, 50.372, 48.3521, 47.6043, 49.014, 47.54, 51.8253, 53.4094, 51.3508, 47.2108, 50.4141, 48.2834, 50.5595, 48.3537, 51.9657, 51.4046, 49.3588, 51.0089, 50.1264, 53.4549, 46.1969, 50.8258, 52.486, 49.2664, 49.0018, 50.3546, 48.1605, 48.9268, 47.9516, 49.6449, 45.816, 48.7945, 51.1169, 49.2429, 49.1762, 51.7979, 53.1556, 48.5255, 52.4099, 46.499, 48.3083, 51.0716, 50.5154, 50.2382, 51.7297, 49.5946, 51.525, 49.022, 48.745, 46.2502, 51.3527, 48.2644, 52.0151, 52.0194, 49.5556, 50.1745, 50.3956, 49.5899, 47.0828, 52.8915, 48.8644, 51.0589, 50.5827, 50.5793, 50.4379, 51.8242, 48.2585, 51.9841, 50.3317, 50.0785, 49.1698, 49.9092, 51.1583, 47.6561, 46.5588, 49.4505, 51.4042, 49.4019, 52.7424, 52.5921, 52.805, 52.9046, 50.5271, 51.1339, 48.6358, 44.629, 50.8108, 48.4565, 49.5977, 45.0292, 51.7951, 49.5965, 48.8185, 47.6902, 48.3748, 48.3062, 48.0579, 47.1739, 49.5804, 49.3237, 51.7188, 46.497, 49.1084, 48.2173, 50.6818, 49.8952, 51.698, 53.6764, 50.0021, 51.06, 48.5007, 49.7463, 50.0497, 54.2777, 47.7209, 49.7319, 50.0389, 48.4913, 50.7049, 50.0283, 50.2391, 48.5556, 51.4692, 48.1391, 49.2557, 51.6947, 52.7958, 48.4995, 51.2457, 49.8293, 52.088, 50.2229, 53.3941, 53.0652, 48.0535, 49.3464, 48.499, 49.8384, 46.3655, 46.6526, 52.0396, 50.6815, 51.507, 48.1906, 47.8978, 49.6129, 52.7657, 50.1508, 50.366, 52.3556, 50.7593, 50.3639, 50.8548, 49.6186, 53.1468, 49.7913, 48.559, 51.3632, 51.8933, 49.0565, 51.448, 52.1531, 43.2966, 46.5506, 50.801, 48.1389, 53.3729, 50.6481, 49.7968, 50.1235, 49.2402, 48.7162, 50.2437, 52.0058, 46.9059, 50.4816, 49.1008, 50.1722, 48.4964, 50.2877, 47.8557, 49.9594, 49.4794, 46.6695, 50.8365, 44.3763, 49.2486, 47.0188, 50.514, 49.3279, 51.6339, 49.5958, 49.5741, 52.2412, 49.0704, 49.9406, 52.8525, 51.3238, 53.9658, 50.9181, 48.9407, 52.1481, 51.8447, 49.4538, 51.0802, 49.8352, 50.9961, 50.0652, 49.7402, 53.3775, 50.9124, 47.339, 50.4168, 49.4017, 50.626, 50.4799, 50.7325, 46.6032, 46.8642, 52.8012, 49.9467, 52.6762, 51.0552, 48.9338, 46.623, 51.0239, 51.0346, 53.5024, 49.595, 50.1523, 46.3839, 48.7863, 50.4919, 49.2984, 48.2521, 52.8355, 53.2054, 47.8637, 50.1978, 49.143, 52.9696, 50.4749, 51.1946, 48.1299, 52.655, 49.4021, 53.7258, 52.1849, 48.6981, 51.0538, 50.4868, 49.5574, 51.4997, 49.9491, 50.0563, 48.7369, 48.5112, 50.1532, 50.3574, 52.1517, 47.2909, 50.225, 53.1878, 48.6439, 47.9131, 48.1468, 51.5829, 47.4677, 50.039, 48.6616, 48.8491, 49.3874, 49.2509, 49.2649, 49.8921, 50.5379, 49.093, 50.9412, 49.0408, 49.0918, 50.0837, 46.5675, 48.3581, 48.664, 47.9544, 49.5369, 48.5335, 48.1776, 52.032, 54.1649, 51.9879, 50.5962, 52.248, 50.6284, 49.4786, 50.223, 49.3283, 45.5904, 48.3173, 48.342, 50.9672, 49.038, 46.4005, 49.9428, 50.5734, 51.5386, 50.7286, 54.7812, 48.2652, 52.6343, 51.842, 48.7292, 49.7438, 48.5077, 49.7522, 49.1139, 49.1103, 49.9895, 47.9284, 52.2491, 51.7562, 48.6094, 51.7254, 47.8972, 46.432, 50.6298, 51.0931, 48.5213, 51.0524, 53.921, 56.0248, 48.2541, 50.6533, 47.5429, 55.663, 49.1283, 51.72, 50.1889, 47.8859, 49.5863, 47.2927, 48.7201, 49.4638, 50.4499, 45.4565, 49.8688, 55.106, 48.0965, 50.6517, 49.1537, 44.3556, 48.0092, 48.633, 51.694, 49.9298, 49.5594, 51.3464, 50.2583, 49.6701, 51.3364, 47.2475, 49.5875, 52.5067, 45.7197, 48.4187, 50.3126, 50.4583, 49.3273, 50.8598, 48.2269, 51.9589, 50.3894, 53.6304, 51.6932, 51.1032, 52.8322, 48.3935, 49.4135, 46.4996, 51.741, 53.3083, 49.029, 47.5657, 52.2497, 48.5254, 48.9912, 53.079, 49.2825, 49.6271, 53.2237, 51.1818, 47.8719, 53.0106, 46.5173, 52.015, 50.9804, 48.9532, 48.4422, 47.7752, 53.458, 50.2489, 48.7388, 51.1478, 52.4092, 50.6377, 51.394, 51.908, 50.1175, 50.6332, 49.7692, 48.0153, 47.466, 50.9012, 48.5832, 49.9579, 49.5046, 51.9406, 50.5599, 50.6129, 49.427, 49.724, 49.3202, 50.4992, 46.5518, 49.9605, 50.7351, 50.7865, 47.845, 49.1578, 49.2385, 48.9201, 47.5663, 47.8271, 50.0182, 50.771, 50.296, 48.257, 50.77, 49.6024, 49.0089, 48.1494, 48.9813, 51.434, 49.6321, 49.7537, 47.9979, 55.5808, 45.4701, 45.9442, 48.9503, 50.3988, 53.5471, 51.0276, 50.6016, 51.8393, 50.1902, 46.0898, 50.5097, 50.4346, 54.3393, 48.5581, 52.5148, 47.2796, 53.0656, 50.2652, 51.674, 51.4076, 51.3556, 50.1951, 48.688, 49.6806, 48.4691, 49.7746, 46.7823, 50.3445, 51.9546, 52.4038, 52.6276, 50.305, 49.6917, 49.4895, 50.7847, 51.4342, 50.6763, 47.3092, 52.7561, 50.955, 51.9814, 50.1038, 49.478, 53.8751, 47.8603, 46.6237, 53.9916, 50.4808, 49.1433, 48.8299, 45.9878, 53.7345, 51.4113, 51.02, 51.6493, 48.1707, 50.9168, 52.1714, 45.5902, 51.1919, 51.4942, 50.203, 48.2289, 49.6689, 49.0836, 50.7257, 48.9358, 51.5288, 48.9633, 48.9603, 52.3371, 49.6785, 51.0632, 47.4052, 53.0418, 47.0957, 50.1939, 49.5509, 48.4739, 49.4512, 52.4702, 53.4779, 49.5267, 49.2851, 46.2441, 53.4302, 47.8679, 48.1802, 50.2096, 51.4681, 53.0465, 54.3492, 51.5077, 49.0397, 48.6864, 49.643, 51.6089, 51.9098, 51.2339, 46.2111, 48.8677, 52.9134, 48.9338, 49.8393, 55.4536, 49.8521, 52.8469, 53.6774, 51.5164, 49.1302, 45.4399, 48.2821, 51.2866, 51.1839, 52.3445, 47.7883, 50.3989, 45.8998, 48.2344, 51.0586, 45.6355, 51.6334, 53.6613, 47.1278, 49.4823, 53.4369, 51.0013, 50.7947, 50.215, 47.2564, 49.7263, 52.5733, 50.174, 51.4434, 49.2765, 48.2571, 49.1376, 47.8939, 47.2754, 49.9602, 49.5424, 48.1192, 51.3921, 48.1368, 50.8512, 50.9968, 53.3319, 50.6841, 51.5792, 50.1494, 47.1856, 51.7114, 53.3588, 49.7514, 54.1876, 51.8477, 54.002, 49.6376, 48.2307, 50.112, 48.5475, 50.3969, 49.5167, 50.329, 49.8199, 48.0515, 48.9412, 52.5383, 49.873, 47.3183, 45.9664, 49.3551, 50.5576, 47.6396, 46.4254, 51.1216, 56.3882, 51.744, 48.0068, 49.7647, 49.7623, 47.4564, 47.1917, 49.7145, 51.5803, 50.5058, 48.6334, 51.0188, 51.0425, 48.0346, 47.5643, 51.2904, 52.2724, 50.8108, 52.3585, 52.934, 46.9433, 50.9572, 52.6319, 52.2672, 52.8544, 48.8248, 51.3635, 51.5526, 48.8037, 50.3814, 47.3366, 48.3023, 50.6551, 52.1028, 49.9984, 53.0682, 52.9786, 48.0343, 49.7972, 48.9931, 51.6465, 51.4363, 48.4126, 51.8482, 47.3587, 52.3557, 45.1217, 49.6418, 48.5842, 51.3519, 50.5051, 45.6169, 47.3092, 48.8257, 52.3676, 53.2625, 51.364, 52.8459, 48.4938, 50.8332, 50.254, 47.8404, 49.2992, 49.2863, 50.9122, 50.9908, 48.9031, 48.9362, 46.1987, 51.0106, 49.7932, 49.942, 51.0916, 49.0093, 48.0723, 48.7959, 49.3127, 50.4353, 48.7883, 49.1185, 47.3408, 49.1848, 46.5059, 48.6785, 51.0799, 50.3428, 49.6876, 49.5509, 51.8006, 47.6431, 50.8845, 48.5671, 50.5565, 49.6958, 48.9135, 50.6246, 48.7076, 47.5741, 49.034, 47.4906, 50.2903, 48.7842, 47.4722, 50.7286, 50.8036, 49.6309, 49.4154, 51.8266, 49.4577, 50.5161, 47.73, 51.1152, 49.7141, 51.0365, 49.4538, 48.4941, 47.596, 49.5874, 49.0812, 47.4056, 52.5018, 52.0513, 45.9307, 45.722, 46.9608, 50.3131, 55.3594, 47.6363, 49.3655, 52.6658, 49.0093, 52.2318, 51.8683, 49.9416, 51.7641, 51.8718, 47.1942, 49.6508, 48.7418, 50.0593, 47.5726, 48.0071, 50.1116, 49.9854, 52.7712, 50.4208, 52.8647, 52.6207, 52.2757, 42.9303, 48.454, 50.9269, 47.3536, 48.9442, 51.3372, 50.0951, 49.3023, 53.4649, 49.1558, 52.2227, 49.9006, 50.1983, 49.2829, 48.3188, 49.5568, 47.2686, 51.2223, 50.2261, 49.1198, 51.5888, 47.9155, 46.0648, 50.8429, 47.2451, 47.2094, 50.3259, 51.9326, 48.4429, 48.2156, 53.0125, 47.175, 51.6959, 50.8597, 48.5485, 49.7272, 48.2801, 48.6678, 49.6944, 48.5862, 46.7048, 51.4247, 48.7914, 51.5932, 49.6921, 55.6256, 51.1162, 47.3073, 47.2557, 48.2072, 49.1428, 46.6948, 47.748, 50.0303, 46.8739, 49.8001, 50.466, 47.9902, 51.2079, 50.1701, 52.1867, 51.3294, 49.5747, 49.6849, 50.9236, 50.7555, 46.6144, 51.8531, 48.8781, 52.2681, 50.3583, 48.7008, 49.9996, 52.881, 48.5009, 46.5808, 49.4886, 52.5188, 53.1763, 52.0655, 45.7595, 49.5257, 49.0439, 49.6471, 47.8101, 49.4499, 47.6318, 54.6402, 50.1199, 48.965, 47.521, 51.9158, 51.167, 52.324, 50.6933, 49.063, 48.5442, 48.4713, 49.1898, 51.3706, 48.8968, 50.5685, 51.5059, 49.0919, 51.957, 50.8406, 50.7663, 49.9481, 50.3468, 48.2792, 48.3231, 50.5005, 51.7888, 49.539, 51.0043, 49.5382, 48.4344, 50.025, 50.7685, 48.6225, 48.812, 49.0097, 50.3661, 47.05, 50.5486, 50.5232, 50.4107, 48.8756, 50.5599, 47.7934, 48.4776, 51.5981, 47.3427, 48.711, 48.8445, 51.2992, 47.1198, 48.822, 47.8293, 53.3122, 49.4472, 48.9613, 50.2274, 51.728, 45.8541, 47.8381, 50.4367, 48.7404, 47.1152, 48.5821, 50.3132, 50.6514, 53.9201, 46.7216, 47.0379, 47.5844, 51.9458, 48.2081, 46.9622, 51.6247, 48.5198, 52.2306, 50.4293, 48.6763, 51.7877, 51.6318, 53.0039, 49.1727, 49.363, 52.9442, 52.2231, 50.5143, 48.3, 47.9055, 47.1379, 48.0185, 49.5865, 47.6164, 51.4413, 44.8429, 48.3975, 48.6396, 51.2174, 51.0453, 47.5385, 50.4575, 47.9112, 50.5829, 47.5604, 50.2562, 52.9371, 54.0804, 52.1734, 47.9368, 48.962, 48.1336, 48.7797, 46.5044, 48.7393, 52.2356, 54.4687, 50.8694, 50.4065, 51.346, 46.8389, 48.3085, 51.6104, 49.5339, 49.2638, 51.7084, 46.1865, 52.3345, 48.3758, 51.1267, 50.0013, 51.4569, 51.9847, 47.9761, 51.6747, 51.0129, 52.8509, 48.9438, 52.3751, 51.4573, 49.1158, 52.0023, 49.2554, 51.8264, 49.7993, 50.2162, 50.1359, 52.028, 49.8266, 51.1614, 51.1993, 48.2815, 51.848, 52.9459, 51.0216, 50.8115, 48.2964, 52.5786, 46.9323, 50.2883, 53.0997, 48.622, 51.0791, 48.5474, 51.317, 47.1699, 49.1755, 48.7244, 50.2031, 46.5976, 53.0151, 50.6201, 49.0223, 52.978, 49.9524, 50.513, 50.5766, 53.1816, 50.315, 47.8646, 50.1788, 50.8397, 49.9483, 48.7007, 48.3836, 46.6061, 50.9623, 48.331, 48.715, 51.019, 52.1584, 47.9288, 49.2974, 49.2121, 51.0117, 47.92, 48.3955, 50.8401, 48.7935, 47.9428, 49.9777, 48.1673, 49.453, 52.5676, 49.6466, 49.7258, 49.0589, 46.9575, 50.3546, 52.0338, 52.5252, 55.7068, 49.4091, 50.4035, 47.8, 53.704, 51.9831, 51.9215, 51.1933, 49.7346, 44.9243, 52.5001, 51.3355, 50.5153, 48.3471, 51.735, 50.5974, 50.4011, 47.7862, 47.756, 49.8211, 49.7877, 47.9199, 53.4692, 49.1228, 49.8692, 50.5202, 52.9443, 48.4497, 49.6286, 47.451, 52.0977, 50.8523, 50.317, 50.5688, 53.6319, 49.7799, 48.8322, 48.8422, 52.0619, 51.1763, 50.9604, 48.7031, 51.093, 51.2018, 50.2121, 49.7365, 50.947, 50.7991, 49.0402, 49.3758, 46.5696, 51.1949, 49.7805, 53.0991, 46.4313, 50.3392, 51.186, 48.6028, 50.966, 50.5664, 51.059, 49.5333, 43.6465, 50.1618, 50.1882, 48.5376, 47.3494, 51.0459, 50.7929, 53.1585, 48.387, 52.371, 50.0342, 49.0074, 50.9984, 51.753, 48.9496, 53.1408, 50.0376, 47.5339, 47.7227, 52.1439, 48.8941, 50.1781, 50.2119, 49.7751, 51.9587, 49.0362, 47.7806, 45.3972, 49.763, 49.4719, 52.4765, 48.5918, 52.0464, 49.4219, 53.4414, 48.0526, 49.1977, 51.3573, 52.3769, 51.6879, 47.3298, 52.1766, 49.9814, 46.7438, 48.8824, 49.3032, 48.4016, 52.6118, 51.0738, 52.2788, 48.2396, 46.6599, 50.9043, 50.0681, 51.7265, 51.3203, 50.3118, 51.6024, 50.1533, 50.4103, 53.9569, 52.5794, 47.8961, 46.8361, 52.7146, 49.1272, 49.7367, 49.0237, 50.6542, 49.1722, 47.6193, 46.43, 45.2162, 47.8916, 52.4494, 48.1246, 49.953, 52.243, 52.6278, 48.886, 51.4226, 49.249, 46.1232, 51.9149, 50.2203, 48.2459, 50.412, 50.6673, 50.333, 48.0636, 49.6506, 50.6111, 51.5076, 49.5682, 47.8336, 50.8487, 52.4739, 48.8089, 51.0117, 52.0965, 52.1167, 52.6893, 50.5667, 52.8154, 52.7046, 48.3452, 50.6201, 50.4704, 48.6309, 49.3416, 45.984, 51.4207, 51.6978, 52.3018, 52.6974, 48.7901, 49.68, 53.0872, 52.1593, 48.5249, 45.2792, 49.5423, 47.863, 50.1253, 51.9418, 47.1057, 50.5496, 47.5685, 54.9648, 50.1032, 50.9503, 47.9119, 45.7345, 48.0823, 48.0865, 52.3452, 47.7049, 51.654, 50.843, 49.7769, 45.0271, 48.9007, 51.9415, 51.0746, 50.2992, 47.1262, 50.2521, 50.5074, 49.0278, 50.8663, 48.5794, 45.9845, 48.7135, 48.6194, 52.438, 51.439, 49.8989, 48.9065, 51.1165, 52.9883, 48.0659, 48.7218, 52.3015, 50.9617, 49.1231, 52.3105, 51.1032, 48.1144, 50.5493, 49.9856, 53.3053, 51.2148, 50.967, 50.2666, 51.0419, 47.2217, 47.0912, 50.7787, 50.7994, 49.193, 46.0038, 47.8244, 51.0756, 50.2538, 48.7173, 48.142, 50.533, 49.6983, 49.6813, 48.9913, 50.3005, 50.5654, 48.7473, 53.3254, 48.8224, 50.3326, 46.8969, 48.0021, 51.8409, 51.4528, 50.4293, 48.6549, 50.7073, 48.0141, 52.1401, 44.7421, 49.23, 48.4055, 52.5897, 49.604, 52.4748, 52.8913, 50.9095, 46.724, 48.4923, 49.0017, 50.801, 50.7593, 47.3408, 51.5692, 47.9706, 49.2922, 50.5148, 49.7404, 53.1377, 52.2787, 47.3619, 47.7486, 52.2996, 50.2266, 51.2567, 50.0502, 52.4611, 51.5433, 51.5729, 48.6466, 51.2149, 46.7796, 49.5185, 48.7291, 48.4466, 48.1264, 45.9848, 52.4768, 49.5744, 49.6455, 51.0025, 52.1304, 52.6737, 49.1368, 50.376, 48.1893, 51.4656, 50.0421, 51.8182, 51.6546, 51.5634, 51.0723, 50.1741, 47.5146, 50.6581, 53.3669, 49.1322, 48.6453, 51.2361, 53.3486, 47.9179, 45.1683, 48.7703, 50.1994, 49.7144, 49.4794, 48.9947, 48.7063, 48.3456, 50.72, 51.145, 46.8293, 53.1638, 50.883, 51.1079, 49.4343, 50.5096, 47.7528, 53.1668, 52.8298, 49.5209, 47.3625, 49.3883, 51.1826, 49.2124, 48.4087, 50.3217, 48.2524, 52.6705, 51.891, 51.3276, 48.5842, 50.4137, 52.2188, 45.8138, 50.4114, 52.8124, 53.623, 48.0989, 50.5524, 52.0886, 52.4117, 46.3207, 45.9808, 50.3086, 50.9966, 49.7509, 49.3443, 52.5561, 52.955, 48.8156, 50.3154, 47.6862, 53.471, 47.1915, 47.8598, 48.2204, 47.903, 52.5551, 54.6433, 50.5214, 49.3279, 51.4435, 48.186, 52.6755, 49.9271, 50.8411, 48.6175, 49.5912, 46.7608, 50.0374, 51.7805, 46.2969, 47.9803, 49.0477, 49.3807, 49.8195, 49.9099, 50.5675, 49.929, 46.6362, 50.6274, 52.4068, 50.5161, 46.4531, 50.4646, 50.9507, 48.0215, 50.1524, 52.5529, 53.2348, 50.253, 51.0149, 49.6698, 49.1803, 52.77, 51.9249, 51.234, 48.9469, 52.9345, 52.0809, 47.4166, 52.1772, 50.3366, 50.557, 45.9659, 47.0737, 51.979, 48.466, 51.6249, 47.3457, 47.0495, 53.8215, 51.8188, 49.7433, 50.4474, 48.5828, 50.712, 52.3589, 49.1691, 50.9713, 46.6156, 53.6031, 52.0092, 49.94, 49.3311, 52.822, 48.9905, 50.7395, 49.3722, 48.1545, 52.0777, 49.1756, 50.9284, 49.3054, 49.7311, 49.6579, 48.6903, 51.4666, 49.8264, 51.7255, 51.4936, 52.4446, 49.017, 51.3274, 49.6512, 49.9552, 48.5711, 49.0511, 51.2603, 49.316, 48.5411, 51.6966, 50.7136, 47.563, 50.2114, 52.2564, 52.1924, 48.9257, 47.7786, 49.2689, 52.6882, 51.4875, 45.4126, 51.7175, 45.5643, 53.8651, 51.6907, 49.2108, 50.2139, 51.322, 49.0132, 50.9271, 49.7409, 49.4984, 53.05, 45.9225, 50.0941, 47.2138, 49.6358, 48.5838, 55.0926, 48.9716, 49.726, 48.7632, 51.7788, 48.9797, 48.69, 53.7408, 51.5619, 50.5379, 54.8248, 48.734, 48.3748, 48.413, 52.4063, 48.7624, 52.3805, 48.7412, 46.3707, 48.3968, 50.5743, 52.3846, 52.6027, 50.7328, 51.3682, 44.7111, 50.5253, 50.0771, 49.3821, 48.6682, 51.7595, 52.2785, 53.9292, 49.6105, 48.4079, 53.7705, 49.3592, 48.9588, 47.2256, 50.8402, 51.2114, 51.6872, 50.4462, 51.0882, 51.1086, 51.0288, 52.3569, 51.7049, 50.3776, 48.9255, 51.6059, 48.8457, 49.7047, 48.5676, 54.2659, 48.0577, 51.3278, 51.3526, 51.7524, 49.9208, 50.1678, 49.6064, 44.5639, 48.4715, 52.7281, 48.3675, 50.27, 55.2752, 48.0637, 48.9907, 49.4959, 46.0031, 48.2635, 47.1427, 51.0878, 49.5058, 45.735, 51.6203, 51.9442, 49.2766, 51.8934, 51.1747, 48.1713, 50.5625, 50.3694, 48.3297, 47.9467, 50.8158, 54.6134, 49.9254, 50.4206, 47.8911, 49.4809, 49.5953, 49.2465, 48.6884, 49.9027, 48.8741, 52.4829, 54.0998, 48.4773, 49.2728, 50.8672, 51.1662, 48.473, 48.8583, 51.1732, 46.7233, 54.4301, 50.6029, 49.3918, 49.6993, 47.8532, 53.605, 49.8322, 49.1298, 53.514, 52.0639, 49.6111, 50.8725, 49.3357, 49.2756, 49.5581, 50.5949, 52.1898, 53.9551, 45.6548, 54.6447, 52.0487, 50.0331, 49.1399, 46.2638, 52.3888, 47.8108, 51.3037, 49.1705, 46.7485, 50.8368, 50.9727, 48.1284, 51.7188, 53.6108, 50.9813, 50.8628, 48.5324, 47.9213, 49.1878, 50.138, 50.0235, 49.6022, 54.9835, 51.1423, 48.0474, 47.5988, 46.5229, 47.9809, 51.1574, 49.4295, 48.6143, 51.1793, 51.0984, 50.7428, 49.9735, 49.9265, 47.3628, 46.3096, 48.3872, 48.4226, 48.3621, 49.6536, 49.0519, 47.3908, 49.7942, 50.672, 49.0149, 51.6381, 50.6309, 50.7789, 49.2529, 50.8269, 51.365, 46.1415, 52.1366, 48.9777, 51.3012, 45.3873, 49.1317, 46.602, 49.7032, 50.3629, 50.8139, 50.0414, 47.4949, 52.6055, 47.3095, 49.3274, 48.4465, 48.7949, 47.1938, 52.1712, 51.4922, 50.1433, 49.7113, 48.0801, 49.7798, 48.1839, 50.1728, 50.7875, 49.5057, 50.798, 51.1672, 51.6093, 53.9495, 47.1446, 47.5323, 47.567, 49.6044, 46.8111, 48.9391, 51.6762, 51.4585, 53.2791, 51.7073, 52.026, 48.9421, 49.2839, 51.7577, 51.7172, 46.1673, 47.2228, 48.0443, 48.2801, 52.6347, 53.6118, 50.6599, 50.6814, 53.8839, 50.8974, 51.1181, 50.7454, 50.7486, 52.6982, 51.4527, 50.1707, 49.2137, 50.5201, 46.6746, 50.9215, 50.2522, 50.6416, 47.6865, 50.9374, 50.3662, 49.986, 50.7404, 48.3407, 47.0873, 50.9082, 45.5965, 51.1901, 54.1351, 50.7416, 51.7074, 53.2554, 52.0884, 54.554, 48.2577, 49.3176, 50.9667, 46.7702, 49.9871, 50.1335, 52.5958, 52.1345, 51.5325, 51.3935, 50.1228, 50.5844, 51.5189, 52.0234, 48.5619, 50.8992, 49.8493, 50.5311, 52.3088, 49.4987, 48.156, 48.178, 48.8537, 51.219, 49.6686, 48.8039, 51.5455, 50.3199, 51.4011, 54.386, 53.7625, 50.6897, 50.6778, 52.2273, 52.5558, 49.2837, 47.5499, 51.7259, 50.4502, 51.2204, 51.0858, 48.6031, 48.9799, 52.1426, 49.6769, 48.4369, 49.4493, 50.7953, 48.9796, 53.4748, 51.6247, 47.0196, 50.4591, 53.1379, 56.5926, 49.0584, 50.0495, 47.2873, 51.1125, 50.9577, 50.5664, 47.8315, 51.5625, 53.6563, 52.7174, 50.7245, 49.8985, 51.7966, 49.7178, 44.9419, 46.5643, 52.7364, 52.6606, 49.7492, 48.4035, 49.3994, 47.4278, 49.4921, 53.494, 48.7488, 48.4112, 47.3121, 50.4114, 48.1002, 51.3008, 49.3828, 53.3626, 51.1826, 50.954, 47.1864, 50.0482, 50.6076, 50.6857, 50.7108, 50.2451, 47.6646, 45.1864, 47.7677, 52.0279, 51.6007, 52.2847, 50.6562, 50.4541, 50.0346, 46.5835, 50.3563, 48.7048, 48.7818, 48.0235, 49.8656, 51.8303, 51.5995, 48.0584, 50.4845, 49.8512, 45.9776, 51.8803, 48.7061, 51.1607, 48.4177, 51.5559, 52.4968, 50.523, 51.0863, 48.693, 49.366, 47.7621, 52.1054, 52.3727, 49.0403, 50.0758, 48.6665, 47.3819, 48.9705, 47.6056, 46.119, 50.5919, 48.0086, 49.9163, 44.6843, 50.1774, 48.6158, 48.7493, 51.741, 49.7554, 50.5983, 50.1069, 50.9624, 48.4169, 49.9767, 49.5335, 51.4178, 48.8471, 51.5066, 51.0568, 48.8379, 51.4531, 49.2016, 48.7199, 48.3987, 47.851, 50.6225, 49.6071, 49.3861, 51.7082, 51.7633, 50.2195, 46.1293, 50.9703, 46.0824, 48.2148, 49.6783, 53.0694, 45.0365, 46.9373, 48.5692, 51.3824, 46.7358, 48.3999, 52.4256, 51.7636, 48.7842, 52.0276, 50.1703, 48.1863, 48.573, 48.7447, 47.8426, 50.9177, 52.0199, 47.1195, 51.3327, 47.911, 49.8548, 50.6071, 52.0277, 49.9519, 50.4975, 53.2586, 53.2305, 52.1063, 51.501, 51.0164, 53.2785, 51.4746, 48.6443, 50.2124, 50.8216, 47.2146, 48.8442, 53.4215, 47.7259, 51.0197, 50.6261, 51.9301, 48.4457, 48.4464, 50.1065, 48.7422, 53.0966, 50.3636, 51.7061, 48.0077, 51.1804, 54.9792, 49.8902, 47.7581, 52.2773, 49.0511, 47.4231, 47.7447, 47.6363, 51.0454, 48.3001, 48.2621, 49.256, 50.8517, 51.7803, 52.4657, 49.3357, 52.0326, 48.4252, 53.4214, 51.2403, 50.5314, 46.8236, 51.9482, 49.0643, 48.7773, 48.3582, 48.7877, 50.9872, 50.8545, 50.1039, 53.7464, 47.5025, 50.5721, 47.3433, 51.1273, 51.1467, 50.2715, 51.0122, 51.1692, 50.9679, 47.2319, 51.7549, 53.4976, 52.2474, 49.4796, 53.932, 50.4944, 52.3447, 51.3655, 52.8856, 46.8156, 48.4145, 51.0485, 49.5219, 49.2729, 53.0077, 48.8778, 50.6185, 50.7531, 49.5473, 45.3727, 46.277, 49.4831, 54.4022, 48.5597, 49.9528, 54.1557, 50.0765, 51.0186, 50.6233, 48.3247, 48.2842, 48.9951, 49.985, 48.5328, 49.0121, 50.5201, 52.3991, 54.7198, 48.5773, 50.5687, 48.0353, 48.7621, 46.5595, 53.4533, 49.148, 51.9194, 47.8909, 45.3101, 53.4165, 46.7687, 47.9325, 52.4055, 50.179, 49.628, 52.6699, 49.4349, 51.6019, 47.5267, 52.8547, 48.8873, 50.3574, 48.5632, 48.3731, 49.4404, 51.8347, 49.5102, 50.389, 49.0566, 52.6478, 47.07, 46.6469, 52.8287, 45.6774, 53.4419, 49.9698, 50.8694, 50.6465, 48.6847, 51.0357, 54.0747, 52.44, 48.5753, 52.4797, 47.6557, 49.5633, 50.2916, 52.4874, 47.2297, 52.1014, 49.1756, 46.723, 51.9951, 49.1672, 45.9931, 51.5935, 46.627, 49.2441, 47.747, 48.3785, 52.1779, 51.2699, 46.984, 49.5491, 50.1363, 52.7129, 50.9212, 47.58, 47.4178, 51.3279, 51.5272, 48.7985, 48.7477, 51.0192, 50.5791, 44.7399, 49.4572, 51.6469, 47.0317, 51.7414, 47.5043, 50.4645, 48.3081, 46.7698, 50.4418, 49.7955, 53.0434, 51.6632, 46.8235, 50.656, 51.9626, 51.6972, 53.7208, 53.9064, 48.5869, 50.7765, 54.8027, 52.5563, 48.6591, 46.9504, 46.8874, 51.3121, 49.7848, 49.6334, 48.8406, 48.2793, 51.2332, 49.9449, 50.8621, 46.7255, 53.5796, 52.3576, 52.1412, 45.8729, 51.7811, 47.1328, 50.8583, 52.3256, 52.1433, 51.4525, 53.7055, 50.3304, 48.3851, 48.9443, 50.0387, 51.6775, 47.8745, 51.6305, 49.9509, 49.0804, 48.1321, 49.0571, 50.6107, 49.6106, 51.5089, 46.7768, 47.0605, 47.9261, 52.2185, 49.7218, 50.0749, 51.1837, 51.3125, 48.9321, 47.1455, 49.283, 46.9428, 49.8658, 48.467, 50.5749, 50.3922, 49.2721, 51.2695, 55.6737, 46.31, 54.8534, 48.0544, 47.2911, 48.0775, 51.4678, 50.4315, 48.76, 48.8405, 48.4808, 51.1831, 52.5098, 49.4894, 48.6413, 49.2476, 45.3848, 49.8913, 50.7658, 49.2616, 48.9906, 52.2424, 50.6268, 50.7753, 51.0062, 50.2866, 52.6272, 47.2609, 49.9375, 45.4337, 49.1591, 54.0067, 47.4308, 47.7936, 49.8504, 51.7266, 51.3603, 48.9126, 53.3951, 49.884, 52.2769, 53.1869, 48.0339, 47.0102, 51.0717, 50.3724, 50.0682, 50.5362, 49.7991, 53.1228, 43.9787, 52.5417, 50.5179, 49.7451, 48.0502, 52.4647, 47.679, 50.2165, 52.2751, 46.69, 50.6322, 50.6216, 50.8536, 49.0698, 51.1711, 52.0772, 49.3992, 54.1668, 47.7272, 48.6428, 52.4052, 49.5666, 48.1262, 49.1069, 53.0292, 51.5877, 48.1473, 46.2535, 52.9845, 50.4912, 49.1547, 48.1848, 45.8552, 47.3573, 50.6006, 49.0126, 53.291, 51.838, 48.8156, 48.1455, 52.5804, 49.2539, 55.2872, 50.1929, 47.27, 45.9186, 48.529, 52.8908, 49.5058, 44.9997, 48.7498, 49.4198, 52.7397, 50.8652, 49.7, 50.6059, 54.4485, 52.1181, 48.5171, 51.3684, 52.2639, 54.6589, 50.5738, 49.3534, 50.7153, 49.0454, 50.3018, 48.39, 50.0468, 47.0863, 51.6879, 51.5971, 46.6984, 51.4943, 48.8792, 52.8256, 52.0087, 52.174, 51.1822, 47.9137, 45.8457, 50.2712, 47.4545, 50.3796, 47.0235, 51.5624, 51.0317, 47.4411, 48.0706, 50.8478, 51.7703, 50.4597, 48.6121, 50.3238, 49.5472, 48.9309, 47.1826, 50.0828, 48.3622, 49.744, 45.9724, 51.6726, 48.8767, 50.1591, 53.0002, 53.1073, 51.3239, 47.9578, 49.8237, 50.6001, 50.5387, 50.281, 51.6408, 51.3167, 52.4379, 51.6453, 48.6104, 49.3623, 49.9748, 50.8257, 49.0165, 49.9787, 49.3364, 48.931, 50.8257, 51.8198, 53.5448, 52.0453, 49.2153, 52.5422, 47.1391, 50.8312, 48.8818, 48.8984, 53.9621, 49.1592, 50.492, 51.1813, 49.9492, 47.278, 50.6562, 49.3153, 49.7884, 49.9536, 50.9123, 50.8216, 46.9631, 50.4396, 53.5282, 46.1847, 48.1475, 48.6202, 46.028, 46.3399, 48.0812, 52.2979, 49.2653, 48.1344, 49.6641, 50.9779, 50.9707, 50.0848, 55.2832, 50.5291, 50.867, 48.9387, 48.277, 47.6711, 47.42, 51.1013, 50.3238, 48.7391, 49.2981, 52.1184, 49.5855, 50.0683, 50.5786, 50.9941, 48.4875, 45.0728, 46.0989, 50.7064, 48.8466, 49.3157, 46.5656, 48.3989, 50.2387, 50.0791, 47.8424, 47.6905, 53.8541, 49.5005, 49.7817, 47.3167, 48.4377, 49.4452, 47.6993, 50.1811, 47.6876, 48.5112, 48.4035, 46.6798, 46.8434, 50.2404, 47.9389, 49.6295, 49.7087, 50.6634, 51.6249, 48.7045, 47.6956, 50.3897, 51.7116, 49.3094, 49.8672, 49.612, 49.6909, 51.2696, 49.1917, 51.2081, 50.8287, 54.3005, 48.5573, 52.3002, 51.6057, 47.5544, 51.1321, 51.2233, 48.7818, 45.0778, 51.4913, 47.4075, 49.6552, 46.4508, 51.1868, 46.3282, 48.8251, 48.8708, 49.9861, 47.0338, 50.9188, 50.9674, 49.2738, 49.4312, 44.494, 53.2105, 49.5465, 51.294, 50.366, 50.1115, 51.3776, 48.7211, 52.0383, 53.1504, 50.4018, 49.6861, 51.9551, 50.8266, 49.25, 49.317, 50.2503, 51.524, 48.9928, 51.58, 53.9251, 51.1853, 49.8744, 51.1382, 49.1157, 47.761, 48.4827, 47.261, 51.9225, 49.0452, 46.299, 51.0216, 50.7256, 50.6074, 47.3176, 47.7647, 53.5239, 48.7906, 50.9114, 50.2461, 47.2285, 47.0514, 50.9909, 49.3797, 49.4353, 52.0836, 46.7541, 49.8797, 52.3428, 51.6863, 49.448, 50.9387, 51.2488, 48.2489, 47.0446, 51.7291, 50.1071, 53.6385, 48.7125, 51.9921, 51.6603, 50.9852, 50.0576, 48.1092, 49.4162, 49.0129, 50.0461, 47.9073, 50.4917, 53.5644, 48.2441, 51.0623, 46.2184, 51.0026, 50.5243, 48.1786, 51.1024, 50.2086, 53.6164, 50.2264, 50.7896, 49.7081, 47.7558, 55.2037, 50.3652, 50.6116, 50.1696, 47.0664, 47.2799, 46.6496, 52.642, 51.0042, 49.3295, 47.1383, 48.3382, 49.7924, 47.5323, 51.7458, 48.3919, 49.4369, 49.799, 45.6233, 51.6184, 50.0804, 45.5683, 49.2182, 49.3319, 47.9309, 50.6977, 52.4089, 50.6933, 47.1778, 48.6446, 46.0435, 50.4012, 48.0035, 50.5509, 51.6023, 51.7564, 50.4155, 49.4884, 46.7571, 54.3625, 54.418, 49.8132, 50.8628, 47.6996, 49.2239, 50.0523, 48.82, 53.5147, 50.6223, 48.7576, 49.1839, 50.487, 46.8165, 50.9643, 49.9208, 51.7969, 50.7108, 48.6935, 48.6604, 52.7723, 50.8573, 51.1914, 51.1877, 49.8188, 47.8101, 53.5978, 49.6131, 52.5765, 49.8216, 52.2145, 48.2675, 47.3676, 49.4412, 49.0352, 51.322, 50.687, 46.9071, 48.5173, 47.2026, 48.5028, 49.814, 48.7582, 52.3331, 50.8368, 48.3012, 52.575, 51.8215, 50.3913, 49.2714, 53.8735, 51.5957, 47.85, 50.3232, 48.3344, 51.7895, 47.9429, 48.7262, 48.7648, 50.9608, 47.9012, 50.0155, 45.6987, 51.7005, 44.6286, 50.3535, 50.4995, 49.0012, 52.1988, 52.2583, 52.1466, 52.2683, 50.6548, 49.2408, 50.5268, 52.2028, 49.8943, 45.1981, 46.6432, 53.6048, 48.3537, 48.7784, 51.889, 51.7934, 51.1171, 50.2889, 45.7557, 54.4371, 49.2422, 52.1792, 50.2835, 48.9294, 49.4659, 49.6628, 53.3018, 47.4139, 50.7936, 53.6124, 48.9808, 50.0719, 47.6513, 53.2911, 47.7328, 51.2918, 46.0668, 48.2755, 50.4445, 47.7727, 49.4893, 47.3196, 50.1779, 47.6357, 47.8788, 50.5313, 46.1912, 51.2621, 48.3671, 53.194, 48.9493, 48.2359, 50.2161, 51.9947, 45.1287, 48.7168, 52.5153, 47.9203, 47.5608, 46.8177, 49.3079, 47.488, 50.8967, 46.9954, 49.0465, 49.6152, 48.7823, 49.5236, 48.0733, 48.22, 52.4572, 50.8477, 50.8449, 52.1104, 50.8073, 49.3888, 51.1591, 49.5086, 53.4911, 50.4182, 50.0926, 53.1264, 51.6498, 48.5938, 50.9567, 47.4401, 49.5051, 50.3511, 50.2807, 49.6691, 48.0892, 50.7983, 51.1111, 48.6509, 49.9555, 50.986, 50.9848, 50.7092, 50.9491, 51.2084, 51.4477, 50.914, 48.9832, 50.67, 48.6653, 48.8311, 50.6844, 50.118, 48.6469, 51.1202, 48.4884, 50.9221, 47.3391, 52.6438, 50.9753, 50.9271, 50.0356, 47.344, 46.6615, 50.1474, 49.258, 50.6538, 52.076, 50.8315, 48.0799, 51.2686, 48.7802, 50.8013, 51.1956, 48.9613, 52.9203, 49.3178, 50.0589, 52.5434, 50.3741, 48.3368, 49.3023, 50.463, 49.113, 48.9836, 51.8943, 49.6128, 53.4761, 49.6782, 47.9582, 49.5093, 51.8623, 48.8425, 52.2357, 50.0141, 50.7905, 48.5486, 50.0649, 49.9885, 52.0972, 49.069, 46.8752, 47.793, 48.6421, 51.2727, 48.2108, 48.041, 49.391, 49.9604, 49.8252, 47.4322, 49.3724, 51.9054, 50.7855, 50.7657, 48.4816, 49.4374, 47.5009, 51.1386, 51.6885, 49.5371, 49.2419, 48.3322, 49.7616, 53.3347, 48.5631, 50.4399, 51.8182, 49.8053, 47.3802, 50.6762, 53.0535, 50.3056, 49.9224, 49.8981, 45.7413, 50.6326, 49.0361, 48.1738, 52.4667, 48.0933, 50.1945, 47.5217, 50.6723, 47.1847, 50.4432, 50.2347, 51.472, 47.4035, 49.1241, 48.352, 51.4409, 46.5386, 49.2162, 50.9725, 50.3482, 46.9289, 52.2261, 50.118, 51.9972, 49.1543, 50.0712, 50.3934, 49.1232, 54.4247, 49.4556, 50.6767, 48.7139, 48.8883, 49.7065, 48.5685, 48.102, 50.0739, 49.1675, 54.254, 49.6341, 48.6799, 51.233, 53.4997, 46.7914, 52.4539, 47.8821, 49.0179, 47.217, 49.0611, 47.2254, 48.7847, 49.3254, 49.7074, 50.508, 50.5292, 49.843, 52.5933, 50.3359, 52.4105, 50.2627, 48.7213, 47.2843, 44.414, 49.1347, 47.6888, 49.953, 52.5628, 45.4812, 51.346, 46.9703, 46.2921, 54.4781, 51.5132, 44.0535, 52.6828, 49.5457, 52.9855, 48.1472, 50.3948, 50.2351, 45.857, 50.257, 51.5934, 48.0865, 51.051, 51.3151, 50.0426, 52.2683, 51.2808, 53.2294, 50.5192, 52.0803, 49.7119, 51.3541, 50.6839, 50.8833, 51.4825, 49.3661, 49.3581, 46.3949, 50.4562, 47.6549, 48.4589, 49.2328, 51.3104, 51.1498, 50.9253, 49.6386, 50.5632, 48.2172, 53.0765, 53.243, 48.7989, 47.5157, 47.6798, 48.144, 48.1359, 50.6079, 50.3623, 51.696, 50.3606, 50.4224, 49.4005, 53.1207, 53.2217, 48.4174, 50.6046, 49.4822, 49.4744, 48.8746, 47.7005, 49.4541, 51.8828, 52.7524, 51.8916, 50.2866, 52.6907, 49.8431, 49.7537, 47.3445, 52.3733, 52.0253, 48.0967, 47.4854, 53.9835, 50.452, 47.8464, 49.383, 51.1531, 52.149, 51.6175, 53.2171, 51.4537, 50.9054, 52.4478, 48.9994, 48.8305, 47.1756, 51.5296, 48.5966, 50.509, 50.2057, 49.3241, 49.1914, 51.9813, 53.2447, 49.1613, 48.4392, 53.8577, 50.1802, 48.8849, 49.3395, 51.7097, 49.827, 50.187, 47.4213, 48.4433, 52.2264, 50.8384, 52.0178, 46.5966, 48.8362, 50.6203, 51.3419, 54.163, 50.4018, 48.2163, 48.4795, 47.3201, 52.6891, 49.6932, 48.7171, 52.2943, 52.6933, 49.3635, 48.9618, 50.5819, 46.6154, 50.9994, 51.3585, 50.3688, 51.4205, 50.033, 50.3458, 52.7756, 50.2246, 53.2498, 51.7159, 49.4732, 49.9156, 48.6467, 52.4338, 55.5517, 49.4904, 50.5942, 50.9719, 50.1855, 49.6683, 51.2726, 47.0755, 48.2534, 50.4724, 50.1337, 50.3984, 51.1713, 52.3949, 47.8988, 48.6397, 52.149, 50.181, 50.3756, 52.4221, 46.3319, 52.9825, 50.3957, 47.4507, 52.4266, 53.5962, 53.0121, 49.4973, 51.3944, 51.074, 47.2617, 55.1253, 48.0139, 54.1316, 49.9402, 50.531, 49.4911, 52.7968, 53.5792, 50.3632, 48.7468, 48.6034, 51.3416, 45.547, 46.784, 50.0211, 50.6148, 49.0342, 49.1374, 46.5561, 49.2196, 49.6897, 50.5844, 51.1482, 46.1037, 53.1298, 45.7766, 51.0327, 49.0991, 51.9672, 51.1042, 49.6212, 49.373, 46.6684, 49.8195, 48.5384, 48.114, 47.7656, 50.0198, 49.156, 51.7416, 48.9164, 47.019, 48.4199, 50.0517, 46.337, 52.6282, 49.5281, 49.725, 50.2564, 51.3227, 51.3105, 48.4786, 48.5556, 53.9343, 45.7802, 47.9698, 48.2215, 51.7986, 50.5568, 50.6262, 48.2504, 50.636, 48.0665, 48.8735, 48.4738, 48.5463, 47.9914, 50.4153, 50.5865, 48.3549, 49.07, 50.8476, 50.2928, 52.8649, 49.4749, 50.6422, 51.3181, 47.9962, 47.8245, 47.2438, 50.8153, 49.5949, 50.5036, 50.2422, 50.4066, 51.2595, 49.1889, 51.4922, 51.2148, 47.2199, 49.5211, 53.091, 57.1777, 49.9096, 50.0491, 46.7184, 50.2232, 49.863, 48.8628, 53.5396, 50.4204, 48.0098, 47.8143, 51.4703, 48.7331, 48.128, 46.6261, 49.7313, 51.1907, 51.6234, 50.4805, 53.2912, 47.6222, 50.3852, 50.7546, 46.7185, 49.6176, 47.8082, 50.4512, 48.3265, 51.3055, 53.1714, 49.5593, 48.701, 47.568, 50.7907, 48.1471, 51.8599, 53.3168, 53.4592, 53.6406, 50.2217, 50.9209, 48.4271, 47.3411, 51.4803, 47.1475, 51.9816, 48.2725, 49.5841, 53.4713, 50.5105, 51.0199, 49.4571, 51.712, 49.4749, 48.137, 48.0201, 46.8704, 47.4818, 51.3413, 49.832, 48.088, 51.5689, 50.3624, 50.8881, 48.0137, 49.0727, 50.6983, 49.4565, 52.0119, 51.5467, 52.995, 50.6116, 48.7175, 50.0919, 54.6537, 52.1717, 49.6928, 51.4241, 49.5901, 49.3579, 52.2623, 50.8541, 51.8696, 53.4952, 49.0096, 50.621, 51.9035, 51.5898, 49.2521, 50.1028, 53.8492, 48.8842, 50.9295, 50.989, 47.1357, 51.2998, 47.3129, 50.4294, 52.4694, 49.0071, 46.9611, 49.9527, 49.9611, 50.2414, 50.454, 50.5681, 47.0727, 52.1483, 45.6657, 49.2896, 51.6117, 48.472, 47.0969, 48.4947, 49.0263, 54.0101, 47.0114, 50.8417, 49.5989, 48.368, 47.2363, 47.6237, 50.6863, 51.3495, 52.63, 48.0883, 45.756, 51.1516, 51.0532, 52.37, 46.2127, 52.9934, 50.2617, 54.0357, 49.5813, 52.7816, 48.841, 54.3012, 48.9732, 46.9671, 50.4766, 52.2835, 52.5345, 49.8787, 50.7978, 49.9765, 52.6926, 52.0947, 48.9933, 51.945, 49.9587, 52.3751, 49.2421, 50.1836, 48.8622, 46.8715, 47.5701, 52.2489, 51.24, 48.4173, 50.9849, 50.0665, 51.5444, 49.1144, 49.9808, 47.6968, 52.2937, 51.0484, 50.237, 54.8901, 52.358, 52.8596, 50.6656, 48.9737, 50.9147, 50.1043, 49.3226, 52.3793, 49.3779, 50.509, 50.2566, 47.0026, 51.0732, 51.5475, 50.1101, 50.518, 49.3666, 48.7561, 48.75, 46.4049, 51.0791, 47.3483, 49.1067, 45.8302, 48.6726, 51.0895, 50.183, 50.0626, 50.4792, 46.6195, 51.7473, 49.1619, 50.063, 50.8733, 44.6904, 52.8463, 49.32, 51.1157, 49.3117, 48.7672, 52.6381, 47.593, 50.5872, 48.9391, 51.0323, 51.798, 51.3882, 51.1148, 48.8007, 49.5072, 50.665, 52.4082, 50.9411, 49.62, 50.4238, 51.8298, 50.9366, 51.7994, 49.1971, 51.8163, 49.2855, 50.1893, 51.1523, 47.3411, 49.4923, 50.5476, 50.3325, 51.6614, 45.3539, 46.6746, 51.9889, 51.48, 53.8921, 49.7682, 52.3949, 54.4525, 45.4291, 46.6849, 49.0037, 47.1591, 53.0304, 49.4685, 48.5995, 52.4717, 51.3049, 48.8344, 51.3667, 48.1571, 48.6041, 52.3568, 48.3103, 49.0002, 49.0769, 48.8757, 44.9091, 46.8817, 50.302, 52.7519, 51.37, 48.9616, 49.7447, 46.6443, 49.4868, 49.5194, 48.8172, 51.1899, 50.7834, 51.1024, 54.4057, 51.0696, 46.0581, 47.2083, 49.8796, 48.2185, 49.4949, 52.8282, 50.1599, 47.5791, 52.8617, 49.594, 49.8952, 50.4253, 51.0264, 48.5285, 50.1212, 52.4871, 52.4633, 48.3626, 50.0318, 53.0496, 49.4787, 47.3127, 48.7044, 51.1941, 49.7941, 50.078, 50.5211, 49.4442, 51.0034, 52.6537, 50.8516, 51.0499, 52.2471, 51.4611, 52.2641, 45.9555, 50.0693, 50.8039, 49.7296, 48.2934, 49.7346, 48.5245, 50.6749, 51.3546, 49.5195, 52.1276, 48.951, 48.801, 50.1595, 49.1989, 51.9859, 49.6541, 51.0662, 51.8765, 46.7427, 49.8916, 50.2399, 46.3063, 50.1081, 49.6148, 47.1159, 52.6604, 50.251, 45.4947, 49.0482, 49.3515, 49.7745, 48.474, 47.8582, 50.4978, 48.068, 51.9285, 50.9753, 50.4736, 48.8619, 50.2226, 50.119, 50.2986, 46.7848, 49.9859, 45.4463, 50.2448, 54.9396, 48.0545, 48.3791, 51.6591, 48.3151, 47.9358, 49.5271, 50.3052, 51.7371, 49.0677, 48.7957, 49.4734, 48.5859, 50.5983, 52.7357, 48.3374, 47.6879, 49.8602, 48.8359, 47.1395, 47.3349, 46.2875, 49.866, 48.516, 53.5774, 50.788, 47.9565, 47.7976, 49.0667, 47.2757, 49.8431, 52.1996, 49.357, 48.6094, 46.0551, 47.0516, 50.1714, 49.7355, 50.3779, 47.1489, 51.7454, 48.9954, 46.3138, 47.7836, 48.7149, 49.8496, 46.669, 51.7517, 49.9694, 51.6964, 52.8715, 49.4088, 48.7286, 51.1527, 46.525, 52.1564, 49.8792, 49.1456, 47.7291, 47.3853, 49.3797, 50.9203, 49.9632, 45.3876, 48.6243, 51.0266, 53.6701, 49.7001, 50.761, 50.0075, 49.1924, 47.6972, 48.1649, 47.3171, 50.9268, 51.7019, 49.6217, 48.7263, 52.0189, 54.4329, 46.5045, 51.1197, 50.2744, 50.6411, 51.3843, 53.0778, 49.7467, 54.3059, 47.6405, 51.5227, 47.1417, 47.1624, 50.8378, 51.4399, 48.8422, 51.1188, 48.5473, 52.2221, 47.0392, 50.4138, 50.5722, 50.4202, 50.0027, 49.7591, 44.8504, 47.065, 51.9949, 51.3897, 52.7157, 50.124, 53.3742, 49.7216, 52.0617, 49.0633, 48.8983, 51.8098, 47.1074, 53.05, 53.685, 49.9872, 52.7572, 48.9282, 49.5041, 50.475, 48.8933, 51.4079, 51.7865, 51.301, 48.9742, 46.9534, 50.8337, 49.2922, 46.7663, 47.5908, 49.4292, 53.0474, 50.7621, 48.2406, 47.8411, 48.0143, 47.9602, 50.3205, 52.2249, 55.4133, 53.5307, 49.0352, 51.8799, 50.1972, 53.4819, 51.0295]

BURSTY_TRAFFIC = [495.0469, 509.6423, 492.0803, 493.7152, 496.8687, 497.3225, 0.0292, 0.0601, 0.0767, 0.0376, 0.0635, 0.033, 0.0492, 0.0417, 0.0519, 0.0552, 0.0371, 0.0484, 0.0574, 0.0407, 0.0624, 0.0628, 0.0453, 0.0642, 0.0306, 0.0439, 0.0554, 0.0595, 0.061, 0.0598, 0.0504, 0.0569, 0.0503, 0.0353, 0.059, 0.0557, 0.0487, 0.0442, 0.0695, 0.0407, 0.0507, 0.043, 0.0495, 0.0614, 0.0541, 0.0469, 0.0581, 0.0593, 0.0493, 0.0457, 0.0427, 0.0311, 0.0655, 0.0429, 0.0384, 0.0415, 0.0386, 0.0611, 0.0491, 0.0402, 0.0419, 0.04, 0.0612, 0.0357, 0.0508, 0.0549, 0.0537, 0.0523, 0.0486, 0.0265, 0.0498, 0.045, 486.7916, 514.4725, 512.5739, 496.267, 503.5742, 500.0377, 0.0311, 0.0457, 0.0587, 0.0489, 0.04, 0.0613, 0.0535, 0.0384, 0.0443, 0.0458, 0.0402, 0.0576, 0.0446, 0.0514, 0.0678, 0.0433, 0.039, 0.05, 0.0455, 0.0467, 0.0409, 0.0345, 0.0461, 0.0371, 0.039, 0.0784, 0.0742, 0.0738, 0.0469, 0.039, 0.0555, 0.0397, 0.0472, 0.0407, 0.0589, 0.0489, 0.0532, 0.0439, 0.048, 0.0319, 0.049, 0.0469, 0.0542, 0.0453, 0.0401, 0.0508, 0.0646, 0.0486, 0.0678, 0.025, 0.0413, 0.0473, 0.0367, 0.0226, 0.0505, 0.0401, 0.042, 0.0486, 0.0478, 0.0438, 0.0562, 0.0421, 0.0614, 0.0622, 0.0342, 0.0412, 509.228, 487.2668, 494.2323, 501.5766, 510.0171, 511.7377, 0.0486, 0.0554, 0.0533, 0.0663, 0.0499, 0.0487, 0.048, 0.0371, 0.037, 0.0231, 0.0647, 0.0696, 0.0328, 0.0585, 0.054, 0.048, 0.0562, 0.049, 0.0765, 0.0591, 0.0421, 0.0391, 0.0638, 0.0473, 0.0478, 0.0515, 0.0507, 0.0616, 0.0406, 0.027, 0.0444, 0.0421, 0.0436, 0.0334, 0.0406, 0.0354, 0.0596, 0.0391, 0.0477, 0.0644, 0.0466, 0.0537, 0.0601, 0.0558, 0.0442, 0.0396, 0.0629, 0.0519, 0.0428, 0.0465, 0.0495, 0.0322, 0.0548, 0.0604, 0.0434, 0.0416, 0.0459, 0.048, 0.0702, 0.0585, 0.0518, 0.0439, 0.0508, 0.0482, 0.0384, 0.0457, 504.4112, 489.2926, 486.8359, 498.4292, 496.0102, 482.7873, 0.0619, 0.0618, 0.0709, 0.0454, 0.0557, 0.0623, 0.0554, 0.0615, 0.0516, 0.0451, 0.0547, 0.0549, 0.0568, 0.0609, 0.0516, 0.0479, 0.0618, 0.0485, 0.0418, 0.0595, 0.0287, 0.0612, 0.0585, 0.05, 0.0614, 0.046, 0.053, 0.0356, 0.0377, 0.0545, 0.0459, 0.0386, 0.0593, 0.0492, 0.0433, 0.0484, 0.065, 0.0608, 0.0505, 0.0564, 0.0442, 0.068, 0.0631, 0.0464, 0.052, 0.0592, 0.0596, 0.0601, 0.0569, 0.0535, 0.0341, 0.0646, 0.0466, 0.0524, 0.0497, 0.0605, 0.0458, 0.0384, 0.0647, 0.057, 0.0654, 0.0495, 0.0534, 0.059, 0.0398, 0.0345, 491.7545, 493.6087, 517.8153, 525.6872, 497.905, 500.9281, 0.0468, 0.0476, 0.0534, 0.0534, 0.0465, 0.0489, 0.044, 0.0427, 0.046, 0.0569, 0.0549, 0.0448, 0.0597, 0.0506, 0.0596, 0.0481, 0.068, 0.064, 0.0573, 0.0644, 0.0435, 0.0674, 0.0378, 0.0508, 0.0439, 0.0309, 0.037, 0.0456, 0.0549, 0.0463, 0.0594, 0.0467, 0.0407, 0.0636, 0.0621, 0.0475, 0.0339, 0.0391, 0.0448, 0.0508, 0.062, 0.0507, 0.0529, 0.0543, 0.0382, 0.0613, 0.0652, 0.0552, 0.0655, 0.0475, 0.0501, 0.0637, 0.0483, 0.0439, 0.0678, 0.0485, 0.042, 0.0499, 0.0286, 0.0605, 0.0635, 0.0376, 0.0433, 0.0686, 0.0597, 0.0467, 498.3306, 504.0133, 514.2054, 507.7485, 505.6508, 497.9603, 0.0654, 0.0558, 0.039, 0.0461, 0.068, 0.0318, 0.0394, 0.0555, 0.0486, 0.0387, 0.015, 0.0467, 0.0618, 0.04, 0.0385, 0.0577, 0.064, 0.0412, 0.0465, 0.0348, 0.05, 0.0425, 0.0483, 0.0255, 0.0592, 0.0315, 0.0365, 0.0476, 0.0298, 0.0339, 0.0406, 0.0316, 0.0429, 0.0489, 0.067, 0.0587, 0.0254, 0.0479, 0.0414, 0.0546, 0.0466, 0.0535, 0.0565, 0.0461, 0.0335, 0.0459, 0.0562, 0.0557, 0.0481, 0.0567, 0.049, 0.0371, 0.0517, 0.0583, 0.0631, 0.0441, 0.0512, 0.0476, 0.0365, 0.0532, 0.0406, 0.0507, 0.0433, 0.0441, 0.0494, 0.0508, 504.9506, 495.9148, 497.1774, 503.661, 495.7969, 500.2102, 0.0442, 0.0495, 0.0582, 0.0581, 0.0582, 0.0621, 0.0515, 0.0599, 0.0468, 0.0601, 0.0576, 0.0666, 0.0583, 0.0568, 0.0532, 0.045, 0.0435, 0.0585, 0.0372, 0.0656, 0.0521, 0.0561, 0.0597, 0.0525, 0.0492, 0.0285, 0.0536, 0.0556, 0.0353, 0.0519, 0.049, 0.0604, 0.0329, 0.0444, 0.048, 0.0414, 0.0519, 0.0294, 0.0273, 0.0497, 0.0555, 0.0417, 0.0537, 0.053, 0.0558, 0.0508, 0.0329, 0.05, 0.0513, 0.065, 0.035, 0.0729, 0.0492, 0.0394, 0.0472, 0.0612, 0.0505, 0.0425, 0.0569, 0.0598, 0.0501, 0.0671, 0.0711, 0.0258, 0.0503, 0.0685, 504.9866, 514.8419, 505.7171, 485.5475, 493.6777, 499.9073, 0.0634, 0.0494, 0.0452, 0.0446, 0.0519, 0.0521, 0.073, 0.0486, 0.0376, 0.0562, 0.0527, 0.0517, 0.0429, 0.0547, 0.0451, 0.0446, 0.0441, 0.0598, 0.0357, 0.0491, 0.0474, 0.0575, 0.0482, 0.0591, 0.0424, 0.0543, 0.0528, 0.0509, 0.0656, 0.0553, 0.0527, 0.061, 0.0539, 0.0475, 0.0597, 0.0723, 0.0444, 0.0564, 0.0514, 0.0509, 0.0311, 0.0436, 0.042, 0.0643, 0.0388, 0.0633, 0.0405, 0.0483, 0.046, 0.0444, 0.0344, 0.0639, 0.0612, 0.062, 0.0597, 0.0591, 0.0624, 0.0424, 0.0557, 0.0645, 0.0535, 0.0482, 0.0412, 0.0474, 0.0453, 0.0201, 504.7448, 515.2522, 506.2786, 501.7734, 492.7512, 497.6197, 0.064, 0.0363, 0.0727, 0.035, 0.0586, 0.0433, 0.0455, 0.0285, 0.0595, 0.0543, 0.0608, 0.045, 0.0634, 0.0519, 0.0483, 0.045, 0.0624, 0.0536, 0.0542, 0.0352, 0.0494, 0.04, 0.0419, 0.0315, 0.0559, 0.0489, 0.05, 0.0402, 0.0519, 0.0401, 0.0491, 0.0563, 0.0538, 0.0559, 0.0432, 0.0306, 0.0528, 0.0393, 0.0468, 0.0382, 0.0477, 0.0567, 0.0467, 0.0378, 0.0515, 0.0527, 0.0502, 0.0528, 0.0624, 0.0666, 0.0571, 0.0465, 0.0536, 0.0361, 0.0501, 0.0686, 0.0495, 0.0499, 0.0422, 0.0612, 0.0472, 0.0531, 0.0465, 0.0379, 0.0482, 0.0399, 493.2261, 494.2891, 517.2198, 506.4776, 503.1522, 493.7094, 0.0561, 0.0486, 0.0622, 0.0478, 0.0672, 0.0477, 0.0509, 0.0453, 0.0497, 0.0402, 0.0385, 0.0334, 0.0416, 0.0405, 0.0529, 0.0436, 0.0484, 0.0631, 0.0559, 0.0344, 0.0541, 0.056, 0.0486, 0.0405, 0.0536, 0.0474, 0.0527, 0.0558, 0.0542, 0.0451, 0.0339, 0.051, 0.0488, 0.0484, 0.0533, 0.0553, 0.0392, 0.0584, 0.0535, 0.0516, 0.0507, 0.0719, 0.0545, 0.0491, 0.0341, 0.0473, 0.0548, 0.0373, 0.0485, 0.0514, 0.0579, 0.0349, 0.0482, 0.0476, 0.05, 0.0542, 0.0588, 0.061, 0.076, 0.0522, 0.0546, 0.0488, 0.0492, 0.0409, 0.0482, 0.0435, 487.2326, 501.5782, 494.3931, 502.0454, 497.1529, 505.0461, 0.0644, 0.0553, 0.0464, 0.0463, 0.0521, 0.0458, 0.0465, 0.0615, 0.0529, 0.0453, 0.0519, 0.0488, 0.0449, 0.0525, 0.046, 0.0441, 0.0571, 0.0432, 0.0639, 0.0376, 0.0546, 0.054, 0.0536, 0.053, 0.059, 0.0474, 0.0462, 0.0467, 0.0699, 0.0396, 0.0608, 0.0417, 0.0554, 0.0611, 0.0378, 0.0412, 0.0587, 0.062, 0.0441, 0.0675, 0.0473, 0.0538, 0.0627, 0.0426, 0.0666, 0.0425, 0.049, 0.0461, 0.0733, 0.0503, 0.0587, 0.0617, 0.0457, 0.059, 0.0469, 0.0327, 0.0463, 0.0505, 0.0276, 0.0381, 0.0492, 0.0543, 0.0563, 0.0498, 0.0434, 0.0558, 486.3505, 507.0814, 484.7717, 509.1429, 490.9865, 515.582, 0.0457, 0.0438, 0.0398, 0.0557, 0.0379, 0.0474, 0.0543, 0.0411, 0.0409, 0.0449, 0.0364, 0.0428, 0.0498, 0.0344, 0.0501, 0.0508, 0.0519, 0.0499, 0.0265, 0.041, 0.0531, 0.0483, 0.0386, 0.0658, 0.0624, 0.0363, 0.0485, 0.0554, 0.0662, 0.0287, 0.0564, 0.0461, 0.0516, 0.047, 0.0666, 0.0695, 0.0472, 0.0407, 0.0755, 0.0543, 0.0392, 0.0612, 0.048, 0.0467, 0.0606, 0.0328, 0.0594, 0.0518, 0.0535, 0.0519, 0.0334, 0.0423, 0.0537, 0.0551, 0.0493, 0.0334, 0.0473, 0.042, 0.0423, 0.0548, 0.053, 0.0349, 0.0487, 0.0557, 0.0519, 0.0483, 500.0842, 488.1702, 518.8654, 501.2902, 491.2894, 481.5181, 0.0323, 0.0437, 0.0603, 0.0443, 0.0473, 0.0398, 0.0649, 0.0724, 0.0226, 0.0463, 0.0549, 0.0549, 0.0448, 0.0452, 0.0567, 0.0651, 0.0321, 0.043, 0.0546, 0.0397, 0.0445, 0.0632, 0.0528, 0.0447, 0.0547, 0.0364, 0.0516, 0.0545, 0.062, 0.0564, 0.0514, 0.048, 0.0475, 0.0622, 0.0624, 0.0554, 0.0504, 0.0414, 0.0365, 0.0454, 0.0578, 0.0516, 0.0628, 0.0481, 0.0337, 0.0431, 0.0583, 0.0525, 0.0512, 0.0495, 0.0449, 0.0564, 0.0447, 0.0539, 0.0502, 0.0339, 0.0654, 0.0475, 0.0584, 0.0559, 0.0498, 0.0454, 0.052, 0.0447, 0.0416, 0.0449, 483.2593, 489.9058, 498.5701, 505.5517, 479.7498, 504.7801, 0.0633, 0.0588, 0.0636, 0.0379, 0.0403, 0.0359, 0.0637, 0.0718, 0.0339, 0.0483, 0.0366, 0.0312, 0.0405, 0.0647, 0.045, 0.058, 0.0566, 0.0416, 0.0633, 0.0391, 0.0448, 0.0544, 0.047, 0.0475, 0.0581, 0.0615, 0.0319, 0.0503, 0.0626, 0.0658, 0.0248, 0.0423, 0.0508, 0.0458, 0.0572, 0.0548, 0.0554, 0.0476, 0.0482, 0.0593, 0.0553, 0.0533, 0.0511, 0.0423, 0.0424, 0.0513, 0.0604, 0.0399, 0.0533, 0.054, 0.0474, 0.0488, 0.0564, 0.0422, 0.0639, 0.0325, 0.0566, 0.0569, 0.0638, 0.0296, 0.0394, 0.0608, 0.0422, 0.0497, 0.0607, 0.0393, 489.5629, 490.1229, 499.5785, 492.5179, 500.5466, 498.8615, 0.055, 0.0434, 0.0555, 0.0585, 0.0589, 0.0544, 0.0457, 0.051, 0.036, 0.0531, 0.0591, 0.0434, 0.0639, 0.0583, 0.0696, 0.0388, 0.0508, 0.0434, 0.0459, 0.0577, 0.0615, 0.0497, 0.0466, 0.0391, 0.0495, 0.0527, 0.0563, 0.0593, 0.0444, 0.0432, 0.0633, 0.0527, 0.0329, 0.066, 0.0432, 0.0581, 0.0467, 0.0506, 0.0667, 0.0318, 0.0468, 0.0427, 0.0473, 0.0469, 0.0592, 0.0543, 0.0453, 0.0651, 0.0584, 0.0412, 0.0463, 0.0432, 0.0521, 0.0461, 0.0575, 0.0447, 0.0501, 0.044, 0.0439, 0.0585, 0.0349, 0.0523, 0.0582, 0.0631, 0.0406, 0.0622, 498.9163, 500.9065, 502.7819, 486.8057, 513.1098, 506.9739, 0.0434, 0.0441, 0.0736, 0.048, 0.0493, 0.0337, 0.0477, 0.0552, 0.0445, 0.0515, 0.0532, 0.0463, 0.06, 0.0481, 0.0491, 0.0499, 0.032, 0.0558, 0.0577, 0.0578, 0.0544, 0.0491, 0.0554, 0.0773, 0.039, 0.056, 0.0549, 0.0584, 0.0357, 0.0701, 0.0629, 0.0477, 0.0683, 0.0517, 0.0712, 0.0522, 0.0299, 0.0497, 0.0455, 0.0363, 0.0401, 0.0528, 0.0425, 0.06, 0.0332, 0.0475, 0.0547, 0.0541, 0.0444, 0.0527, 0.0396, 0.043, 0.0358, 0.0631, 0.046, 0.0401, 0.0471, 0.0636, 0.0676, 0.0411, 0.0681, 0.0495, 0.0615, 0.0588, 0.0423, 0.0431, 483.3116, 500.377, 504.1124, 497.9767, 487.6112, 504.5393, 0.0581, 0.0517, 0.0438, 0.0534, 0.0406, 0.0528, 0.0538, 0.0606, 0.0686, 0.0685, 0.0589, 0.0447, 0.0567, 0.0359, 0.0499, 0.0488, 0.045, 0.055, 0.0457, 0.0701, 0.0483, 0.069, 0.0529, 0.0401, 0.0511, 0.0714, 0.0485, 0.0509, 0.0555, 0.058, 0.0575, 0.0331, 0.0427, 0.0447, 0.0804, 0.042, 0.0514, 0.0769, 0.0551, 0.0635, 0.0585, 0.0342, 0.0454, 0.0475, 0.032, 0.0292, 0.06, 0.0692, 0.0393, 0.0488, 0.0646, 0.0605, 0.0359, 0.0496, 0.0541, 0.0312, 0.0446, 0.0444, 0.027, 0.042, 0.0513, 0.0542, 0.037, 0.0554, 0.048, 0.0487, 494.0709, 478.2863, 508.6394, 504.6632, 499.7455, 494.7167, 0.0365, 0.0541, 0.0453, 0.0558, 0.0567, 0.045, 0.0427, 0.0483, 0.0533, 0.0328, 0.0519, 0.0354, 0.0463, 0.0731, 0.0401, 0.0398, 0.0459, 0.0478, 0.037, 0.0534, 0.0564, 0.0551, 0.0535, 0.0473, 0.0405, 0.0503, 0.0552, 0.0415, 0.0479, 0.0501, 0.0726, 0.0613, 0.0635, 0.057, 0.0439, 0.0561, 0.0652, 0.0401, 0.0506, 0.0513, 0.0556, 0.0617, 0.048, 0.0484, 0.0815, 0.0452, 0.0363, 0.0514, 0.0444, 0.0483, 0.0488, 0.0272, 0.0509, 0.0523, 0.0618, 0.0517, 0.0616, 0.0664, 0.0553, 0.0546, 0.0467, 0.0562, 0.0467, 0.0265, 0.0487, 0.0614, 508.8612, 497.3183, 492.0835, 497.3452, 499.6467, 488.3025, 0.0399, 0.0492, 0.0522, 0.0558, 0.0419, 0.0307, 0.0481, 0.0598, 0.0352, 0.0414, 0.0433, 0.0665, 0.0611, 0.0467, 0.0578, 0.043, 0.0497, 0.0316, 0.0402, 0.0405, 0.0383, 0.0556, 0.0401, 0.0601, 0.0556, 0.0524, 0.0617, 0.0525, 0.0429, 0.0457, 0.0567, 0.0372, 0.0591, 0.048, 0.0562, 0.0512, 0.0422, 0.0659, 0.0476, 0.053, 0.0447, 0.042, 0.0509, 0.045, 0.0494, 0.0513, 0.0447, 0.0598, 0.056, 0.0295, 0.0409, 0.0463, 0.0402, 0.0427, 0.0564, 0.0549, 0.0339, 0.037, 0.0525, 0.047, 0.0582, 0.0435, 0.0503, 0.0413, 0.0472, 0.056, 503.8221, 488.8878, 510.4386, 499.3604, 504.3571, 504.3077, 0.0454, 0.0587, 0.0427, 0.0462, 0.0378, 0.0345, 0.072, 0.0483, 0.0459, 0.0688, 0.0326, 0.0622, 0.0525, 0.0486, 0.0477, 0.047, 0.0649, 0.0601, 0.0487, 0.0421, 0.0502, 0.0399, 0.0419, 0.047, 0.0424, 0.0435, 0.0464, 0.0396, 0.0652, 0.0287, 0.057, 0.0567, 0.0482, 0.0484, 0.0514, 0.0504, 0.057, 0.0554, 0.0459, 0.0401, 0.0531, 0.0557, 0.0578, 0.0445, 0.0748, 0.0327, 0.0684, 0.0419, 0.0489, 0.0675, 0.0686, 0.0656, 0.058, 0.0541, 0.0361, 0.0381, 0.0492, 0.0561, 0.0572, 0.0585, 0.064, 0.0642, 0.0504, 0.0291, 0.0601, 0.0478, 495.1735, 501.6769, 487.0631, 497.7347, 485.5215, 476.7783, 0.0429, 0.0646, 0.0512, 0.0577, 0.0488, 0.054, 0.031, 0.0427, 0.0412, 0.0363, 0.0511, 0.0539, 0.0535, 0.0494, 0.057, 0.0506, 0.0527, 0.0441, 0.0554, 0.0542, 0.0397, 0.0434, 0.0606, 0.0369, 0.0458, 0.0602, 0.0567, 0.0598, 0.056, 0.0464, 0.0322, 0.0705, 0.0581, 0.0411, 0.0512, 0.0437, 0.049, 0.0559, 0.0429, 0.0689, 0.0466, 0.0455, 0.0618, 0.0384, 0.0513, 0.0712, 0.0509, 0.0522, 0.0442, 0.0407, 0.0478, 0.0728, 0.0592, 0.0554, 0.0569, 0.0596, 0.0467, 0.0498, 0.0494, 0.0545, 0.0403, 0.037, 0.0426, 0.0539, 0.039, 0.0577, 488.5348, 497.8455, 486.1783, 506.1297, 484.6796, 479.9006, 0.0506, 0.0532, 0.0577, 0.0517, 0.0542, 0.0519, 0.0521, 0.0638, 0.0479, 0.0403, 0.0631, 0.0597, 0.0557, 0.0446, 0.0548, 0.0669, 0.0453, 0.0567, 0.0366, 0.0407, 0.0598, 0.0566, 0.0465, 0.0392, 0.0426, 0.0705, 0.0506, 0.0587, 0.0558, 0.0527, 0.0545, 0.0467, 0.0613, 0.0509, 0.0468, 0.0554, 0.0497, 0.054, 0.0416, 0.0323, 0.0281, 0.0353, 0.04, 0.0442, 0.0501, 0.0548, 0.0554, 0.0383, 0.069, 0.0489, 0.044, 0.049, 0.0527, 0.0535, 0.0445, 0.0654, 0.0344, 0.0548, 0.0577, 0.0495, 0.0405, 0.0508, 0.0593, 0.0508, 0.0448, 0.0296, 503.0271, 480.5126, 510.9951, 492.238, 511.5543, 509.9011, 0.0497, 0.048, 0.0695, 0.0474, 0.047, 0.0453, 0.0425, 0.0501, 0.0485, 0.0231, 0.0395, 0.0628, 0.0586, 0.0734, 0.0333, 0.0301, 0.0608, 0.0395, 0.0588, 0.0435, 0.0618, 0.0468, 0.0486, 0.065, 0.0576, 0.0436, 0.0223, 0.0659, 0.0489, 0.0527, 0.0409, 0.0488, 0.0419, 0.0431, 0.0248, 0.0573, 0.0522, 0.042, 0.0615, 0.0478, 0.0456, 0.0397, 0.0653, 0.0711, 0.0395, 0.0396, 0.0473, 0.0578, 0.0505, 0.0483, 0.0579, 0.0521, 0.0472, 0.0482, 0.0464, 0.06, 0.0498, 0.0497, 0.0499, 0.0593, 0.0459, 0.0694, 0.0413, 0.0352, 0.0524, 0.0535, 495.7048, 532.8877, 504.3582, 512.5304, 506.1438, 503.4137, 0.0408, 0.0516, 0.0554, 0.0368, 0.0269, 0.0622, 0.0563, 0.0545, 0.0472, 0.0582, 0.0361, 0.0441, 0.0442, 0.0618, 0.0473, 0.0439, 0.0584, 0.0596, 0.0487, 0.054, 0.0371, 0.0443, 0.0407, 0.0472, 0.0576, 0.0425, 0.057, 0.0583, 0.041, 0.0716, 0.0474, 0.0391, 0.0406, 0.0546, 0.048, 0.0513, 0.0266, 0.0409, 0.0352, 0.058, 0.0436, 0.0444, 0.0506, 0.062, 0.0587, 0.059, 0.0424, 0.0467, 0.0503, 0.04, 0.0491, 0.0506, 0.0572, 0.0309, 0.0468, 0.0508, 0.0677, 0.0563, 0.0447, 0.0427, 0.0568, 0.0548, 0.0411, 0.051, 0.0652, 0.0561, 492.5012, 485.416, 506.4024, 502.2154, 510.1353, 512.9235, 0.0429, 0.0502, 0.0412, 0.0325, 0.0473, 0.0582, 0.0511, 0.0499, 0.0348, 0.0514, 0.0501, 0.0501, 0.046, 0.0469, 0.0555, 0.0539, 0.0313, 0.0531, 0.0468, 0.0512, 0.0573, 0.0571, 0.0684, 0.048, 0.0569, 0.0395, 0.0566, 0.0364, 0.0588, 0.0393, 0.037, 0.0559, 0.0574, 0.0669, 0.0466, 0.0449, 0.0493, 0.0374, 0.0418, 0.0512, 0.0375, 0.028, 0.0352, 0.0507, 0.038, 0.0598, 0.0581, 0.0565, 0.0479, 0.0511, 0.0376, 0.0534, 0.0585, 0.0506, 0.037, 0.0333, 0.0478, 0.048, 0.0714, 0.0359, 0.0343, 0.0532, 0.0452, 0.0779, 0.0377, 0.0653, 490.7391, 499.8134, 497.2968, 490.421, 513.4861, 505.6125, 0.0405, 0.0628, 0.0416, 0.0634, 0.0518, 0.0421, 0.0507, 0.0415, 0.0325, 0.0638, 0.044, 0.0423, 0.0356, 0.0526, 0.0297, 0.0395, 0.0519, 0.0379, 0.0561, 0.0564, 0.0589, 0.0474, 0.0425, 0.0432, 0.0688, 0.0554, 0.0524, 0.0538, 0.0683, 0.0644, 0.0333, 0.0525, 0.0681, 0.0479, 0.0492, 0.0427, 0.055, 0.0464, 0.0631, 0.0395, 0.0468, 0.0518, 0.0462, 0.0468, 0.0522, 0.0468, 0.0511, 0.0364, 0.0622, 0.0309, 0.0433, 0.064, 0.0284, 0.0709, 0.044, 0.047, 0.0498, 0.0607, 0.0485, 0.0565, 0.0596, 0.0656, 0.0524, 0.0439, 0.0377, 0.0431, 496.7001, 494.1156, 507.7887, 480.3311, 493.4945, 507.9081, 0.0463, 0.0489, 0.0564, 0.0649, 0.0622, 0.0424, 0.0311, 0.0505, 0.0398, 0.0452, 0.0417, 0.0611, 0.0449, 0.048, 0.0596, 0.0543, 0.0473, 0.0527, 0.0654, 0.0582, 0.0485, 0.0548, 0.0517, 0.0635, 0.0465, 0.0562, 0.071, 0.0418, 0.0499, 0.0656, 0.0684, 0.0584, 0.0539, 0.0492, 0.0326, 0.0411, 0.0607, 0.0451, 0.0472, 0.052, 0.0484, 0.0454, 0.028, 0.054, 0.0498, 0.0525, 0.0459, 0.0566, 0.0414, 0.0647, 0.0581, 0.0597, 0.0477, 0.0274, 0.0394, 0.0324, 0.0504, 0.0539, 0.0705, 0.043, 0.0451, 0.0337, 0.0775, 0.0562, 0.0628, 0.0458, 496.8816, 497.3389, 477.0454, 492.3137, 499.6248, 502.896, 0.0616, 0.0526, 0.0438, 0.0414, 0.0436, 0.0684, 0.052, 0.0496, 0.0662, 0.0559, 0.0546, 0.0385, 0.0597, 0.0384, 0.049, 0.0374, 0.0661, 0.0555, 0.0464, 0.04, 0.0451, 0.0524, 0.0303, 0.0581, 0.0595, 0.049, 0.0537, 0.06, 0.0568, 0.0526, 0.0439, 0.0462, 0.0497, 0.0291, 0.0535, 0.0375, 0.0517, 0.0499, 0.0466, 0.032, 0.0546, 0.0524, 0.0513, 0.0527, 0.0414, 0.0618, 0.0503, 0.0583, 0.041, 0.0429, 0.0529, 0.0528, 0.05, 0.0625, 0.0337, 0.0505, 0.0362, 0.0674, 0.0529, 0.0655, 0.0662, 0.0437, 0.0461, 0.064, 0.0422, 0.0487, 496.1863, 488.7987, 520.2551, 507.1485, 496.1513, 486.5951, 0.0487, 0.0566, 0.0678, 0.0707, 0.052, 0.0663, 0.0524, 0.0594, 0.0522, 0.0449, 0.0653, 0.0479, 0.0435, 0.0411, 0.0589, 0.0577, 0.0579, 0.0517, 0.036, 0.0625, 0.057, 0.0541, 0.041, 0.0426, 0.0564, 0.0425, 0.0565, 0.0519, 0.0543, 0.0597, 0.0581, 0.0528, 0.0411, 0.0476, 0.0635, 0.0522, 0.0677, 0.0359, 0.0652, 0.04, 0.0358, 0.0409, 0.0398, 0.0658, 0.0403, 0.0543, 0.0479, 0.0338, 0.0545, 0.0517, 0.0378, 0.0603, 0.0414, 0.0322, 0.0603, 0.0458, 0.0384, 0.0443, 0.0441, 0.0493, 0.0378, 0.0612, 0.0547, 0.0476, 0.0678, 0.0517, 504.0298, 498.7177, 500.0053, 512.5111, 494.7635, 508.5412, 0.0429, 0.0437, 0.0406, 0.0353, 0.0551, 0.0373, 0.0592, 0.0591, 0.0466, 0.0571, 0.0548, 0.06, 0.0396, 0.0541, 0.0612, 0.0476, 0.0539, 0.0442, 0.0721, 0.0585, 0.0477, 0.0635, 0.0486, 0.0533, 0.0573, 0.0654, 0.0467, 0.0699, 0.0598, 0.0601, 0.0584, 0.0611, 0.0547, 0.0515, 0.0647, 0.0536, 0.0584, 0.0399, 0.0653, 0.0541, 0.0647, 0.0559, 0.0496, 0.0577, 0.0414, 0.0322, 0.0404, 0.0627, 0.0425, 0.0445, 0.0596, 0.0551, 0.0427, 0.0495, 0.0456, 0.0586, 0.0546, 0.0407, 0.0372, 0.0341, 0.0555, 0.057, 0.0521, 0.0412, 0.0378, 0.0579, 473.509, 504.9354, 495.7398, 495.9017, 522.1803, 506.3852, 0.0519, 0.0488, 0.0359, 0.0385, 0.0326, 0.0488, 0.0368, 0.0493, 0.0461, 0.0558, 0.0513, 0.0477, 0.0485, 0.0403, 0.054, 0.0499, 0.0707, 0.0609, 0.0519, 0.0617, 0.0387, 0.0443, 0.0359, 0.058, 0.057, 0.04, 0.0607, 0.0536, 0.0393, 0.0483, 0.0477, 0.0689, 0.048, 0.0572, 0.0507, 0.0671, 0.0429, 0.0584, 0.0499, 0.045, 0.0509, 0.0662, 0.0569, 0.0435, 0.0429, 0.0595, 0.0625, 0.0426, 0.0414, 0.0433, 0.0387, 0.0563, 0.0524, 0.0454, 0.0332, 0.0459, 0.0389, 0.0573, 0.055, 0.0559, 0.048, 0.0584, 0.0591, 0.0551, 0.063, 0.0486, 488.4266, 487.2601, 516.5337, 487.9673, 505.05, 500.4938, 0.0489, 0.0627, 0.0649, 0.043, 0.0518, 0.0519, 0.0361, 0.0564, 0.0553, 0.0497, 0.065, 0.0334, 0.0577, 0.0447, 0.0396, 0.0573, 0.0488, 0.0451, 0.0671, 0.0372, 0.0384, 0.0425, 0.053, 0.0499, 0.0493, 0.0407, 0.0403, 0.0532, 0.032, 0.0559, 0.0472, 0.061, 0.0542, 0.0548, 0.0522, 0.0278, 0.0539, 0.0484, 0.0606, 0.0418, 0.0401, 0.0606, 0.0422, 0.0574, 0.0367, 0.0493, 0.0542, 0.0485, 0.0473, 0.0587, 0.0304, 0.0416, 0.0331, 0.0407, 0.0421, 0.0539, 0.0474, 0.0557, 0.0614, 0.0644, 0.0471, 0.02, 0.053, 0.0617, 0.0377, 0.0437, 506.64, 504.7903, 505.8813, 505.423, 480.7013, 507.7932, 0.0446, 0.0717, 0.0667, 0.0488, 0.0632, 0.0432, 0.0543, 0.0553, 0.0589, 0.0358, 0.0713, 0.0537, 0.0621, 0.0469, 0.0504, 0.0489, 0.0511, 0.048, 0.0569, 0.0728, 0.0354, 0.043, 0.0313, 0.0475, 0.0487, 0.0546, 0.0448, 0.0314, 0.04, 0.0536, 0.0484, 0.0699, 0.0662, 0.0493, 0.057, 0.0562, 0.0656, 0.0585, 0.0487, 0.0412, 0.042, 0.0496, 0.0418, 0.0412, 0.0526, 0.0346, 0.041, 0.0709, 0.0288, 0.0594, 0.0524, 0.0416, 0.058, 0.0377, 0.0519, 0.0481, 0.0492, 0.0491, 0.0563, 0.0574, 0.064, 0.0448, 0.0495, 0.0557, 0.0564, 0.035, 498.6466, 506.5146, 517.4506, 482.7378, 510.3746, 486.993, 0.0537, 0.0501, 0.0436, 0.0476, 0.0545, 0.0594, 0.0492, 0.0597, 0.0377, 0.0428, 0.0354, 0.0514, 0.0536, 0.0576, 0.0509, 0.0583, 0.0322, 0.0517, 0.0427, 0.0559, 0.0455, 0.0505, 0.0657, 0.0634, 0.0503, 0.0418, 0.0587, 0.0483, 0.0474, 0.0458, 0.0415, 0.0519, 0.0617, 0.0601, 0.0452, 0.0335, 0.032, 0.0518, 0.0397, 0.0507, 0.0508, 0.0583, 0.029, 0.049, 0.0507, 0.0465, 0.0511, 0.0423, 0.0459, 0.0591, 0.0406, 0.0536, 0.0567, 0.0459, 0.0488, 0.041, 0.0536, 0.0422, 0.039, 0.057, 0.0534, 0.0559, 0.0328, 0.0328, 0.0432, 0.0442, 498.4146, 498.7709, 496.8735, 482.2647, 513.1748, 508.3904, 0.0645, 0.0411, 0.0362, 0.0452, 0.0406, 0.0489, 0.0519, 0.0555, 0.0307, 0.0456, 0.0523, 0.0678, 0.0576, 0.0452, 0.0535, 0.0659, 0.0525, 0.049, 0.0736, 0.053, 0.0581, 0.056, 0.0442, 0.0506, 0.0477, 0.0569, 0.0511, 0.0425, 0.0493, 0.0551, 0.0531, 0.0357, 0.0612, 0.0621, 0.0495, 0.0542, 0.0643, 0.0572, 0.0508, 0.0397, 0.0688, 0.0517, 0.0455, 0.0465, 0.0484, 0.0323, 0.0547, 0.0628, 0.0466, 0.0582, 0.0478, 0.0498, 0.049, 0.0567, 0.0487, 0.0646, 0.0418, 0.0515, 0.0718, 0.0644, 0.0393, 0.0457, 0.0603, 0.0432, 0.0501, 0.0519, 489.9988, 500.1863, 491.2338, 509.019, 505.5364, 504.4816, 0.0599, 0.0484, 0.0511, 0.0595, 0.0368, 0.0445, 0.041, 0.0658, 0.0544, 0.0493, 0.0597, 0.0675, 0.0424, 0.0505, 0.0587, 0.0607, 0.0342, 0.0527, 0.0434, 0.047, 0.0508, 0.0424, 0.0466, 0.0584, 0.0551, 0.0571, 0.0406, 0.0459, 0.0653, 0.0505, 0.0506, 0.0322, 0.0417, 0.0476, 0.0449, 0.0428, 0.0469, 0.0384, 0.0698, 0.0256, 0.0541, 0.0523, 0.047, 0.0408, 0.0503, 0.0441, 0.0499, 0.044, 0.0253, 0.0602, 0.0602, 0.0526, 0.0586, 0.0658, 0.0334, 0.0513, 0.0403, 0.0471, 0.0469, 0.0602, 0.0438, 0.0717, 0.0446, 0.0391, 0.0428, 0.0436, 496.7591, 495.5263, 493.3084, 499.0154, 488.0579, 489.6043, 0.0424, 0.0491, 0.0272, 0.0554, 0.0643, 0.0429, 0.0532, 0.0457, 0.0314, 0.0471, 0.0604, 0.0506, 0.0522, 0.053, 0.0586, 0.0488, 0.0559, 0.0642, 0.0413, 0.0479, 0.0604, 0.0542, 0.0552, 0.0577, 0.0433, 0.0474, 0.0342, 0.0334, 0.0471, 0.0683, 0.059, 0.0402, 0.0452, 0.0631, 0.0437, 0.0544, 0.0358, 0.0463, 0.0551, 0.0527, 0.049, 0.042, 0.0496, 0.0546, 0.0539, 0.0373, 0.0509, 0.0411, 0.0518, 0.0367, 0.0469, 0.0679, 0.0603, 0.0393, 0.044, 0.051, 0.0563, 0.0206, 0.0651, 0.0598, 0.0536, 0.0548, 0.0562, 0.0437, 0.0526, 0.048, 489.2656, 499.2091, 495.4614, 492.343, 495.0047, 499.9882, 0.041, 0.0464, 0.0415, 0.0575, 0.0454, 0.0612, 0.0297, 0.046, 0.0637, 0.0291, 0.0678, 0.0436, 0.0454, 0.0314, 0.0392, 0.0457, 0.0537, 0.0352, 0.04, 0.0462, 0.0487, 0.0518, 0.0426, 0.0584, 0.0422, 0.0358, 0.0529, 0.0625, 0.0737, 0.0497, 0.0454, 0.0542, 0.05, 0.0485, 0.0386, 0.0543, 0.0586, 0.0503, 0.058, 0.0553, 0.0495, 0.0726, 0.048, 0.0484, 0.0482, 0.0613, 0.0648, 0.0542, 0.0497, 0.064, 0.0683, 0.0466, 0.065, 0.0326, 0.0641, 0.0498, 0.0387, 0.0507, 0.0618, 0.0382, 0.051, 0.0474, 0.0709, 0.0538, 0.0593, 0.0634, 503.6594, 496.1477, 483.0803, 509.361, 513.3712, 504.9136, 0.0542, 0.0517, 0.0225, 0.0422, 0.0547, 0.063, 0.069, 0.052, 0.055, 0.0429, 0.0445, 0.029, 0.0295, 0.0375, 0.0264, 0.0476, 0.0344, 0.0609, 0.0482, 0.0468, 0.0554, 0.0395, 0.0494, 0.0458, 0.0425, 0.0528, 0.0538, 0.0613, 0.0577, 0.0647, 0.0504, 0.0493, 0.0486, 0.0592, 0.043, 0.0609, 0.0457, 0.0378, 0.0452, 0.0511, 0.0636, 0.0587, 0.0553, 0.0623, 0.0667, 0.0464, 0.0517, 0.0432, 0.0471, 0.0529, 0.0488, 0.0426, 0.0575, 0.0378, 0.0553, 0.0462, 0.0502, 0.0447, 0.0648, 0.0551, 0.0524, 0.0549, 0.0471, 0.0566, 0.0578, 0.0692, 503.6963, 507.4987, 497.4635, 492.5825, 486.8782, 500.835, 0.0417, 0.0617, 0.0366, 0.0544, 0.0513, 0.0476, 0.055, 0.0415, 0.0433, 0.0484, 0.0473, 0.0412, 0.0567, 0.0335, 0.0541, 0.065, 0.0312, 0.0496, 0.0512, 0.0458, 0.0511, 0.0424, 0.0475, 0.0505, 0.061, 0.0597, 0.0521, 0.0551, 0.0418, 0.045, 0.0404, 0.0592, 0.0652, 0.0533, 0.0361, 0.0353, 0.0604, 0.0505, 0.0427, 0.0624, 0.0679, 0.063, 0.0461, 0.0605, 0.0508, 0.0519, 0.054, 0.0397, 0.0405, 0.0451, 0.0347, 0.0612, 0.0498, 0.0597, 0.0421, 0.0628, 0.0418, 0.0753, 0.0622, 0.0382, 0.0597, 0.0431, 0.0348, 0.0582, 0.0597, 0.0471, 511.7898, 502.1383, 518.431, 490.2196, 523.3564, 494.8155, 0.0585, 0.0754, 0.0501, 0.0447, 0.0373, 0.072, 0.0585, 0.0484, 0.0518, 0.0321, 0.0442, 0.0515, 0.0556, 0.05, 0.0563, 0.0443, 0.0564, 0.0536, 0.0513, 0.0542, 0.0505, 0.0652, 0.0555, 0.042, 0.0409, 0.0513, 0.035, 0.0528, 0.043, 0.029, 0.0407, 0.0336, 0.0454, 0.0337, 0.0543, 0.053, 0.0504, 0.0447, 0.0531, 0.0289, 0.0569, 0.0353, 0.0411, 0.0546, 0.0604, 0.055, 0.0492, 0.0367, 0.0524, 0.0635, 0.0511, 0.0405, 0.04, 0.0657, 0.0372, 0.0393, 0.0624, 0.0426, 0.0542, 0.0549, 0.0526, 0.0604, 0.0422, 0.0623, 0.0427, 0.0537, 485.9407, 512.1127, 524.6268, 505.4766, 494.7318, 502.8218, 0.0422, 0.0327, 0.0459, 0.0509, 0.0482, 0.0457, 0.0617, 0.0363, 0.0587, 0.0507, 0.0412, 0.0455, 0.0389, 0.0532, 0.0598, 0.0475, 0.0511, 0.0416, 0.0492, 0.0642, 0.0357, 0.0391, 0.0408, 0.053, 0.0411, 0.0515, 0.0407, 0.0479, 0.0562, 0.0226, 0.0404, 0.0481, 0.0474, 0.0449, 0.0379, 0.0699, 0.0444, 0.0464, 0.0562, 0.0351, 0.047, 0.0509, 0.049, 0.055, 0.0405, 0.0506, 0.0617, 0.0402, 0.0499, 0.0591, 0.0447, 0.0677, 0.0439, 0.0483, 0.0488, 0.0515, 0.0436, 0.0627, 0.0422, 0.0447, 0.066, 0.0537, 0.05, 0.0542, 0.0633, 0.059, 492.8725, 492.1254, 495.8702, 526.4009, 497.202, 493.0617, 0.0587, 0.0331, 0.0487, 0.0379, 0.0461, 0.051, 0.0461, 0.054, 0.0641, 0.0479, 0.0572, 0.0434, 0.054, 0.0495, 0.0649, 0.0427, 0.0481, 0.051, 0.0573, 0.0476, 0.0381, 0.033, 0.0555, 0.0409, 0.0549, 0.0544, 0.0494, 0.0585, 0.0305, 0.0483, 0.0507, 0.0679, 0.042, 0.058, 0.0507, 0.0393, 0.0497, 0.0326, 0.0475, 0.0647, 0.0326, 0.0366, 0.0465, 0.0428, 0.0484, 0.0511, 0.0455, 0.0527, 0.0486, 0.0634, 0.0587, 0.0487, 0.0503, 0.0519, 0.0484, 0.0532, 0.0463, 0.0653, 0.0562, 0.0382, 0.0441, 0.0433, 0.0323, 0.0648, 0.0591, 0.0507, 493.8295, 508.914, 483.9943, 503.9014, 503.7869, 514.9981, 0.0464, 0.0432, 0.0692, 0.0539, 0.0638, 0.0472, 0.0415, 0.0465, 0.0576, 0.0779, 0.0443, 0.0561, 0.044, 0.0637, 0.0638, 0.0526, 0.0547, 0.0581, 0.0199, 0.0638, 0.0766, 0.0539, 0.0391, 0.046, 0.0522, 0.0724, 0.0593, 0.0601, 0.0526, 0.0463, 0.0562, 0.0805, 0.0443, 0.0473, 0.0594, 0.0646, 0.049, 0.0399, 0.036, 0.0591, 0.0382, 0.0567, 0.046, 0.0586, 0.0664, 0.0628, 0.0664, 0.0458, 0.0449, 0.0613, 0.0346, 0.0624, 0.0388, 0.0504, 0.055, 0.0403, 0.0556, 0.0471, 0.0471, 0.062, 0.0444, 0.0596, 0.0602, 0.0693, 0.0392, 0.0597, 510.1432, 498.3443, 490.9076, 489.4998, 508.9621, 510.6375, 0.0635, 0.0499, 0.0473, 0.026, 0.0466, 0.0568, 0.0398, 0.0452, 0.0581, 0.0552, 0.0491, 0.0293, 0.0428, 0.0396, 0.0627, 0.0353, 0.0551, 0.0581, 0.0544, 0.0456, 0.0708, 0.0413, 0.0463, 0.0575, 0.0554, 0.0458, 0.0427, 0.0518, 0.0259, 0.0317, 0.0578, 0.0243, 0.0451, 0.05, 0.0429, 0.0445, 0.0552, 0.0472, 0.0251, 0.056, 0.0526, 0.0501, 0.0411, 0.032, 0.0699, 0.0494, 0.0594, 0.0544, 0.049, 0.0658, 0.0625, 0.0619, 0.0426, 0.0401, 0.0613, 0.0517, 0.0488, 0.0418, 0.0351, 0.0611, 0.0511, 0.0406, 0.0475, 0.0383, 0.0438, 0.0415, 503.9959, 503.9489, 498.5347, 518.6201, 500.1094, 495.1321, 0.055, 0.059, 0.0382, 0.0687, 0.0519, 0.0434, 0.0617, 0.0582, 0.0691, 0.0596, 0.0425, 0.0504, 0.0495, 0.0583, 0.0335, 0.056, 0.046, 0.0377, 0.036, 0.0405, 0.0549, 0.0566, 0.0517, 0.0595, 0.0446, 0.0563, 0.0555, 0.048, 0.0424, 0.0415, 0.0422, 0.0531, 0.0494, 0.0346, 0.055, 0.0566, 0.0394, 0.0595, 0.0568, 0.0512, 0.0457, 0.0625, 0.0491, 0.066, 0.049, 0.0167, 0.0385, 0.0577, 0.0544, 0.0581, 0.0609, 0.0662, 0.0462, 0.0589, 0.0576, 0.0414, 0.0559, 0.0607, 0.0596, 0.069, 0.0741, 0.0522, 0.0453, 0.0572, 0.0513, 0.058, 503.0903, 482.625, 494.4807, 492.4037, 478.6338, 505.5831, 0.0659, 0.0394, 0.0599, 0.0356, 0.0429, 0.0489, 0.0543, 0.0641, 0.0463, 0.0527, 0.0482, 0.0533, 0.0383, 0.0459, 0.0489, 0.0297, 0.0533, 0.0494, 0.0431, 0.0469, 0.0494, 0.0664, 0.0446, 0.0365, 0.0505, 0.0653, 0.0472, 0.0508, 0.0402, 0.042, 0.0555, 0.0535, 0.0518, 0.0468, 0.06, 0.043, 0.0567, 0.0527, 0.0387, 0.0432, 0.0379, 0.0528, 0.0517, 0.0414, 0.0456, 0.0451, 0.0531, 0.0528, 0.0541, 0.0618, 0.0525, 0.0613, 0.038, 0.0444, 0.0531, 0.0463, 0.0631, 0.0387, 0.0562, 0.067, 0.0417, 0.0427, 0.0668, 0.0501, 0.0406, 0.0431, 505.2994, 510.6529, 475.5016, 497.8084, 493.8334, 519.1271, 0.05, 0.058, 0.042, 0.0468, 0.0244, 0.0601, 0.0609, 0.0461, 0.0386, 0.0745, 0.0441, 0.0511, 0.0597, 0.0543, 0.0423, 0.0714, 0.0366, 0.055, 0.0438, 0.0485, 0.0531, 0.0333, 0.0527, 0.0615, 0.0448, 0.0611, 0.0567, 0.0551, 0.04, 0.0417, 0.0533, 0.0548, 0.0518, 0.0325, 0.0582, 0.039, 0.0638, 0.0709, 0.0645, 0.0483, 0.0542, 0.0331, 0.0472, 0.0731, 0.0306, 0.0534, 0.0481, 0.0553, 0.0453, 0.0581, 0.0497, 0.0391, 0.0411, 0.0545, 0.0353, 0.0584, 0.0283, 0.0649, 0.039, 0.0644, 0.0669, 0.0473, 0.0655, 0.0519, 0.0541, 0.0653, 497.3139, 509.2897, 492.282, 515.9198, 494.1337, 511.3917, 0.0522, 0.0566, 0.0303, 0.0496, 0.0558, 0.0546, 0.0448, 0.0602, 0.048, 0.0389, 0.053, 0.0494, 0.0418, 0.0371, 0.0597, 0.0437, 0.0474, 0.0634, 0.0467, 0.0533, 0.0449, 0.0438, 0.0345, 0.0666, 0.0541, 0.0534, 0.05, 0.0411, 0.0516, 0.0398, 0.0533, 0.0547, 0.048, 0.0564, 0.0564, 0.0539, 0.0348, 0.0425, 0.0492, 0.0623, 0.0495, 0.052, 0.0505, 0.0463, 0.0535, 0.0346, 0.0423, 0.068, 0.059, 0.0439, 0.0548, 0.0458, 0.0391, 0.0522, 0.0425, 0.063, 0.0478, 0.0426, 0.05, 0.0478, 0.0575, 0.057, 0.0408, 0.057, 0.0617, 0.0536, 510.2362, 493.7698, 510.6668, 501.0896, 511.6058, 502.3718, 0.0553, 0.0331, 0.0369, 0.0507, 0.0392, 0.0378, 0.0252, 0.0392, 0.0524, 0.0379, 0.0558, 0.0315, 0.0693, 0.0618, 0.0257, 0.0299, 0.0502, 0.0329, 0.0427, 0.0534, 0.0303, 0.0562, 0.049, 0.0355, 0.063, 0.0564, 0.0434, 0.0603, 0.0435, 0.0327, 0.0481, 0.0509, 0.049, 0.0495, 0.0509, 0.0483, 0.0516, 0.0604, 0.0496, 0.0571, 0.0459, 0.0421, 0.0357, 0.0539, 0.0516, 0.037, 0.0374, 0.0663, 0.0539, 0.0457, 0.051, 0.0433, 0.051, 0.0521, 0.0345, 0.0385, 0.0523, 0.0377, 0.0585, 0.0475, 0.0471, 0.0566, 0.0522, 0.0582, 0.0429, 0.0536, 506.4458, 497.273, 496.6595, 504.2874, 508.6625, 493.6127, 0.0549, 0.0416, 0.0345, 0.0557, 0.0494, 0.0402, 0.0405, 0.0533, 0.0527, 0.0594, 0.0517, 0.0459, 0.06, 0.0697, 0.0492, 0.045, 0.0502, 0.0449, 0.0364, 0.0509, 0.05, 0.0413, 0.0605, 0.077, 0.0529, 0.041, 0.0498, 0.0549, 0.0488, 0.0503, 0.0533, 0.0405, 0.0559, 0.0427, 0.0679, 0.0436, 0.0322, 0.0578, 0.0374, 0.0883, 0.0624, 0.0573, 0.0413, 0.0572, 0.0576, 0.0476, 0.0447, 0.0429, 0.0548, 0.0559, 0.0452, 0.0479, 0.0586, 0.0628, 0.0503, 0.0465, 0.0565, 0.031, 0.0449, 0.0418, 0.045, 0.053, 0.061, 0.0707, 0.0661, 0.0464, 502.3425, 494.1181, 503.4898, 496.6846, 506.1382, 509.9988, 0.0452, 0.0632, 0.0566, 0.0458, 0.0424, 0.0658, 0.0397, 0.0683, 0.0698, 0.0543, 0.0526, 0.0484, 0.0403, 0.0594, 0.0442, 0.0491, 0.0712, 0.052, 0.0749, 0.0663, 0.0586, 0.0574, 0.0696, 0.0479, 0.0448, 0.0488, 0.0387, 0.0414, 0.0458, 0.0604, 0.0543, 0.047, 0.0447, 0.0421, 0.038, 0.0396, 0.0335, 0.0523, 0.054, 0.0447, 0.051, 0.0552, 0.0567, 0.0475, 0.0539, 0.0522, 0.0328, 0.0619, 0.0557, 0.0544, 0.0559, 0.0635, 0.0372, 0.0738, 0.0441, 0.0394, 0.0317, 0.0403, 0.0503, 0.0447, 0.037, 0.0569, 0.0295, 0.0388, 0.0712, 0.0546, 497.6464, 502.0742, 502.0393, 506.0052, 501.6415, 502.0609, 0.0516, 0.0443, 0.0443, 0.0617, 0.0409, 0.0509, 0.0373, 0.0367, 0.0403, 0.0449, 0.0531, 0.0636, 0.0452, 0.0486, 0.0469, 0.0668, 0.0581, 0.0458, 0.056, 0.0452, 0.0541, 0.0392, 0.0359, 0.0455, 0.0455, 0.042, 0.0464, 0.0496, 0.0405, 0.0607, 0.0551, 0.0489, 0.0516, 0.0609, 0.0597, 0.0581, 0.0442, 0.0695, 0.0462, 0.06, 0.0541, 0.0496, 0.0579, 0.0412, 0.031, 0.0643, 0.0566, 0.0499, 0.0538, 0.044, 0.0662, 0.0517, 0.0418, 0.0608, 0.0615, 0.0662, 0.0323, 0.0472, 0.0453, 0.0555, 0.0616, 0.046, 0.0468, 0.0533, 0.0572, 0.0622, 485.8171, 486.9826, 500.0398, 494.2567, 512.8219, 495.1266, 0.0551, 0.0437, 0.0736, 0.0438, 0.0438, 0.0706, 0.0708, 0.0463, 0.0447, 0.0511, 0.0502, 0.0499, 0.0499, 0.0627, 0.0415, 0.071, 0.0308, 0.0335, 0.0596, 0.0537, 0.0615, 0.0646, 0.0517, 0.0319, 0.0571, 0.0477, 0.0533, 0.036, 0.0449, 0.0541, 0.0519, 0.0467, 0.0578, 0.0482, 0.054, 0.0468, 0.0484, 0.026, 0.0563, 0.0588, 0.0421, 0.0351, 0.055, 0.0503, 0.0483, 0.0543, 0.0422, 0.0418, 0.0455, 0.0429, 0.0617, 0.0616, 0.0463, 0.0511, 0.0718, 0.0471, 0.0457, 0.0567, 0.0598, 0.0493, 0.0538, 0.0469, 0.037, 0.0528, 0.0609, 0.0392, 504.6474, 483.7968, 500.7402, 504.6047, 513.5971, 499.7954, 0.0423, 0.0445, 0.0601, 0.0392, 0.0633, 0.028, 0.0374, 0.0567, 0.0554, 0.0439, 0.0487, 0.0421, 0.0499, 0.0619, 0.0333, 0.0592, 0.0541, 0.0496, 0.0646, 0.0607, 0.0505, 0.0617, 0.0376, 0.042, 0.0638, 0.0606, 0.0467, 0.0376, 0.0551, 0.0417, 0.0274, 0.0473, 0.04, 0.0591, 0.035, 0.0404, 0.0626, 0.0463, 0.0626, 0.0614, 0.0404, 0.0615, 0.0586, 0.0441, 0.037, 0.0602, 0.0399, 0.0644, 0.0578, 0.0395, 0.0265, 0.0466, 0.0554, 0.037, 0.0526, 0.0354, 0.0628, 0.0521, 0.0739, 0.0537, 0.0683, 0.0631, 0.0552, 0.0347, 0.0545, 0.0438, 503.8247, 491.651, 507.4585, 498.7504, 497.0486, 501.0415, 0.0204, 0.058, 0.0485, 0.0677, 0.0543, 0.0666, 0.0416, 0.0474, 0.0425, 0.0554, 0.0577, 0.0323, 0.0556, 0.0429, 0.0378, 0.039, 0.0537, 0.0438, 0.0522, 0.0459, 0.0475, 0.0359, 0.0455, 0.0608, 0.0538, 0.059, 0.0486, 0.0656, 0.0393, 0.0646, 0.0633, 0.0398, 0.0585, 0.0478, 0.0601, 0.0585, 0.063, 0.0416, 0.0344, 0.0438, 0.0402, 0.0476, 0.0478, 0.0437, 0.0614, 0.0573, 0.0573, 0.0429, 0.0487, 0.0658, 0.0402, 0.0479, 0.0541, 0.0478, 0.0677, 0.045, 0.0563, 0.0446, 0.0463, 0.0482, 0.0608, 0.05, 0.0622, 0.0532, 0.046, 0.0431]

SEASONAL_TRAFFIC = [4.7839, 4.7514, 4.8759, 6.1493, 4.9799, 3.0214, 5.8835, 5.1227, 5.3582, 6.0385, 6.4151, 8.0349, 7.5183, 6.9635, 5.9753, 5.8662, 8.0833, 10.0263, 8.4879, 8.6515, 10.0138, 7.4604, 9.6161, 11.2828, 12.339, 11.168, 12.6123, 12.9562, 14.3116, 12.0402, 15.1515, 12.6334, 11.5981, 15.2569, 15.4488, 18.8076, 19.1766, 17.0533, 20.8695, 18.8261, 20.9452, 21.3926, 22.7774, 24.619, 25.1467, 25.5242, 26.7964, 27.3729, 26.5595, 27.2794, 28.5164, 30.846, 30.607, 35.38, 31.5503, 32.042, 35.7618, 37.668, 37.2268, 38.6614, 40.4927, 39.1631, 38.1258, 40.4228, 43.6152, 40.9889, 44.1766, 45.4808, 45.6046, 48.1423, 48.9083, 52.5004, 50.93, 50.0676, 51.1202, 51.6958, 55.3504, 54.0488, 55.7683, 57.9695, 56.729, 58.3386, 56.9779, 59.0721, 60.7953, 63.2159, 65.322, 64.4371, 65.783, 66.5617, 68.8479, 69.4636, 69.4284, 68.3866, 72.1338, 72.2161, 74.3404, 73.2999, 77.1081, 74.4623, 78.2005, 76.7816, 76.6199, 76.4739, 78.6989, 81.8055, 81.6261, 82.1514, 78.256, 83.5728, 84.0113, 83.0079, 83.5309, 85.0913, 88.2882, 84.7074, 86.2201, 89.4588, 87.2834, 87.9247, 89.1178, 87.5908, 90.2454, 88.5448, 92.1116, 91.1938, 94.9997, 92.3616, 94.3347, 90.657, 92.7341, 93.687, 96.0852, 91.189, 95.4192, 95.0224, 96.6167, 95.5448, 94.6931, 93.9501, 92.9565, 95.1968, 94.6696, 98.0197, 94.0835, 95.4699, 92.6037, 94.3105, 95.2205, 95.9685, 96.7872, 94.41, 92.6405, 94.8221, 94.7088, 94.4479, 92.4162, 94.9023, 93.0491, 93.6616, 94.1973, 92.8543, 92.0044, 94.4182, 91.1494, 89.9153, 90.0834, 91.6769, 89.1492, 89.2501, 89.7462, 86.6468, 84.272, 86.7391, 86.0455, 84.1828, 85.7786, 84.7441, 81.685, 83.2837, 81.5256, 78.8935, 81.081, 79.6027, 77.8075, 78.951, 78.1264, 75.7426, 76.4115, 76.5233, 73.1095, 73.9161, 72.5041, 75.0435, 67.9852, 70.9459, 68.5585, 67.9733, 70.0731, 66.2969, 68.7523, 63.8016, 64.0575, 61.856, 60.6108, 60.7896, 59.3159, 59.0828, 54.6566, 59.8493, 55.6232, 57.5134, 52.4113, 53.3819, 56.7103, 49.6771, 47.7571, 48.1986, 48.7459, 48.0969, 48.0135, 44.7155, 41.7229, 42.5019, 44.0462, 41.9194, 37.3248, 39.2516, 40.4504, 40.5975, 37.3108, 35.9992, 32.7488, 32.4254, 32.8496, 32.6312, 31.8525, 29.3797, 27.4934, 27.1888, 25.7645, 27.6203, 22.3531, 24.4994, 24.8639, 25.6741, 22.7127, 23.3354, 20.4761, 19.2128, 18.5869, 21.1729, 19.6715, 18.2247, 21.8179, 16.1187, 16.4585, 15.3666, 13.9663, 17.1842, 15.3981, 10.4846, 11.4476, 12.1715, 12.2036, 8.5246, 6.7012, 6.7812, 9.1095, 8.6562, 8.9433, 6.9051, 5.8775, 4.3536, 7.5765, 7.3528, 8.0228, 7.4758, 5.7806, 7.8886, 5.4791, 4.5325, 4.6041, 4.3902, 1.9226, 5.3308, 5.4177, 4.4673, 3.9292, 5.5684, 7.6181, 5.1537, 4.4098, 4.3803, 5.2803, 3.6266, 5.4958, 5.9564, 8.8337, 7.7048, 8.0844, 5.7283, 8.0876, 5.6791, 8.1818, 8.6878, 7.2758, 11.8101, 10.0672, 6.7866, 10.9138, 9.9362, 11.0309, 12.2276, 12.6332, 9.5251, 11.4007, 14.8689, 16.2509, 17.7599, 18.2328, 13.0839, 17.9767, 14.6192, 20.6006, 19.2619, 17.8867, 23.3443, 22.0405, 18.9967, 23.0459, 22.2944, 24.356, 24.3015, 27.8818, 24.5203, 27.9761, 31.0768, 27.9809, 30.413, 31.2852, 30.8418, 33.7511, 33.8359, 33.1934, 38.1782, 37.6557, 37.157, 37.3981, 38.1276, 42.1066, 41.0012, 42.875, 42.8778, 45.0509, 44.927, 47.2238, 46.782, 49.2815, 50.0269, 49.8251, 49.692, 50.5527, 51.832, 52.4453, 56.1977, 55.8038, 59.2007, 61.2332, 58.8154, 57.4178, 60.1237, 61.5338, 60.3596, 63.156, 64.8952, 64.7018, 65.1571, 66.0826, 70.8036, 68.7784, 68.6581, 70.2193, 73.076, 71.473, 74.0676, 75.2703, 76.1243, 77.9105, 75.7832, 79.0934, 76.9773, 78.3306, 81.4647, 81.6351, 81.1212, 80.0327, 83.3489, 82.2319, 82.447, 83.4998, 85.4645, 82.5194, 86.8312, 87.1227, 86.5393, 89.508, 89.3882, 88.0617, 88.4477, 90.9582, 88.0852, 90.2849, 90.2424, 91.6794, 92.257, 92.3413, 94.3141, 93.2594, 92.7298, 91.6504, 94.7932, 94.7255, 96.3116, 93.1952, 94.5159, 94.527, 94.6011, 94.8443, 92.3318, 96.1946, 95.9691, 96.6957, 98.3637, 94.4787, 94.8494, 94.8434, 97.6458, 92.0182, 95.2049, 92.1101, 90.263, 90.9021, 91.6377, 95.0702, 91.8997, 92.5761, 90.8666, 93.2026, 90.2874, 93.5511, 89.6994, 89.6366, 90.5434, 89.9526, 91.5897, 89.1518, 86.6593, 87.1121, 86.557, 87.9494, 86.8657, 85.5218, 86.3992, 83.6793, 83.6284, 83.4486, 84.7987, 81.672, 80.5919, 78.8328, 80.6996, 78.044, 78.6821, 74.5418, 78.1737, 73.813, 73.8346, 75.7664, 71.3431, 72.3808, 71.7559, 69.2809, 71.9174, 71.266, 65.1662, 65.0473, 67.5221, 63.4364, 63.8818, 63.7261, 63.6301, 61.312, 60.8387, 58.5747, 60.7176, 57.0712, 57.3552, 55.1062, 55.0585, 53.6698, 52.6994, 50.4422, 52.1763, 52.1211, 49.3831, 49.1356, 48.314, 47.47, 45.556, 44.4447, 44.4505, 42.2891, 39.7601, 40.296, 36.4715, 38.3443, 38.0278, 38.3222, 35.7621, 36.0013, 33.6895, 31.244, 29.7593, 29.5276, 28.0478, 30.1719, 28.0441, 28.3555, 26.7654, 27.3876, 26.5896, 23.2211, 22.9796, 21.8065, 19.4015, 22.0874, 22.1126, 19.5888, 18.1421, 19.8166, 13.9762, 17.0887, 16.3821, 14.6717, 16.9926, 15.7552, 13.3183, 13.0081, 12.0018, 11.2792, 9.5667, 13.0988, 12.0893, 11.2818, 7.9992, 12.3374, 11.7812, 8.7075, 6.7033, 6.4142, 8.016, 5.7132, 6.7464, 8.1663, 4.0294, 9.0753, 8.2147, 3.828, 3.4033, 4.9598, 3.7207, 4.7757, 1.2246, 4.6998, 7.715, 3.3251, 4.6011, 2.8084, 6.0537, 4.8333, 8.1786, 5.6952, 4.9655, 6.5091, 5.1053, 4.0577, 6.7425, 6.271, 7.0472, 7.6459, 6.6227, 8.3462, 10.6662, 6.7637, 11.4171, 8.8519, 8.4908, 13.7253, 10.7798, 13.0845, 12.7554, 9.5265, 12.7651, 12.3502, 11.6973, 11.6415, 15.0586, 16.4134, 16.7532, 16.3638, 16.2958, 16.6999, 18.0492, 18.0489, 20.0245, 21.0402, 20.4895, 22.2577, 22.2506, 24.1824, 25.76, 26.0887, 27.3634, 25.022, 27.7875, 29.6364, 31.0588, 28.5852, 32.1152, 34.5889, 33.4224, 34.467, 36.2109, 36.8389, 38.4197, 38.4618, 39.5329, 39.0866, 40.9653, 44.0655, 42.8482, 43.8735, 44.3637, 47.2588, 45.7748, 49.4029, 47.6129, 48.4133, 51.2906, 52.1581, 53.3895, 55.5158, 54.2803, 56.5382, 55.4808, 59.7029, 59.7278, 60.5446, 60.9777, 60.4685, 62.1012, 64.2844, 64.436, 65.5765, 64.27, 67.4924, 67.0857, 67.3928, 69.671, 67.9939, 72.6923, 73.778, 73.2646, 72.6878, 73.5826, 75.5843, 72.9733, 77.665, 79.1632, 78.4576, 78.929, 80.6745, 81.6441, 83.461, 82.534, 82.1428, 83.1409, 84.7449, 87.4291, 85.2205, 84.7112, 85.5567, 84.2716, 88.4473, 86.429, 87.1209, 86.4887, 88.2385, 91.2119, 88.8168, 88.5646, 91.842, 91.4286, 92.9345, 93.7227, 92.9045, 91.2556, 93.281, 94.4608, 93.0588, 91.9791, 95.9703, 93.8534, 94.0012, 94.7565, 96.3745, 95.2991, 94.4573, 96.0125, 98.2205, 97.071, 95.9665, 93.2202, 100.4568, 92.9345, 94.0573, 93.4264, 96.7567, 94.7657, 91.7926, 94.1118, 94.287, 92.7245, 91.087, 91.5243, 91.6309, 91.9745, 90.7947, 92.2918, 89.3589, 87.7622, 88.8064, 91.476, 88.1114, 91.9822, 88.6898, 85.6695, 85.6104, 86.6551, 83.9344, 88.6567, 82.9857, 84.8542, 85.3677, 82.3426, 80.326, 80.7085, 80.9449, 80.9842, 79.0105, 76.0662, 77.4578, 75.5989, 72.5361, 73.9543, 72.0298, 74.2251, 75.4162, 74.4326, 69.9189, 69.2019, 70.051, 69.7155, 66.5926, 66.0958, 68.7013, 64.3036, 62.8038, 62.7722, 62.5164, 59.1634, 59.3672, 57.0295, 57.3968, 59.6609, 56.9863, 54.7602, 52.5223, 52.476, 53.539, 50.1391, 52.1756, 46.9579, 47.6021, 49.671, 43.0662, 46.8836, 41.3493, 43.0193, 41.927, 42.4574, 35.5284, 36.4274, 37.5041, 37.463, 35.1284, 35.2039, 32.8298, 33.0884, 31.5091, 32.2424, 31.8543, 32.2464, 28.2367, 27.8785, 27.5716, 26.2128, 25.7435, 22.6561, 24.7467, 22.0183, 21.1703, 19.4513, 22.8161, 20.1185, 21.3227, 19.2904, 15.6252, 15.8681, 17.9594, 15.0187, 13.8925, 14.6361, 14.0336, 12.1922, 12.6489, 11.8661, 8.1624, 12.283, 9.8118, 12.504, 8.3593, 7.2713, 10.9976, 6.4334, 7.4712, 8.9557, 7.2194, 4.9049, 7.3648, 6.5063, 8.4591, 7.1726, 10.6203, 3.3958, 5.6511, 3.9238, 7.1171, 6.5002, 6.3023, 3.9304, 3.9251, 1.9662, 7.5643, 5.773, 4.6515, 6.4966, 6.2976, 6.7304, 2.9497, 4.453, 5.9768, 6.3978, 7.5025, 4.7767, 6.7242, 10.1058, 8.1206, 8.694, 7.6851, 9.2111, 11.1314, 8.9709, 11.0521, 8.328, 10.9697, 11.9036, 9.9009, 13.1762, 11.0345, 11.376, 13.1364, 16.608, 14.7628, 16.3089, 14.4303, 16.2835, 15.0577, 16.637, 19.4337, 18.8243, 21.7754, 20.0258, 20.7777, 23.7485, 21.6328, 21.1114, 26.141, 25.6206, 22.5737, 26.722, 26.8943, 30.9728, 28.1278, 29.2259, 29.6166, 30.2953, 31.7285, 31.5364, 33.0623, 33.1253, 34.2223, 35.0682, 37.5714, 38.2786, 38.4205, 41.9383, 42.1137, 42.5065, 43.4304, 47.4903, 46.4377, 47.7699, 44.1581, 48.0377, 46.7435, 50.3424, 52.5228, 51.9317, 54.6999, 53.3649, 56.7374, 54.5151, 57.4216, 59.4088, 60.5437, 60.505, 64.5564, 61.9707, 62.8553, 60.3255, 68.0443, 65.7562, 65.4567, 70.105, 70.8711, 70.0655, 68.6263, 72.273, 71.5679, 71.5886, 75.7435, 71.8018, 76.6617, 77.298, 80.4708, 78.6543, 75.8378, 78.4164, 80.4986, 81.6514, 83.291, 79.5669, 82.6826, 85.2876, 86.788, 87.8863, 85.1156, 87.9364, 89.4294, 89.2132, 89.0381, 89.7127, 87.7863, 87.2818, 91.3898, 89.8387, 90.7417, 90.3209, 90.9852, 92.2895, 90.7534, 92.7146, 93.2863, 93.0862, 92.3512, 94.8903, 96.7423, 93.2335, 96.168, 95.8102, 90.6351, 93.5907, 93.875, 96.0763, 95.2399, 95.7009, 95.9544, 93.6409, 93.8373, 93.0693, 94.5734, 94.5539, 94.8718, 93.3853, 95.6761, 95.511, 96.2531, 94.7774, 93.7449, 94.2109, 93.8319, 91.6341, 94.2202, 94.5181, 94.54, 91.2419, 91.2703, 90.9838, 89.9117, 90.3816, 88.7894, 88.1804, 90.5911, 87.6632, 86.9624, 87.613, 85.9264, 85.5322, 84.3767, 82.0022, 83.131, 80.8011, 82.135, 79.3459, 81.7766, 80.7944, 79.3461, 78.0164, 78.0187, 73.6614, 74.1657, 74.7776, 74.6964, 73.2257, 70.9931, 71.8447, 70.0981, 68.3001, 69.5121, 67.8086, 69.0155, 67.308, 66.4929, 64.9473, 62.264, 61.1889, 59.4401, 65.0144, 58.1206, 58.4643, 57.2736, 56.4239, 54.9976, 52.0965, 52.4247, 50.8571, 51.7727, 49.9554, 48.9692, 49.3421, 47.1629, 48.455, 45.4987, 45.4387, 42.1384, 44.1398, 41.5781, 41.8341, 40.7552, 39.044, 38.6793, 36.8297, 38.4874, 36.9367, 35.3328, 31.9201, 31.1303, 30.8806, 30.6147, 30.769, 27.8765, 30.1211, 27.5054, 23.636, 25.1085, 21.1216, 23.0615, 22.5674, 21.6901, 21.3456, 20.4834, 19.4388, 21.8522, 20.7043, 16.4674, 19.3745, 14.3905, 14.9453, 17.8158, 11.5459, 15.1613, 11.8298, 12.9222, 12.3136, 14.5932, 10.3131, 10.9253, 11.4878, 9.7068, 8.4076, 9.1273, 8.9513, 9.7515, 6.6451, 7.0401, 7.8726, 6.832, 6.5198, 6.5078, 5.2458, 4.8671, 6.5258, 4.041, 7.2718, 5.7109, 3.3527, 5.5958, 5.3473, 6.1861, 6.749, 4.4504, 3.9491, 4.1339, 3.6247, 4.0516, 5.6942, 5.4079, 4.7867, 4.5763, 6.3865, 5.3143, 4.7294, 6.3058, 6.401, 5.4777, 8.6289, 8.9829, 8.121, 8.622, 9.6019, 9.1698, 10.9777, 12.5685, 10.668, 11.6892, 12.8391, 11.5403, 10.8914, 14.4972, 11.3568, 16.9824, 16.2108, 15.8095, 16.2439, 19.4496, 16.0743, 16.4399, 17.9847, 19.2057, 18.8197, 21.3053, 22.0374, 21.3849, 25.7956, 22.1009, 23.0843, 26.3857, 26.344, 28.1266, 27.427, 27.6713, 29.1287, 29.9568, 32.6639, 32.0593, 34.8324, 35.4912, 37.0961, 37.8193, 38.5842, 39.5079, 38.5291, 39.8674, 38.4757, 42.6235, 42.1438, 44.7286, 45.8922, 44.0499, 45.5361, 47.5131, 48.2419, 50.2505, 49.2485, 52.0336, 50.4104, 50.6893, 55.974, 53.9157, 56.0057, 55.6881, 56.6658, 59.1415, 60.0807, 63.1207, 63.2666, 63.1401, 65.6013, 67.0657, 66.9267, 66.6113, 69.6515, 71.6706, 70.8938, 73.4347, 73.0344, 73.7733, 71.7095, 72.5082, 74.9264, 73.3068, 75.7195, 78.6953, 77.1688, 79.7252, 77.6437, 79.6611, 82.6532, 82.1326, 82.9418, 85.7346, 85.778, 83.1567, 87.0716, 84.778, 86.2636, 86.8847, 89.0257, 86.2587, 89.1488, 89.7572, 90.67, 89.5999, 91.8644, 89.7165, 92.9096, 92.1029, 89.8402, 92.898, 92.8808, 92.3838, 92.0979, 93.1064, 91.5472, 96.4694, 92.4429, 93.3244, 96.1936, 95.4926, 95.8129, 97.1038, 94.4354, 93.3874, 96.2557, 96.1944, 94.499, 93.0588, 96.7624, 95.6925, 92.6723, 95.7849, 92.3148, 93.5924, 92.4504, 92.9766, 92.4604, 92.5467, 94.2886, 93.3591, 93.555, 93.9247, 91.3813, 91.6944, 91.9962, 93.344, 91.7079, 91.9878, 90.9812, 90.557, 85.794, 89.2739, 87.7355, 86.9432, 85.4991, 85.063, 85.7191, 85.732, 81.5861, 83.5046, 81.6653, 80.3936, 81.707, 79.9085, 78.682, 77.7717, 78.5885, 77.3792, 74.9715, 74.5494, 74.7269, 74.7862, 71.7702, 73.2322, 70.4085, 74.8703, 68.4915, 67.8326, 68.4146, 65.8672, 67.5512, 68.093, 63.8833, 63.7909, 61.8157, 61.6468, 62.8435, 61.0812, 57.4227, 60.133, 58.5886, 56.6032, 53.9102, 54.0206, 51.7499, 52.6643, 50.507, 46.6476, 50.4076, 48.3243, 48.6746, 45.8737, 45.3837, 45.7993, 43.7361, 42.6178, 46.0425, 40.0067, 39.5579, 40.9542, 36.2002, 34.9067, 33.3871, 35.4096, 34.6287, 33.8915, 29.8461, 32.491, 31.8929, 29.0753, 28.4044, 28.5134, 27.2059, 26.7845, 23.3702, 23.9271, 21.5724, 23.5527, 22.6288, 20.9263, 20.7746, 17.2637, 20.1688, 17.4793, 17.6872, 18.4956, 15.0325, 17.3239, 15.0913, 14.3414, 14.5441, 11.2676, 13.475, 12.1396, 13.0834, 10.7036, 10.0023, 10.639, 9.5517, 7.4552, 8.52, 10.3269, 7.92, 6.4081, 8.462, 4.3026, 3.6174, 6.5271, 6.561, 6.3973, 4.5255, 5.4579, 3.4256, 5.7143, 2.8445, 4.9474, 5.4887, 2.4079, 4.227, 3.1822, 4.3244, 0.01, 2.5184, 0.1613, 0.01, 4.4283, 3.0488, 0.8545, 2.4054, 3.0577, 2.3866, 5.5072, 3.0685, 0.01, 1.777, 1.1364, 1.9657, 2.3247, 1.362, 0.7474, 4.4576, 3.348, 1.487, 3.5554, 3.5931, 4.5274, 1.0912, 3.8932, 1.8625, 4.5592, 2.5918, 0.01, 3.0457, 0.3746, 2.7848, 3.0843, 2.632, 1.0673, 1.689, 2.162, 3.1241, 5.4977, 4.6984, 2.9974, 5.6885, 1.7987, 4.9524, 3.7371, 4.4305, 5.1107, 3.2115, 5.5113, 4.375, 8.087, 4.0939, 6.5357, 5.6849, 3.036, 6.9216, 3.3741, 1.7013, 6.4142, 6.8231, 5.3834, 5.0, 7.8534, 6.6323, 4.6676, 6.8357, 3.9606, 5.0743, 4.4233, 2.7872, 4.4085, 8.0951, 4.7019, 5.6104, 4.7806, 7.9069, 6.6964, 7.5165, 6.7072, 5.1942, 5.5744, 8.3752, 7.1167, 8.4474, 2.6242, 9.1149, 6.7898, 10.8703, 6.9243, 7.8116, 8.8376, 6.6103, 9.3091, 7.1073, 10.0829, 9.4121, 9.0378, 7.2789, 8.1192, 8.9536, 5.5211, 7.8098, 10.1095, 6.8638, 10.7469, 7.947, 9.434, 7.2859, 9.7907, 9.8136, 10.878, 11.2569, 11.1569, 9.6393, 7.5343, 11.4053, 7.5079, 8.8488, 10.6537, 10.2528, 12.0148, 9.6552, 7.1604, 9.3151, 10.0199, 9.2618, 11.9335, 9.4688, 7.7099, 10.5856, 8.1837, 12.473, 10.3444, 7.8485, 11.5849, 13.5301, 6.9787, 11.346, 10.7222, 10.2626, 10.515, 10.7369, 8.9567, 12.1079, 7.9605, 12.9141, 12.2573, 8.1742, 9.9311, 12.0529, 9.1687, 9.6418, 9.2601, 11.5914, 8.9033, 9.773, 10.5691, 9.4166, 8.3959, 7.6489, 7.3478, 7.8178, 6.9672, 8.4166, 9.9144, 9.5008, 8.1336, 7.7989, 7.7865, 7.1439, 7.3196, 10.1911, 6.9573, 9.0333, 8.022, 12.5314, 6.133, 9.056, 8.2017, 7.4807, 9.044, 8.7371, 6.8317, 9.0047, 8.8781, 10.1865, 7.2342, 10.2808, 7.7048, 4.9599, 8.6316, 7.6468, 6.3669, 9.0108, 6.8233, 8.9751, 7.244, 8.4112, 8.222, 7.8291, 5.4872, 8.3303, 6.8984, 9.7838, 7.4126, 7.7352, 5.3748, 5.8263, 6.4937, 4.5059, 4.4191, 5.9244, 5.8832, 6.2159, 7.5012, 5.1379, 6.6727, 5.3476, 5.1869, 5.7771, 2.2038, 5.3192, 4.1769, 3.6545, 2.1342, 4.2163, 1.981, 6.0194, 4.273, 2.0271, 3.459, 5.5214, 3.4172, 3.809, 3.5992, 3.8836, 1.4503, 3.8567, 3.0137, 8.2084, 3.3862, 2.9513, 5.0477, 3.2623, 3.8089, 2.0514, 5.6305, 2.2924, 3.7346, 4.8091, 2.5941, 2.9924, 3.8156, 3.9045, 1.1914, 3.0464, 1.3053, 1.5561, 1.6538, 4.4043, 4.9308, 6.4013, 2.3671, 1.1504, 0.9205, 4.75, 0.01, 1.7965, 1.3921, 4.8373, 0.6651, 3.8123, 4.1063, 1.8645, 2.7931, 0.01, 1.9285, 1.724, 0.01, 2.6468, 2.548, 0.01, 0.01, 0.877, 1.2062, 1.5414, 0.5666, 0.4968, 2.475, 1.3109, 1.874, 1.702, 2.7466, 1.8454, 3.3871, 2.2691, 3.4698, 4.0304, 0.01, 3.5953, 4.9155, 0.8132, 2.2567, 1.8029, 3.036, 3.1925, 1.448, 4.4619, 1.2509, 2.3729, 4.1618, 5.6043, 1.9544, 3.9477, 3.1566, 0.5068, 1.503, 1.1855, 2.2959, 2.4854, 3.2135, 5.1505, 3.9314, 7.3422, 3.0637, 4.6802, 4.1866, 5.8946, 3.1376, 5.0456, 6.2944, 2.8437, 3.8877, 4.8325, 3.5008, 2.918, 7.0586, 4.0445, 7.0704, 3.7876, 4.3213, 5.91, 4.4881, 3.5324, 3.8849, 5.4583, 4.1351, 5.3517, 1.9195, 4.5543, 5.2074, 4.7956, 4.161, 4.4131, 5.9313, 8.1433, 3.9024, 5.6729, 7.6401, 6.7633, 6.208, 5.7594, 6.542, 6.4569, 3.4149, 5.7067, 3.9414, 8.8873, 8.2692, 5.937, 8.4101, 10.9587, 6.4335, 9.3987, 8.0745, 7.2559, 6.0316, 6.9353, 7.2546, 4.4503, 8.7957, 7.5925, 8.8381, 7.5934, 12.7917, 5.8793, 7.0355, 9.5615, 12.1089, 7.1488, 11.4462, 7.3905, 10.7685, 9.0025, 12.2941, 11.6803, 8.0926, 13.5231, 7.4872, 8.7553, 11.9885, 8.2237, 8.4115, 9.6156, 10.1428, 10.0877, 8.4295, 9.8828, 10.5814, 11.9172, 10.1878, 7.8486, 9.8014, 8.8568, 11.7934, 7.3271, 10.7033, 8.2873, 11.8133, 11.0799, 10.2682, 10.7109, 9.4605, 10.9899, 9.9103, 11.0882, 10.0841, 6.2773, 9.2295, 12.2753, 12.175, 10.1483, 9.7957, 9.4734, 10.9116, 10.822, 8.4706, 10.9156, 11.7545, 8.4531, 9.5834, 10.5355, 10.899, 9.1569, 8.9658, 9.0322, 10.2734, 10.3049, 9.5961, 7.5412, 7.9131, 10.4621, 7.6325, 9.7592, 8.8324, 8.4225, 9.3167, 11.7403, 9.6066, 8.676, 6.8541, 9.7757, 10.6542, 9.8005, 10.5774, 9.4809, 6.7474, 8.57, 9.3585, 9.5852, 7.6954, 8.2702, 8.8431, 10.1292, 9.6571, 9.0446, 8.5943, 6.386, 6.1956, 7.6314, 9.2528, 8.204, 8.3724, 5.1974, 5.1756, 8.9656, 7.1509, 5.1488, 8.3585, 7.3378, 11.293, 8.6554, 7.2146, 6.3818, 6.8705, 6.2815, 4.1904, 7.6529, 6.5868, 1.9552, 5.0467, 4.6696, 7.2969, 5.6723, 7.8825, 3.1773, 3.8642, 6.9921, 4.3226, 3.6317, 4.3442, 3.9095, 5.7737, 6.5579, 2.4168, 4.2781, 4.6533, 4.6735, 5.7191, 4.5688, 3.4398, 2.563, 1.4159, 3.5194, 4.0216, 5.3075, 3.2841, 7.2633, 3.591, 2.9097, 4.1358, 2.0405, 3.7422, 0.2665, 4.3118, 3.334, 3.4874, 3.3428, 1.1403, 1.6447, 5.2855, 3.6224, 1.9307, 3.4058, 3.335, 5.6058, 4.292, 3.1971, 1.8621, 5.1686, 2.2996, 1.1067, 0.5444, 1.0452, 1.7584, 3.4201, 3.611, 3.9389, 2.4146, 3.407, 5.5253, 3.4801, 4.4991, 0.01, 0.9481, 0.9199, 0.01, 2.1343, 4.1039, 1.2056, 2.297, 0.7199, 4.2624, 5.4387, 3.2492, 6.8574, 2.2931, 5.7508, 4.6478, 7.7574, 6.8264, 2.7384, 2.4331, 4.7876, 5.78, 6.5142, 7.1281, 8.3985, 5.6648, 5.3588, 8.8041, 8.2695, 9.0611, 8.678, 9.8247, 12.7771, 8.594, 9.6907, 13.0098, 14.935, 12.8297, 11.8159, 11.2974, 15.296, 13.654, 19.4306, 20.3349, 17.8331, 18.9084, 18.705, 21.3111, 20.3248, 21.1696, 23.874, 23.545, 26.5875, 21.7338, 24.166, 24.4657, 27.9179, 26.7596, 29.259, 27.4678, 29.9555, 34.4277, 34.334, 29.9614, 34.2372, 35.8486, 34.7951, 34.8147, 38.4007, 38.5044, 40.1329, 40.0231, 44.7177, 40.8151, 42.4104, 44.8986, 46.1986, 44.0099, 49.0028, 45.8499, 49.0279, 49.5395, 49.9202, 53.6627, 49.4226, 52.8258, 53.5449, 57.186, 59.1712, 58.9774, 60.872, 56.403, 60.9413, 59.5723, 62.0299, 63.8988, 64.6067, 67.4545, 63.3418, 65.9671, 65.9027, 66.5596, 71.4117, 71.0523, 73.9794, 74.2778, 73.447, 72.7241, 76.4883, 74.7735, 74.8098, 75.6686, 78.3493, 80.8237, 79.7495, 82.2382, 81.2551, 81.1801, 86.5881, 85.909, 84.1282, 83.2237, 82.6813, 86.3029, 85.9067, 87.5623, 87.9007, 88.607, 90.1844, 89.4425, 88.3675, 88.7597, 91.234, 89.1761, 92.2665, 92.6459, 91.8745, 91.114, 89.9473, 91.2313, 90.7633, 93.5067, 93.047, 92.5523, 95.4442, 94.5103, 94.5476, 95.4522, 96.2872, 92.4245, 95.9637, 92.2438, 93.7977, 96.5182, 96.0261, 95.9543, 95.1768, 96.9482, 92.4213, 94.1573, 94.5473, 97.3693, 95.6752, 95.491, 92.5684, 96.8412, 93.91, 91.4084, 96.1299, 90.1458, 90.6373, 91.2236, 89.7184, 91.5747, 90.7744, 90.0857, 92.2934, 86.5202, 90.5206, 86.7156, 89.6094, 89.7197, 89.7423, 85.4151, 83.3499, 84.9639, 83.7527, 80.5332, 83.6097, 80.4358, 83.2811, 81.8493, 79.2486, 78.9797, 77.8027, 76.7082, 81.2564, 74.4066, 75.0837, 75.6657, 72.7683, 71.5572, 69.6508, 72.5667, 70.971, 69.7227, 65.8604, 67.9761, 66.7377, 64.8838, 62.3997, 63.4467, 61.286, 61.7669, 60.7909, 59.2325, 60.1021, 57.7151, 57.6392, 56.5013, 56.4113, 52.4759, 52.4252, 53.3459, 51.212, 51.6887, 50.1362, 47.3701, 48.3776, 45.6918, 46.5359, 46.907, 44.7918, 45.6201, 38.8936, 39.4377, 38.9046, 37.7527, 37.9664, 35.9161, 37.1944, 36.0862, 34.3105, 31.2609, 32.6975, 31.9936, 30.6278, 29.2663, 30.456, 26.6774, 26.1052, 26.8221, 25.7955, 25.468, 22.965, 20.6337, 19.9771, 20.4255, 21.5181, 20.7868, 16.158, 18.981, 17.3628, 15.2594, 19.4534, 15.9239, 16.1463, 18.1504, 12.8383, 12.543, 14.8174, 10.0859, 11.6399, 11.0982, 12.0026, 10.6926, 8.271, 10.6745, 10.0787, 6.8489, 7.0279, 6.9251, 5.6641, 8.6797, 6.312, 6.1166, 4.733, 5.4749, 8.0921, 6.8061, 3.0976, 3.9004, 6.2209, 4.4241, 4.2665, 3.7521, 3.0141, 5.1429, 4.4403, 6.7534, 4.9963, 3.7235, 6.3082, 7.4042, 4.4201, 3.1298, 5.1462, 4.0418, 8.752, 4.4517, 6.3062, 9.293, 8.695, 6.9433, 6.885, 8.1532, 8.4508, 11.4607, 9.4087, 8.0596, 12.026, 12.5837, 11.1888, 13.2056, 12.6607, 11.328, 13.5884, 12.5821, 13.954, 14.1197, 16.6665, 17.1022, 15.5141, 16.8004, 18.8779, 20.295, 20.4378, 17.7644, 23.7638, 25.2642, 25.7668, 25.0052, 26.0073, 24.8402, 26.9381, 25.8041, 28.5381, 27.0768, 30.9748, 30.4503, 33.027, 33.0531, 33.0009, 35.8741, 33.7751, 36.071, 36.6014, 39.4691, 39.1909, 40.6652, 42.0091, 38.6667, 41.765, 44.3002, 46.6197, 46.9369, 49.023, 47.7047, 49.1694, 49.2503, 50.3282, 50.7172, 52.1282, 53.6363, 53.9217, 55.9135, 54.1176, 58.4561, 59.0452, 60.4091, 60.0006, 60.8845, 64.0658, 63.3, 67.4446, 63.2817, 65.9387, 65.5297, 66.9435, 67.8328, 69.1819, 71.953, 69.9287, 73.415, 71.1835, 73.5702, 76.9804, 76.504, 77.0174, 78.3394, 79.0305, 79.8675, 81.7761, 78.8439, 81.012, 82.7757, 83.6308, 84.0146, 85.7926, 83.7205, 83.0702, 87.6095, 86.2888, 86.0388, 87.4698, 87.3042, 89.9803, 90.3064, 89.9203, 90.7268, 90.4082, 92.3236, 87.644, 89.8223, 91.8805, 91.666, 91.1861, 93.8472, 91.7347, 93.7927, 93.8968, 94.0199, 92.8916, 94.0266, 96.3167, 95.4303, 96.1768, 94.7086, 92.3502, 94.2575, 94.7633, 96.9523, 96.6932, 95.5944, 93.6189, 95.0214, 94.3399, 94.2498, 92.626, 95.0122, 94.0906, 95.1399, 91.518, 91.7762, 98.6717, 91.5972, 93.0432, 92.9428, 90.4671, 94.166, 91.0906, 91.0081, 93.0869, 88.729, 88.7212, 88.4529, 86.4121, 88.3664, 88.1257, 87.1368, 87.2738, 86.9994, 85.6029, 84.1098, 85.6634, 82.1325, 84.6009, 81.5304, 82.2653, 83.1414, 76.2734, 78.6371, 77.5606, 79.9553, 75.9987, 79.9045, 72.7088, 74.7027, 72.7653, 73.2576, 70.7968, 70.1021, 67.1687, 69.1801, 65.8767, 65.2563, 66.44, 65.2089, 66.0054, 61.5021, 63.2238, 62.1306, 60.2423, 58.5343, 58.6604, 59.1401, 56.2849, 57.1446, 54.4883, 56.5092, 52.9833, 51.6996, 48.5654, 47.8593, 49.5903, 47.696, 47.4788, 45.051, 44.8753, 43.1908, 43.5972, 41.8586, 44.0179, 39.2281, 40.9823, 36.7714, 36.7097, 35.2059, 37.4247, 35.2646, 33.896, 33.1309, 30.2498, 33.0865, 32.1813, 29.1699, 28.3754, 28.4737, 26.3923, 25.5213, 24.2601, 23.6702, 22.677, 23.7005, 21.341, 20.432, 19.3892, 17.3492, 21.2222, 18.9431, 18.7934, 16.0277, 18.353, 15.7458, 17.0842, 14.279, 13.643, 12.3462, 12.7001, 12.3849, 13.768, 13.3384, 10.6822, 11.9131, 5.5642, 8.5107, 9.1856, 9.7561, 8.6943, 7.6298, 6.6959, 5.8831, 9.6507, 8.2167, 8.2513, 6.0826, 5.063, 6.5157, 5.4868, 5.1929, 5.2302, 4.2218, 3.7892, 4.6792, 2.9326, 5.8974, 6.2685, 3.8885, 2.3552, 5.7616, 5.6251, 5.4157, 3.5221, 2.807, 8.432, 5.7421, 7.0462, 6.4272, 7.4181, 5.1653, 6.7196, 5.6808, 6.4289, 7.3619, 6.1012, 8.5244, 8.5744, 8.3052, 10.348, 11.0118, 10.2735, 15.0653, 13.6612, 14.8206, 13.2174, 15.6395, 16.0536, 14.0002, 15.1439, 21.1954, 16.8768, 18.9105, 18.56, 20.8455, 18.8376, 19.5666, 23.535, 22.9035, 19.6746, 24.2242, 24.7264, 26.8875, 27.1368, 28.0133, 28.4867, 29.657, 28.3681, 29.7598, 30.5979, 30.7675, 34.8727, 36.2255, 36.4562, 35.5664, 36.602, 37.6933, 40.9735, 41.0502, 43.8293, 40.7315, 42.816, 42.2353, 42.9751, 45.8451, 46.5533, 47.2679, 46.7162, 50.2952, 50.5559, 53.3352, 53.7689, 51.9544, 55.4925, 54.9754, 59.1443, 57.7698, 58.0238, 59.13, 58.4445, 63.5585, 65.7713, 60.9371, 64.0871, 65.2253, 65.4183, 69.0471, 69.9948, 68.6498, 73.0099, 70.8278, 71.2816, 72.9197, 72.2257, 76.3582, 75.9256, 75.2785, 76.3307, 76.0326, 78.5603, 76.985, 79.6753, 79.6258, 81.9687, 83.3837, 83.6868, 82.9936, 82.7684, 84.0225, 85.0699, 86.4328, 85.4377, 85.4109, 87.6763, 89.9908, 91.2795, 90.1609, 87.9673, 92.0284, 89.0908, 89.628, 91.8304, 89.5041, 93.1429, 92.2057, 93.2105, 91.6821, 94.4719, 94.2363, 93.1654, 95.3512, 90.1449, 94.8598, 94.315, 93.4225, 94.9983, 95.5785, 93.7982, 94.7779, 94.9272, 95.5893, 96.8295, 94.2612, 96.879, 92.8724, 95.1837, 92.0356, 94.5839, 95.3997, 97.1698, 94.0074, 92.5879, 95.0064, 93.264, 93.0648, 93.9874, 93.9253, 89.3422, 91.6519, 91.1644, 89.1795, 87.9234, 89.8152, 88.7571, 87.8841, 88.265, 87.4261, 87.4425, 89.227, 86.2448, 88.5215, 86.9609, 85.9234, 82.74, 82.7373, 81.1268, 82.4436, 81.0175, 81.0641, 80.1243, 79.1772, 77.6312, 75.9348, 75.9464, 76.8859, 74.7548, 74.0884, 74.6465, 73.2314, 69.4323, 70.6581, 68.596, 68.9365, 68.709, 67.9849, 68.8054, 64.6397, 64.0224, 64.3928, 64.0353, 60.0997, 61.7259, 60.738, 58.5535, 57.3925, 57.9445, 56.5144, 55.5001, 52.8243, 50.3597, 51.8219, 50.575, 50.6872, 47.8716, 48.9892, 47.6713, 44.9678, 46.5185, 43.6119, 42.1097, 42.5621, 41.1989, 38.9026, 40.2343, 38.3394, 36.2704, 33.8373, 36.1749, 34.7576, 33.8694, 34.8445, 28.1405, 32.886, 32.1427, 27.7512, 29.8775, 26.2821, 25.0914, 25.6694, 27.7408, 24.7316, 23.4658, 23.9343, 20.8997, 23.3208, 22.6854, 20.2423, 17.6995, 19.7882, 17.9357, 17.788, 17.8721, 16.1827, 13.5514, 16.5346, 14.1289, 13.6244, 13.5065, 12.515, 12.6509, 11.325, 10.2809, 9.2592, 8.8737, 8.7839, 10.2951, 7.9201, 7.893, 7.5622, 8.1889, 8.0562, 9.7594, 4.4437, 5.9477, 6.9262, 3.337, 8.2957, 5.3496, 4.194, 6.7236, 1.8742, 5.4147, 3.5556, 4.9883, 5.5611, 6.1995, 5.6598, 8.2259, 5.2642, 4.7546, 7.2242, 5.4258, 6.311, 0.01, 6.7465, 6.1775, 5.881, 5.8132, 8.4375, 4.3256, 12.4376, 9.7908, 8.9801, 11.6615, 9.6281, 8.2983, 11.6251, 8.0932, 11.929, 13.3261, 12.8498, 10.4071, 13.4458, 13.5254, 13.1858, 11.4372, 13.7498, 15.4161, 18.5109, 21.6234, 19.4654, 17.6995, 18.9669, 21.9527, 21.9952, 22.4198, 22.9629, 25.19, 27.543, 25.0137, 26.0597, 27.4118, 26.8068, 25.0666, 29.9619, 28.9966, 32.9571, 32.15, 35.0254, 32.4039, 36.3059, 33.0878, 37.8747, 37.0518, 39.7593, 38.767, 41.2839, 41.9749, 42.7606, 43.8185, 46.647, 44.259, 48.1831, 46.5257, 49.8476, 52.5279, 48.8025, 47.7476, 52.2085, 51.9056, 53.1323, 54.4051, 55.073, 58.9921, 59.5023, 60.5177, 63.208, 59.5397, 57.9017, 65.6276, 63.9075, 64.3813, 62.6865, 64.2822, 68.2586, 67.9089, 65.7885, 68.4923, 72.3524, 73.5625, 72.8212, 77.5958, 75.7186, 77.7161, 77.8109, 77.8558, 75.3855, 75.766, 77.8134, 80.0581, 80.4032, 81.6801, 81.7898, 83.223, 84.6588, 83.8447, 84.04, 81.1629, 87.0092, 85.13, 85.4981, 88.7177, 89.3303, 89.491, 90.4007, 87.8116, 89.5717, 89.5343, 93.3786, 92.4847, 91.2087, 93.2025, 92.8482, 92.4357, 93.6176, 94.4781, 93.2534, 91.8347, 94.4652, 93.7392, 92.5983, 93.3239, 94.2408, 94.7733, 95.6713, 94.5849, 95.632, 94.4292, 95.8185, 95.5939, 95.8109, 97.0594, 94.4045, 92.3426, 94.4982, 95.6904, 94.3538, 94.6125, 91.3493, 92.4592, 94.2747, 94.3689, 91.7916, 93.1624, 91.2197, 90.2117, 91.6811, 91.5146, 91.3784, 91.4543, 92.4312, 90.8758, 88.4299, 89.8806, 85.7513, 87.5672, 88.4421, 87.3088, 86.9433, 87.9599, 83.3609, 85.025, 83.0375, 84.1784, 81.9962, 82.2912, 82.7217, 80.6169, 78.6107, 77.615, 76.3532, 78.1661, 77.7794, 74.6342, 71.4644, 72.3945, 73.151, 70.2243, 67.8409, 69.2364, 65.9575, 68.6118, 66.6191, 66.4001, 67.3359, 63.1029, 60.3099, 62.5498, 62.3503, 58.5516, 59.1871, 58.2583, 57.8559, 55.9223, 59.8689, 54.5053, 54.2018, 52.216, 47.9982, 53.053, 45.2648, 51.0536, 46.055, 45.0185, 45.9146, 48.3948, 44.6057, 42.8676, 41.0342, 42.197, 39.7051, 40.3748, 35.4079, 38.2004, 36.9452, 33.4949, 33.0601, 33.4692, 32.0495, 32.3114, 28.8302, 28.7702, 32.3923, 27.0919, 26.8608, 26.3896, 25.4038, 26.8097, 23.3308, 24.6735, 21.3226, 22.9931, 20.7534, 20.0673, 19.4655, 19.7073, 16.39, 16.0379, 19.8784, 16.9269, 14.9867, 15.8683, 14.2089, 10.3329, 13.3802, 12.4011, 12.5711, 10.3669, 10.6982, 12.2605, 9.8582, 8.9973, 9.7637, 8.2197, 10.0272, 7.7979, 8.2589, 6.332, 5.211, 7.8767, 6.9263, 7.2458, 7.1717, 3.6608, 5.8633, 2.515, 6.164, 3.639, 5.8722, 6.1853, 4.2336, 4.9761, 6.8335, 2.5299, 6.0083, 5.2739, 6.5935, 2.7896, 5.3903, 7.18, 7.7224, 4.7108, 5.6474, 9.0517, 4.4036, 6.7291, 7.3489, 7.6505, 6.3125, 9.5064, 9.7582, 11.5352, 8.0267, 8.9182, 11.7294, 13.2703, 11.0139, 9.2369, 11.7233, 14.0309, 14.1553, 15.3794, 17.1865, 14.2582, 14.1713, 14.3631, 16.6383, 19.0222, 20.771, 19.2101, 19.6205, 20.1301, 22.9141, 20.6904, 22.4483, 23.275, 24.1483, 27.7117, 24.4836, 30.3381, 26.517, 27.1248, 28.23, 31.0701, 30.9611, 33.5582, 31.5437, 31.1805, 34.0527, 35.9549, 34.2636, 37.2479, 39.1565, 38.0941, 39.0242, 39.5782, 41.9707, 43.8389, 48.2477, 46.8488, 44.1854, 44.7517, 47.8717, 51.3763, 50.9857, 50.1907, 53.4653, 55.0092, 56.1146, 53.2994, 56.5298, 54.9238, 56.606, 56.8612, 59.3469, 58.5418, 62.8092, 62.5738, 62.2351, 65.1929, 67.687, 66.8278, 66.3453, 67.6978, 68.8616, 68.8507, 68.2111, 71.0767, 74.3641, 72.1039, 71.283, 74.8675, 77.4652, 74.0253, 77.6793, 78.7837, 79.7307, 80.5062, 81.3138, 78.7422, 82.7439, 84.5726, 82.845, 84.3899, 82.9504, 87.0493, 84.7733, 88.7642, 86.2919, 88.4328, 87.1525, 91.2877, 86.0129, 90.0067, 86.7963, 88.5521, 93.6218, 92.551, 88.5588, 91.9313, 91.3567, 93.4666, 95.6929, 94.1831, 94.1186, 94.4725, 92.2946, 95.187, 95.698, 93.5577, 93.6513, 96.9075, 95.1424, 93.1977, 94.321, 94.303, 94.9032, 94.8802, 94.5833, 97.4146, 96.0772, 96.957, 92.073, 94.643, 96.0785, 95.2235, 92.9143, 92.5764, 94.9067, 92.8835, 93.8897, 92.8468, 92.1097, 92.1211, 90.3302, 93.7408, 91.6061, 92.4583, 89.1217, 88.6419, 88.4923, 87.1786, 88.9698, 88.4849, 86.0921, 85.8105, 86.2658, 83.9659, 83.858, 86.1735, 82.0576, 81.7311, 85.5769, 77.9285, 78.625, 82.3665, 78.3111, 78.9163, 80.5738, 75.5334, 74.9237, 75.6168, 74.0647, 72.5574, 72.3, 69.6523, 71.4773, 71.1547, 68.7756, 67.7879, 68.0439, 65.5024, 64.9287, 64.3623, 65.7398, 62.5185, 61.4763, 60.4496, 59.1641, 57.3317, 56.4355, 58.1361, 55.02, 55.0375, 53.2076, 50.9513, 51.2657, 53.0771, 49.3781, 48.0038, 47.3953, 46.5549, 46.4208, 44.4835, 43.9799, 42.4181, 42.7221, 41.6878, 40.5777, 40.2538, 38.2043, 39.2271, 37.1675, 37.767, 34.4895, 34.0985, 31.756, 31.8998, 32.2092, 29.5488, 31.4596, 28.394, 29.8748, 25.082, 25.4062, 24.2548, 25.705, 24.3542, 22.4911, 21.1497, 21.0343, 21.4163, 20.8521, 18.7925, 17.5096, 17.6467, 17.0164, 16.546, 14.8478, 17.5159, 13.3559, 15.9787, 15.2287, 14.0045, 14.8585, 12.3627, 10.5538, 9.7627, 9.0779, 10.8967, 6.9952, 6.6775, 10.7241, 9.579, 8.3353, 8.7732, 8.2442, 6.5175, 4.3304, 8.2142, 6.736, 3.8003, 5.8971, 4.8206, 5.2119, 4.7755, 5.9981, 4.7837, 3.3104, 6.0202, 2.7287, 0.01, 2.6175, 3.34, 1.7865, 2.3053, 0.8877, 0.01, 2.8435, 1.945, 2.7392, 1.7625, 1.7458, 2.4032, 2.0902, 3.5117, 1.6054, 0.1054, 2.5207, 0.3839, 0.01, 0.7673, 1.7941, 1.2992, 0.2309, 2.2434, 4.4511, 3.9182, 2.7357, 4.1559, 2.166, 1.5575, 3.9535, 1.3673, 3.5519, 3.072, 2.6275, 2.5469, 5.0035, 0.9786, 3.8323, 3.0635, 2.4528, 3.6932, 4.1794, 3.6878, 4.2184, 6.0472, 3.0987, 4.703, 1.5451, 4.9163, 1.5091, 5.3361, 3.7565, 4.7964, 2.4487, 4.7503, 6.0332, 5.8105, 4.9388, 5.0395, 6.8524, 6.3236, 4.3683, 4.5218, 4.4581, 5.5111, 3.9104, 2.5008, 5.4981, 6.2921, 6.2796, 7.7147, 4.2357, 5.4919, 4.185, 6.8042, 6.3652, 5.8873, 6.7568, 5.72, 5.3327, 9.3215, 8.2508, 6.8431, 4.8907, 6.9643, 8.2295, 7.7046, 9.0444, 9.4513, 7.5637, 7.067, 7.1054, 7.3037, 9.3568, 7.4389, 5.628, 8.9197, 8.1459, 7.6645, 5.4898, 10.2588, 9.6157, 6.9321, 8.93, 7.1405, 6.7875, 5.7414, 10.1181, 10.3272, 8.5994, 9.0298, 11.8058, 8.0927, 7.4995, 9.5172, 10.1978, 8.9743, 7.325, 8.3561, 10.5756, 10.6596, 7.1192, 7.8273, 8.2178, 9.6899, 13.069, 9.359, 9.908, 8.6445, 13.7417, 8.9825, 9.1376, 10.1575, 7.9527, 11.1666, 9.9533, 8.7121, 9.0911, 7.1504, 9.1629, 6.5871, 9.3243, 9.2557, 9.1127, 9.1172, 8.7218, 11.8273, 12.1246, 9.6991, 11.6547, 9.4634, 9.4515, 8.6422, 10.9099, 10.7673, 7.8792, 10.0277, 8.9832, 8.3751, 9.657, 6.783, 8.9743, 12.4218, 10.2016, 7.8035, 10.2942, 9.5526, 8.8923, 8.4472, 9.2776, 8.3372, 8.9136, 10.2288, 10.2877, 7.0627, 8.2465, 11.2998, 11.5232, 9.3207, 11.1167, 10.4497, 8.3732, 5.5093, 8.3433, 6.442, 8.4989, 10.8416, 8.5223, 6.8973, 6.246, 4.9795, 4.988, 10.2093, 8.9744, 7.4144, 7.3013, 7.3718, 7.3505, 9.3739, 7.788, 4.1457, 8.6263, 4.056, 6.2565, 4.7013, 6.7551, 4.7228, 4.4554, 4.8657, 7.5693, 5.983, 7.1753, 8.1277, 6.3575, 6.7679, 4.3713, 5.6115, 3.9281, 6.3953, 6.8372, 6.8403, 5.2631, 6.5628, 4.9162, 4.207, 5.7178, 5.9696, 8.1027, 5.8079, 2.9805, 3.0831, 2.5167, 4.5051, 2.66, 6.2743, 3.7157, 5.0387, 4.2275, 4.4406, 2.296, 3.7275, 3.0646, 3.4828, 3.752, 4.5185, 2.7305, 4.598, 3.7915, 5.6921, 0.01, 2.1465, 4.9388, 0.01, 5.1628, 3.0038, 0.01, 3.8626, 1.1445, 1.3049, 4.8234, 2.0, 1.0969, 5.505, 3.8456, 1.9107, 1.1905, 2.0328, 4.6704, 0.7982, 0.3304, 4.1241, 1.7619, 2.3105, 2.9236, 1.5295, 0.01, 1.7586, 3.9223, 5.3052, 1.8574, 1.9808, 4.0634, 2.9021, 2.4469, 0.01, 1.3755, 2.3231, 0.01, 1.4595, 4.578, 1.638, 0.01, 0.01, 2.0438, 1.2103, 0.792, 2.4559, 2.5635, 2.4217, 2.7109, 0.3688, 1.2805, 1.7827, 2.2237, 3.8231, 1.2825, 1.2462, 4.683, 2.7308, 0.4388, 2.1139, 0.7722, 0.9687, 0.722, 1.5803, 5.9162, 4.3962, 5.0083, 4.6241, 2.8486, 3.7157, 3.3258, 1.6318, 1.554, 4.7131, 1.6013, 3.7977, 4.5431, 4.7639, 4.2596, 1.9766, 4.6614, 3.7175, 2.5337, 1.0929, 4.8298, 1.9022, 1.7485, 7.0109, 2.6672, 3.9203, 4.7396, 4.8196, 3.2682, 3.8182, 6.1732, 4.6311, 5.0995, 1.9757, 4.4449, 6.6776, 4.3841, 4.1372, 6.2137, 6.6364, 6.3261, 5.0632, 7.1244, 8.5307, 7.9294, 3.9166, 10.7429, 4.4471, 4.6832, 7.0651, 6.5531, 7.3224, 8.8332, 8.3465, 5.6951, 7.2274, 8.7196, 8.8651, 9.0548, 8.6759, 8.5926, 6.8407, 5.7132, 8.4027, 7.166, 9.7907, 6.6912, 7.5033, 7.5071, 9.6727, 9.4215, 8.3995, 8.8731, 10.9258, 5.9272, 9.7594, 10.3223, 10.5875, 10.0322, 7.7286, 8.1405, 10.0006, 8.1802, 8.822, 6.9155, 7.4371, 9.7966, 8.6869, 8.2354, 9.1379, 9.9162, 9.115, 9.8069, 9.7202, 9.248, 9.6442, 8.3646, 8.9756, 7.0032, 8.0381, 8.0343, 9.2419, 11.5592, 9.8718, 10.1309, 8.5095, 10.3699, 12.4971, 9.8349, 8.7391, 8.236, 10.3858, 8.5842, 11.0691, 8.4815, 7.5149, 10.7161, 8.0509, 10.894, 11.5324, 9.0766, 10.2659, 12.0275, 9.2259, 12.3029, 9.3925, 8.4571, 9.9865, 10.1526, 11.4893, 11.0884, 10.2823, 10.6798, 9.9326, 10.8134, 8.8094, 7.9261, 9.8197, 13.4978, 10.6312, 8.3235, 11.4167, 6.4799, 8.8479, 9.7695, 8.1097, 8.1729, 8.7524, 8.1354, 7.7132, 7.2021, 6.426, 7.2527, 8.4851, 10.0807, 7.5086, 6.6175, 10.7734, 6.5794, 8.3642, 6.7446, 6.9967, 8.5798, 8.6157, 9.7535, 8.7723, 7.9215, 8.5478, 5.9854, 9.2655, 8.1671, 8.0204, 8.1006, 4.8997, 5.3344, 7.1492, 7.0832, 7.6429, 6.8545, 6.3317, 8.4088, 6.9598, 7.4686, 8.0544, 8.0704, 6.5638, 7.0887, 6.3117, 7.4343, 9.1593, 4.084, 4.4354, 7.8534, 5.6707, 4.6606, 4.1784, 6.5404, 5.8898, 7.9763, 4.7439, 6.1495, 7.1951, 2.481, 2.9702, 4.8764, 3.5302, 3.6773, 3.2395, 3.9311, 2.72, 2.0804, 4.5027, 4.038, 5.246, 4.4886, 4.2707, 4.6943, 2.124, 2.6812, 3.7749, 4.7, 4.2038, 2.8536, 2.8311, 3.4257, 1.2581, 4.2087, 4.0389, 4.2201, 4.2644, 4.2202, 0.01, 2.9643, 0.4356, 1.1069, 2.2939, 4.2265, 2.9092, 2.7219, 5.0172, 2.666, 0.8474, 0.1504, 0.9029, 2.353, 0.01, 2.7937, 2.578, 1.0148, 2.2331, 2.8355, 1.0986, 3.1334, 0.9487, 2.8965, 4.195, 2.4869, 0.0907]

requirements.txt 0.1 KB
google-cloud-monitoring==2.31.0
google-cloud-aiplatform==1.160.0
google-auth==2.55.2
requests==2.34.2
scan_duplicates.py 3.7 KB
#!/usr/bin/env python3
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Scans a directory of Terraform files to detect duplicate alert policy targets."""

import argparse
import glob
import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from config_utils import extract_alert_policies  # pytype: disable=import-error  # pyrefly: ignore[missing-import]


def validate_directory_tf_files(
    directory: str, expected_engine_var: str | None = None
) -> dict:
  """Scans and validates all *.tf files in a given directory for duplicates."""
  tf_files = glob.glob(os.path.join(directory, "*.tf"))
  all_errors = []
  all_policies = []
  duplicates = []

  target_map = {}

  for filepath in tf_files:
    filename = os.path.basename(filepath)
    try:
      with open(filepath, "r") as f:
        content = f.read()
    except Exception as e:
      all_errors.append(f"File error in '{filename}': {e}")
      continue

    policies = extract_alert_policies(content)
    for policy in policies:
      policy["filename"] = filename
      all_policies.append(policy)

      engine_key = (
          policy["engine_ids"][0]
          if policy["engine_ids"]
          else expected_engine_var or "default"
      )
      key = (engine_key, policy["signal_type"])

      if key not in target_map:
        target_map[key] = []
      target_map[key].append(policy)

  for (engine, signal_type), matches in target_map.items():
    if len(matches) > 1 and signal_type != "unknown":
      duplicates.append({
          "engine_id": engine,
          "signal_type": signal_type,
          "policies": [
              {
                  "filename": p["filename"],
                  "resource_name": p["resource_name"],
                  "display_name": p["display_name"],
              }
              for p in matches
          ],
      })

  for dup in duplicates:
    policy_list = ", ".join(
        f"'{p['resource_name']}' in '{p['filename']}'" for p in dup["policies"]
    )
    all_errors.append(
        "Duplicate Target Error: Multiple alert policies are targeting the"
        f" same engine '{dup['engine_id']}' and signal '{dup['signal_type']}':"
        f" [{policy_list}]. Please apply the in-place upgrade protocol instead"
        " of appending new blocks!"
    )

  return {
      "valid": len(all_errors) == 0,
      "errors": all_errors,
      "policies_scanned_count": len(all_policies),
      "duplicates_found": duplicates,
  }


def main():
  parser = argparse.ArgumentParser(
      description=(
          "Scans a directory of Terraform files to detect duplicate alert"
          " policy targets."
      )
  )
  parser.add_argument(
      "directory",
      type=str,
      nargs="?",
      default=".",
      help="Directory containing *.tf files to scan.",
  )
  parser.add_argument(
      "--engine-var",
      type=str,
      default="${var.gen_ai_agent_name}",
      help="The expected variable or literal for the agent identifier.",
  )
  args = parser.parse_args()

  results = validate_directory_tf_files(args.directory, args.engine_var)
  print(json.dumps(results, indent=2))
  if not results["valid"]:
    sys.exit(1)


if __name__ == "__main__":
  main()
scan_duplicates_test.py 3.9 KB
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Unit tests for duplicate detection in scan_duplicates."""

import os
import sys
import tempfile
import unittest

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import scan_duplicates  # pytype: disable=import-error  # pyrefly: ignore[missing-import]

class ScanDuplicatesTest(unittest.TestCase):

  def test_validator_detects_duplicates(self):
    with tempfile.TemporaryDirectory() as tmpdir:
      tf_content_1 = """
            resource "google_monitoring_alert_policy" "agent_latency_anomaly_1" {
              display_name = "[Agent Alert] Latency Anomaly - ${var.agent_name}"
              conditions {
                condition_prometheus_query_language {
                  query = "sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count[5m])) by (gen_ai_agent_name)"
                }
              }
            }
            """
      tf_content_2 = """
            resource "google_monitoring_alert_policy" "agent_latency_anomaly_2" {
              display_name = "[Agent Alert] Latency Anomaly - Alternative"
              conditions {
                condition_prometheus_query_language {
                  query = "sum(rate(workload_googleapis_com:gen_ai_invoke_agent_duration_count[5m])) by (gen_ai_agent_name)"
                }
              }
            }
            """
      with open(os.path.join(tmpdir, "policy1.tf"), "w") as f:
        f.write(tf_content_1)
      with open(os.path.join(tmpdir, "policy2.tf"), "w") as f:
        f.write(tf_content_2)

      results = scan_duplicates.validate_directory_tf_files(
          tmpdir, "${var.gen_ai_agent_name}"
      )
      self.assertFalse(results["valid"])
      self.assertEqual(len(results["duplicates_found"]), 1)
      self.assertEqual(results["duplicates_found"][0]["signal_type"], "latency")

  def test_validator_detects_quality_duplicates(self):
    with tempfile.TemporaryDirectory() as tmpdir:
      tf_content_1 = """
            resource "google_monitoring_alert_policy" "q1" {
              display_name = "Quality Alert 1"
              conditions {
                condition_threshold {
                  filter = "resource.type=\\"aiplatform.googleapis.com/OnlineEvaluator\\" AND metric.type=\\"aiplatform.googleapis.com/online_evaluator/scores\\" AND metric.labels.evaluation_metric_name=\\"tool_use_quality_v1\\""
                }
              }
            }
            """
      tf_content_2 = """
            resource "google_monitoring_alert_policy" "q2" {
              display_name = "Quality Alert 2"
              conditions {
                condition_threshold {
                  filter = "resource.type=\\"aiplatform.googleapis.com/OnlineEvaluator\\" AND metric.type=\\"aiplatform.googleapis.com/online_evaluator/scores\\" AND metric.labels.evaluation_metric_name=\\"tool_use_quality_v1\\""
                }
              }
            }
            """
      with open(os.path.join(tmpdir, "policy1.tf"), "w") as f:
        f.write(tf_content_1)
      with open(os.path.join(tmpdir, "policy2.tf"), "w") as f:
        f.write(tf_content_2)

      results = scan_duplicates.validate_directory_tf_files(
          tmpdir, "${var.gen_ai_agent_name}"
      )
      self.assertFalse(results["valid"])
      self.assertEqual(len(results["duplicates_found"]), 1)
      self.assertEqual(
          results["duplicates_found"][0]["signal_type"], "tool_use_quality_v1"
      )


if __name__ == "__main__":
  unittest.main()
scripts/
discover_metric_schema.py 13.1 KB
#!/usr/bin/env python3
"""Universal GCP Metric Schema Discovery & PromQL Validator for Generic Resources.

Queries the Cloud Monitoring v3 API (metricDescriptors and
monitoredResourceDescriptors) to discover exact PromQL metric names, units,
resource grouping labels, metric label keys, and documented label enum values
for any GCP service or custom workload. Optionally validates a PromQL query
against the live schema to catch metric name typos, unit scaling bugs (e.g.,
microseconds 'us' vs milliseconds 'ms'), and invalid label enum comparisons.
"""

import argparse
import json
import re
import subprocess
import sys
from typing import Any, Dict, List, Optional
import urllib.error
import urllib.parse
import urllib.request


def get_access_token() -> str:
  """Retrieves a GCP access token using ADC or gcloud auth."""
  commands = [
      ["gcloud", "auth", "application-default", "print-access-token"],
      ["gcloud", "auth", "print-access-token"],
  ]
  for cmd in commands:
    try:
      result = subprocess.run(
          cmd,
          check=True,
          stdout=subprocess.PIPE,
          stderr=subprocess.PIPE,
          text=True,
      )
      token = result.stdout.strip()
      if token:
        return token
    except subprocess.CalledProcessError:
      continue
  raise RuntimeError(
      "Failed to obtain GCP access token via 'gcloud auth application-default"
      " print-access-token' or 'gcloud auth print-access-token'."
  )


def get_default_project() -> Optional[str]:
  """Retrieves default project ID from gcloud config if not specified."""
  try:
    result = subprocess.run(
        ["gcloud", "config", "get-value", "project"],
        check=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    proj = result.stdout.strip()
    return proj if proj and proj != "(unset)" else None
  except subprocess.CalledProcessError:
    return None


def api_get(url: str, token: str) -> Dict[str, Any]:
  """Performs a GET request against the Cloud Monitoring v3 API."""
  headers = {
      "Authorization": f"Bearer {token}",
      "User-Agent": (
          "agent-skills/1.0 (skill:cloud-monitoring-alert-configuration;"
          " script:discover_metric_schema)"
      ),
  }
  req = urllib.request.Request(url, headers=headers)
  try:
    with urllib.request.urlopen(req, timeout=15) as resp:
      return json.loads(resp.read().decode("utf-8"))
  except urllib.error.HTTPError as e:
    body = e.read().decode("utf-8", errors="replace")
    raise RuntimeError(f"HTTP {e.code} from {url}: {body}") from e


def gcp_metric_to_promql(metric_type: str, value_type: str) -> str:
  """Converts a GCP metric type (<domain>/<path>) to its PromQL equivalent."""
  if "/" not in metric_type:
    return metric_type
  domain, path = metric_type.split("/", 1)
  prom_domain = domain.replace(".", "_")
  prom_path = path.replace(".", "_").replace("/", "_")
  prom_name = f"{prom_domain}:{prom_path}"
  if value_type == "DISTRIBUTION" and not prom_name.endswith("_bucket"):
    prom_name += "_bucket"
  return prom_name


def promql_to_gcp_prefix(promql_metric: str) -> str:
  """Infers a GCP metric domain/prefix from a PromQL metric identifier."""
  if ":" not in promql_metric:
    return promql_metric
  domain_part, path_part = promql_metric.split(":", 1)
  # Strip distribution suffixes for lookup
  for suffix in ("_bucket", "_count", "_sum"):
    if path_part.endswith(suffix):
      path_part = path_part[: -len(suffix)]
      break
  gcp_domain = domain_part.replace("_googleapis_com", ".googleapis.com")
  first_segment = path_part.split("_")[0] if "_" in path_part else path_part
  return f"{gcp_domain}/{first_segment}"


def format_unit_guidance(unit: str) -> str:
  """Returns clear threshold scaling guidance based on the metric unit."""
  if unit == "us":
    return (
        "MICROSECONDS ('us') -> [!] MULTIPLY MILLISECONDS BY 1,000 (e.g., 1s ="
        " 1000000, 100ms = 100000, 1ms = 1000)"
    )
  if unit == "ns":
    return (
        "NANOSECONDS ('ns') -> [!] MULTIPLY MILLISECONDS BY 1,000,000 (e.g., 1s"
        " = 1000000000)"
    )
  if unit == "ms":
    return "Milliseconds ('ms') -> (e.g., 1s = 1000)"
  if unit == "s":
    return "Seconds ('s') -> (e.g., 5 minutes = 300)"
  if unit in ("By", "By/s"):
    return f"Bytes ('{unit}') -> (1 KiB = 1024, 1 MiB = 1048576)"
  if unit in ("1", "10^2.%"):
    return f"Count / Ratio ('{unit}')"
  return f"'{unit}'"


def extract_documented_enums(description: str) -> List[str]:
  """Extracts documented enum values from a label description string."""
  # Match bracketed list e.g. ['success', 'invalid', 'internal']
  bracket_match = re.search(r"\[([^\]]+)\]", description)
  if bracket_match:
    items = re.findall(r"['\"]([^'\"]+)['\"]", bracket_match.group(1))
    if items:
      return items
  # Match parenthetical e.g. (e.g., 'success', 'not_found', 'unavailable')
  quoted = re.findall(r"['\"]([a-zA-Z0-9_\-]+)['\"]", description)
  return list(dict.fromkeys(quoted))


def fetch_resource_descriptor(
    project: str, resource_type: str, token: str
) -> Optional[Dict[str, Any]]:
  """Fetches a monitoredResourceDescriptor from the Cloud Monitoring API."""
  url = (
      f"https://monitoring.googleapis.com/v3/projects/{project}/"
      f"monitoredResourceDescriptors/{resource_type}"
  )
  try:
    return api_get(url, token)
  except RuntimeError:
    return None


def fetch_metric_descriptors(
    project: str,
    token: str,
    resource_type: Optional[str] = None,
    metric_prefix: Optional[str] = None,
) -> List[Dict[str, Any]]:
  """Lists metricDescriptors matching the given resource_type or metric_prefix."""
  filters = []
  if resource_type:
    filters.append(f'resource.type="{resource_type}"')
  if metric_prefix:
    if ":" in metric_prefix:
      metric_prefix = promql_to_gcp_prefix(metric_prefix)
    filters.append(f'metric.type=starts_with("{metric_prefix}")')

  filter_str = " AND ".join(filters)
  params = {"pageSize": "500"}
  if filter_str:
    params["filter"] = filter_str

  query_string = urllib.parse.urlencode(params)
  url = (
      f"https://monitoring.googleapis.com/v3/projects/{project}/"
      f"metricDescriptors?{query_string}"
  )
  data = api_get(url, token)
  return data.get("metricDescriptors", [])


def validate_promql_against_schema(
    promql: str, descriptors: List[Dict[str, Any]]
) -> List[str]:
  """Validates a PromQL expression against discovered metric descriptors."""
  warnings: List[str] = []
  by_prom_name: Dict[str, Dict[str, Any]] = {}
  for d in descriptors:
    mtype = d.get("type", "")
    vtype = d.get("valueType", "")
    pname = gcp_metric_to_promql(mtype, vtype)
    by_prom_name[pname] = d
    # Also register base name without _bucket
    if pname.endswith("_bucket"):
      by_prom_name[pname[:-7]] = d

  # Find all PromQL metric names in the query
  prom_metrics = re.findall(
      r"\b([a-z0-9_]+_googleapis_com:[a-z0-9_]+)\b", promql
  )
  for pm in prom_metrics:
    if pm not in by_prom_name:
      suggestions = [k for k in by_prom_name if pm.split(":")[-1][:8] in k]
      msg = (
          f"[ERROR] PromQL metric '{pm}' does NOT exist in GCP metric"
          " descriptors."
      )
      if suggestions:
        msg += f" Did you mean: {', '.join(sorted(set(suggestions))[:5])}?"
      warnings.append(msg)
      continue

    desc = by_prom_name[pm]
    vtype = desc.get("valueType", "")
    unit = desc.get("unit", "")
    if vtype == "DISTRIBUTION" and not pm.endswith(
        ("_bucket", "_count", "_sum")
    ):
      warnings.append(
          f"[ERROR] Metric '{pm}' has valueType=DISTRIBUTION; in PromQL"
          f" histogram_quantile you must query '{pm}_bucket'."
      )

    # Check threshold magnitude if unit is 'us' or 'ns'
    if unit in ("us", "ns"):
      comp_match = re.search(r"[<>]=?\s*(\d+(?:\.\d+)?)", promql)
      if comp_match:
        val = float(comp_match.group(1))
        if 0 < val < 10000:
          warnings.append(
              f"[WARNING] Metric '{pm}' has unit '{unit}'"
              f" (microseconds/nanoseconds), but threshold is '{val}'. If you"
              " meant milliseconds/seconds, scale accordingly (e.g., 1000ms ="
              " 1000000 us)."
          )

    # Check label matchers
    valid_metric_labels = {
        lbl.get("key", ""): lbl.get("description", "")
        for lbl in desc.get("labels", [])
    }
    # Extract label filters inside { ... } following this metric
    brace_match = re.search(re.escape(pm) + r"\s*\{([^}]+)\}", promql)
    if brace_match:
      matcher_str = brace_match.group(1)
      matchers = re.findall(
          r'([a-zA-Z0-9_]+)\s*(=~|!~|!=|=)\s*"([^"]*)"', matcher_str
      )
      for lkey, op, lval in matchers:
        if lkey in ("project_id", "monitored_resource", "le", "region"):
          continue
        if lkey in valid_metric_labels:
          enums = extract_documented_enums(valid_metric_labels[lkey])
          if enums and op in ("=", "!=") and lval not in enums:
            warnings.append(
                f"[WARNING] Label matcher '{lkey}{op}\"{lval}\"' uses value"
                f" '{lval}', but documented enum values for '{lkey}' are:"
                f" {enums}. Verify casing (e.g., 'success' vs 'OK')."
            )

  return warnings


def main() -> None:
  parser = argparse.ArgumentParser(
      description=(
          "Discovers GCP Metric & Monitored Resource Descriptors and validates"
          " PromQL schema."
      )
  )
  parser.add_argument(
      "--project",
      "-p",
      type=str,
      help="GCP Project ID (defaults to gcloud config project).",
  )
  parser.add_argument(
      "--resource-type",
      "-r",
      type=str,
      help="Monitored resource type (e.g., pubsub_topic, cloudsql_database).",
  )
  parser.add_argument(
      "--metric-prefix",
      "-m",
      type=str,
      help=(
          "Metric type prefix or PromQL name (e.g.,"
          " pubsub.googleapis.com/topic/ or pubsub_googleapis_com:topic_...)."
      ),
  )
  parser.add_argument(
      "--promql",
      "-q",
      type=str,
      help="Optional PromQL query string to validate against the schema.",
  )
  args = parser.parse_args()

  project = args.project or get_default_project()
  if not project:
    print(
        "Error: --project must be specified or configured via gcloud config.",
        file=sys.stderr,
    )
    sys.exit(1)

  if not args.resource_type and not args.metric_prefix and not args.promql:
    parser.error(
        "At least one of --resource-type (-r), --metric-prefix (-m), or"
        " --promql (-q) must be specified."
    )

  token = get_access_token()

  # Infer metric prefix from PromQL if not explicitly provided
  metric_prefix = args.metric_prefix
  if not metric_prefix and args.promql:
    found = re.findall(
        r"\b([a-z0-9_]+_googleapis_com:[a-z0-9_]+)\b", args.promql
    )
    if found:
      metric_prefix = promql_to_gcp_prefix(found[0])

  descriptors = fetch_metric_descriptors(
      project=project,
      token=token,
      resource_type=args.resource_type,
      metric_prefix=metric_prefix,
  )

  print("=" * 80)
  print(f"GCP METRIC & RESOURCE SCHEMA DISCOVERY (Project: {project})")
  print("=" * 80)

  # 1. Discover Monitored Resource Labels
  resource_types = set()
  if args.resource_type:
    resource_types.add(args.resource_type)
  for d in descriptors:
    for rt in d.get("monitoredResourceTypes", []):
      resource_types.add(rt)

  if resource_types:
    print(
        "\n[1] MONITORED RESOURCE TYPES & GROUPING LABELS (for 'sum by (...)')"
    )
    print("-" * 80)
    for rt in sorted(resource_types):
      rdesc = fetch_resource_descriptor(project, rt, token)
      if rdesc:
        rlabels = [lbl.get("key", "") for lbl in rdesc.get("labels", [])]
        print(f"  * Resource Type : {rt}")
        print(f"    Grouping Keys : {', '.join(rlabels)}")
      else:
        print(f"  * Resource Type : {rt}")

  # 2. Print Metric Descriptors Table
  print(f"\n[2] DISCOVERED METRIC DESCRIPTORS ({len(descriptors)} matches)")
  print("-" * 80)
  for d in descriptors:
    mtype = d.get("type", "")
    vtype = d.get("valueType", "")
    mkind = d.get("metricKind", "")
    unit = d.get("unit", "1")
    prom_name = gcp_metric_to_promql(mtype, vtype)
    print(f"  * GCP Metric Type : {mtype}")
    print(f"    PromQL Name     : {prom_name}")
    print(f"    Kind / Type     : {mkind} / {vtype}")
    print(f"    Unit Guidance   : {format_unit_guidance(unit)}")
    labels = d.get("labels", [])
    if labels:
      print("    Metric Labels   :")
      for lbl in labels:
        lkey = lbl.get("key", "")
        ldesc = lbl.get("description", "")
        enums = extract_documented_enums(ldesc)
        enum_str = f" [Documented Enums: {enums}]" if enums else ""
        print(f"      - {lkey}: {ldesc}{enum_str}")
    print()

  # 3. Validate PromQL Query if provided
  if args.promql:
    print("[3] PROMQL SCHEMA & SEMANTIC VALIDATION")
    print("-" * 80)
    print(f"  Query: {args.promql.strip()}\n")
    warnings = validate_promql_against_schema(args.promql, descriptors)
    if warnings:
      for w in warnings:
        print(f"  {w}")
      sys.exit(1)
    else:
      print(
          "  [OK] PromQL metric names, units, and label matchers verified"
          " against live GCP schema!"
      )

  print("=" * 80)


if __name__ == "__main__":
  main()
discover_metric_schema_test.py 10.4 KB
"""Unit tests for discover_metric_schema.py."""

import io
import os
import subprocess
import sys
import unittest
from unittest import mock

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import discover_metric_schema  # pytype: disable=import-error  # pyrefly: ignore[missing-import]

SAMPLE_DESCRIPTORS = [
    {
        "name": (
            "projects/test-proj/metricDescriptors/pubsub.googleapis.com/topic/send_request_count"
        ),
        "type": "pubsub.googleapis.com/topic/send_request_count",
        "metricKind": "DELTA",
        "valueType": "INT64",
        "unit": "1",
        "monitoredResourceTypes": ["pubsub_topic"],
        "labels": [
            {
                "key": "response_class",
                "description": (
                    "A classification group for the response code. It can be"
                    " one of ['success', 'invalid', 'internal']."
                ),
            },
            {
                "key": "response_code",
                "description": (
                    "Operation response code string (e.g., 'success',"
                    " 'not_found', 'unavailable')."
                ),
            },
        ],
    },
    {
        "name": (
            "projects/test-proj/metricDescriptors/pubsub.googleapis.com/topic/send_request_latencies"
        ),
        "type": "pubsub.googleapis.com/topic/send_request_latencies",
        "metricKind": "DELTA",
        "valueType": "DISTRIBUTION",
        "unit": "us",
        "monitoredResourceTypes": ["pubsub_topic"],
        "labels": [
            {
                "key": "response_code",
                "description": (
                    "Operation response code string (e.g., 'success',"
                    " 'not_found', 'unavailable')."
                ),
            },
        ],
    },
]

SAMPLE_RESOURCE_DESCRIPTOR = {
    "type": "pubsub_topic",
    "labels": [
        {"key": "project_id", "description": "GCP project ID."},
        {"key": "topic_id", "description": "Pub/Sub topic ID."},
    ],
}


class DiscoverMetricSchemaTest(unittest.TestCase):

  def test_gcp_metric_to_promql_scalar_and_distribution(self):
    self.assertEqual(
        discover_metric_schema.gcp_metric_to_promql(
            "pubsub.googleapis.com/topic/send_request_count", "INT64"
        ),
        "pubsub_googleapis_com:topic_send_request_count",
    )
    self.assertEqual(
        discover_metric_schema.gcp_metric_to_promql(
            "pubsub.googleapis.com/topic/send_request_latencies", "DISTRIBUTION"
        ),
        "pubsub_googleapis_com:topic_send_request_latencies_bucket",
    )
    # Already has _bucket
    self.assertEqual(
        discover_metric_schema.gcp_metric_to_promql(
            "custom.googleapis.com/my/dist_bucket", "DISTRIBUTION"
        ),
        "custom_googleapis_com:my_dist_bucket",
    )

  def test_promql_to_gcp_prefix(self):
    self.assertEqual(
        discover_metric_schema.promql_to_gcp_prefix(
            "pubsub_googleapis_com:topic_send_request_latencies_bucket"
        ),
        "pubsub.googleapis.com/topic",
    )
    self.assertEqual(
        discover_metric_schema.promql_to_gcp_prefix(
            "cloudsql_googleapis_com:database_cpu_utilization"
        ),
        "cloudsql.googleapis.com/database",
    )

  def test_format_unit_guidance(self):
    us_guidance = discover_metric_schema.format_unit_guidance("us")
    self.assertIn("MICROSECONDS ('us')", us_guidance)
    self.assertIn("MULTIPLY MILLISECONDS BY 1,000", us_guidance)

    ns_guidance = discover_metric_schema.format_unit_guidance("ns")
    self.assertIn("NANOSECONDS ('ns')", ns_guidance)

    ms_guidance = discover_metric_schema.format_unit_guidance("ms")
    self.assertIn("Milliseconds ('ms')", ms_guidance)

    s_guidance = discover_metric_schema.format_unit_guidance("s")
    self.assertIn("Seconds ('s')", s_guidance)

    by_guidance = discover_metric_schema.format_unit_guidance("By")
    self.assertIn("Bytes ('By')", by_guidance)

  def test_extract_documented_enums(self):
    bracket_desc = (
        "A classification group. It can be one of ['success', 'invalid',"
        " 'internal']."
    )
    self.assertEqual(
        discover_metric_schema.extract_documented_enums(bracket_desc),
        ["success", "invalid", "internal"],
    )

    paren_desc = (
        "Status code string (e.g., 'success', 'not_found', 'unavailable')."
    )
    self.assertEqual(
        discover_metric_schema.extract_documented_enums(paren_desc),
        ["success", "not_found", "unavailable"],
    )

    no_enum_desc = "Whether or not the publish contained ordering keys."
    self.assertEqual(
        discover_metric_schema.extract_documented_enums(no_enum_desc), []
    )

  def test_validate_promql_against_schema_valid_query(self):
    valid_query = (
        "histogram_quantile(0.95, sum by (topic_id, le)"
        ' (rate(pubsub_googleapis_com:topic_send_request_latencies_bucket{project_id="p",'
        ' response_code!="success"}[5m]))) > 1000000'
    )
    warnings = discover_metric_schema.validate_promql_against_schema(
        valid_query, SAMPLE_DESCRIPTORS
    )
    self.assertEqual(warnings, [])

  def test_validate_promql_catches_unknown_metric_and_suggests_match(self):
    typo_query = (
        "sum by (topic_id)"
        " (rate(pubsub_googleapis_com:topic_send_latencies_bucket[5m])) >"
        " 1000000"
    )
    warnings = discover_metric_schema.validate_promql_against_schema(
        typo_query, SAMPLE_DESCRIPTORS
    )
    self.assertEqual(len(warnings), 1)
    self.assertIn(
        "[ERROR] PromQL metric"
        " 'pubsub_googleapis_com:topic_send_latencies_bucket' does NOT exist",
        warnings[0],
    )
    self.assertIn("Did you mean:", warnings[0])
    self.assertIn(
        "pubsub_googleapis_com:topic_send_request_latencies_bucket",
        warnings[0],
    )

  def test_validate_promql_catches_missing_bucket_on_distribution(self):
    no_bucket_query = (
        "histogram_quantile(0.95, sum by (topic_id, le)"
        " (rate(pubsub_googleapis_com:topic_send_request_latencies[5m]))) >"
        " 1000000"
    )
    warnings = discover_metric_schema.validate_promql_against_schema(
        no_bucket_query, SAMPLE_DESCRIPTORS
    )
    self.assertEqual(len(warnings), 1)
    self.assertIn("valueType=DISTRIBUTION", warnings[0])
    self.assertIn(
        "pubsub_googleapis_com:topic_send_request_latencies_bucket",
        warnings[0],
    )

  def test_validate_promql_catches_microsecond_unit_trap(self):
    small_threshold_query = (
        "histogram_quantile(0.95, sum by (topic_id, le)"
        " (rate(pubsub_googleapis_com:topic_send_request_latencies_bucket[5m])))"
        " > 1000"
    )
    warnings = discover_metric_schema.validate_promql_against_schema(
        small_threshold_query, SAMPLE_DESCRIPTORS
    )
    self.assertEqual(len(warnings), 1)
    self.assertIn("has unit 'us' (microseconds/nanoseconds)", warnings[0])
    self.assertIn("threshold is '1000.0'", warnings[0])

  def test_validate_promql_catches_invalid_label_enum_casing(self):
    bad_enum_query = (
        "sum by (topic_id)"
        ' (rate(pubsub_googleapis_com:topic_send_request_count{response_code!="OK"}[5m]))'
        " > 5"
    )
    warnings = discover_metric_schema.validate_promql_against_schema(
        bad_enum_query, SAMPLE_DESCRIPTORS
    )
    self.assertEqual(len(warnings), 1)
    self.assertIn("uses value 'OK'", warnings[0])
    self.assertIn("['success', 'not_found', 'unavailable']", warnings[0])

  @mock.patch.object(subprocess, "run")
  def test_get_access_token_success(self, mock_run):
    mock_run.return_value = subprocess.CompletedProcess(
        args=[], returncode=0, stdout="mock-oauth-token\n", stderr=""
    )
    self.assertEqual(
        discover_metric_schema.get_access_token(), "mock-oauth-token"
    )

  @mock.patch.object(discover_metric_schema, "api_get")
  def test_fetch_metric_descriptors_builds_filter(self, mock_api_get):
    mock_api_get.return_value = {"metricDescriptors": SAMPLE_DESCRIPTORS}
    res = discover_metric_schema.fetch_metric_descriptors(
        project="my-proj",
        token="tok",
        resource_type="pubsub_topic",
        metric_prefix="pubsub.googleapis.com/topic/",
    )
    self.assertEqual(res, SAMPLE_DESCRIPTORS)
    called_url = mock_api_get.call_args[0][0]
    self.assertIn("projects/my-proj/metricDescriptors", called_url)
    self.assertIn("pubsub_topic", called_url)

  @mock.patch.object(discover_metric_schema, "get_access_token")
  @mock.patch.object(discover_metric_schema, "fetch_metric_descriptors")
  @mock.patch.object(discover_metric_schema, "fetch_resource_descriptor")
  def test_main_cli_exits_zero_on_valid_promql(
      self, mock_fetch_res, mock_fetch_metrics, mock_token
  ):
    mock_token.return_value = "fake-token"
    mock_fetch_metrics.return_value = SAMPLE_DESCRIPTORS
    mock_fetch_res.return_value = SAMPLE_RESOURCE_DESCRIPTOR

    valid_q = (
        "sum by (topic_id)"
        ' (rate(pubsub_googleapis_com:topic_send_request_count{response_class!="success"}[5m]))'
        " > 0.01"
    )
    test_args = [
        "discover_metric_schema.py",
        "--project=test-proj",
        "--resource-type=pubsub_topic",
        f"--promql={valid_q}",
    ]
    with (
        mock.patch("sys.argv", test_args),
        mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout,
    ):
      discover_metric_schema.main()
      output = mock_stdout.getvalue()
      self.assertIn(
          "[OK] PromQL metric names, units, and label matchers verified", output
      )

  @mock.patch.object(discover_metric_schema, "get_access_token")
  @mock.patch.object(discover_metric_schema, "fetch_metric_descriptors")
  @mock.patch.object(discover_metric_schema, "fetch_resource_descriptor")
  def test_main_cli_exits_one_on_invalid_promql(
      self, mock_fetch_res, mock_fetch_metrics, mock_token
  ):
    mock_token.return_value = "fake-token"
    mock_fetch_metrics.return_value = SAMPLE_DESCRIPTORS
    mock_fetch_res.return_value = SAMPLE_RESOURCE_DESCRIPTOR

    invalid_q = (
        "sum by (topic_id)"
        ' (rate(pubsub_googleapis_com:topic_send_request_count{response_code!="OK"}[5m]))'
        " > 0.01"
    )
    test_args = [
        "discover_metric_schema.py",
        "--project=test-proj",
        f"--promql={invalid_q}",
    ]
    with (
        mock.patch("sys.argv", test_args),
        mock.patch("sys.stdout", new_callable=io.StringIO),
    ):
      with self.assertRaises(SystemExit) as cm:
        discover_metric_schema.main()
      self.assertEqual(cm.exception.code, 1)


if __name__ == "__main__":
  unittest.main()
lint_promql.py 2.5 KB
#!/usr/bin/env python3
"""Generic PromQL Linter for Alerting Policies.

Checks for balanced brackets, valid time windows, and basic syntax issues.
"""

import argparse
import re
import sys


def check_balanced_chars(query, open_char, close_char):
  """Checks if parentheses or braces are balanced."""
  count = 0
  for i, char in enumerate(query):
    if char == open_char:
      count += 1
    elif char == close_char:
      count -= 1
      if count < 0:
        return f"Unbalanced '{close_char}' at position {i}"
  if count != 0:
    return f"Unbalanced '{open_char}' (net count: {count})"
  return None


def lint_query(query):
  """Runs generic sanity checks on a PromQL query."""
  errors = []

  # 1. Balanced parentheses
  paren_err = check_balanced_chars(query, "(", ")")
  if paren_err:
    errors.append(f"Parentheses error: {paren_err}")

  # 2. Balanced curly braces
  brace_err = check_balanced_chars(query, "{", "}")
  if brace_err:
    errors.append(f"Curly braces error: {brace_err}")

  # 3. Time window validations (e.g., [5m], [1w:5m], [3d], [1h])
  window_matches = re.finditer(r"\[([^\]]+)\]", query)
  for match in window_matches:
    window_str = match.group(1)
    if not re.match(r"^\d+[smhdw](:(\d+[smhdw])?)?$", window_str):
      errors.append(
          f"Invalid Prometheus time window/subquery interval: '[{window_str}]'"
      )

  # 4. Lookback offset range validation (e.g. offset 1w, offset 1d)
  offset_matches = re.finditer(r"\boffset\s+(\S+)", query)
  for match in offset_matches:
    offset_str = match.group(1)
    if not re.match(r"^\d+[smhdw]$", offset_str):
      errors.append(f"Invalid lookback offset format: 'offset {offset_str}'")

  return errors


def main():
  parser = argparse.ArgumentParser(description="Lints a PromQL query string.")
  parser.add_argument(
      "query", nargs="?", type=str, help="The PromQL query to lint."
  )
  parser.add_argument(
      "--query",
      dest="query_flag",
      type=str,
      help="The PromQL query to lint (optional flag form).",
  )
  args = parser.parse_args()
  query_str = args.query_flag if args.query_flag is not None else args.query
  if not query_str:
    parser.error(
        "A PromQL query string must be provided positionally or via --query."
    )

  errors = lint_query(query_str)
  if errors:
    print("Linting failed:", file=sys.stderr)
    for err in errors:
      print(f"  - {err}", file=sys.stderr)
    sys.exit(1)
  else:
    print("Linting passed!")
    sys.exit(0)


if __name__ == "__main__":
  main()
scripts/kubernetes/
validate_config.py 9.2 KB
#!/usr/bin/env python3
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""HCL configuration and PromQL validation script for Kubernetes metrics.

Parses Terraform HCL alert policy resource blocks, detects duplicate targets
for Kubernetes resources, and lints Prometheus queries for correct syntax, time
windows, and essential label filters.
"""

import argparse
import glob
import json
import os
import re
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import lint_promql  # pylint: disable=g-import-not-at-top


class PromQLLinter:
  """Linter for PromQL query strings inside Kubernetes alert policies."""

  @staticmethod
  def check_balanced_chars(query, open_char, close_char):
    """Checks if parentheses or braces are balanced via scripts/lint_promql.py."""
    return lint_promql.check_balanced_chars(query, open_char, close_char)

  @staticmethod
  def lint_query(query):
    """Runs generic PromQL checks from lint_promql plus Kubernetes label checks.

    Args:
        query: The PromQL query string to lint.

    Returns:
        A list of string lint error messages. Empty if valid.
    """
    errors = list(lint_promql.lint_query(query))

    # Ensure the query references Kubernetes relevant labels in a label filter
    # or grouping aggregation.
    k8s_labels = [
        "cluster",
        "cluster_name",
        "namespace",
        "namespace_name",
        "pod",
        "pod_name",
        "container",
        "container_name",
        "service",
        "job",
        "node",
        "instance",
    ]

    # Check if any of these labels are present in the query
    has_k8s_reference = any(label in query for label in k8s_labels)

    if not has_k8s_reference:
      errors.append(
          "Query is missing Kubernetes-relevant resource references. It should "
          "reference at least one standard label like 'cluster', 'namespace', "
          "'pod', 'container', 'service', or 'job' in filters or groupings."
      )

    return errors


class HCLScanner:
  """Scanner for HCL alert policies."""

  @staticmethod
  def extract_alert_policies(hcl_content):
    """Extracts resource 'google_monitoring_alert_policy' blocks and metadata."""
    policies = []
    pattern = re.compile(
        r'resource\s+"google_monitoring_alert_policy"\s+"([^"]+)"\s*\{'
    )

    for match in pattern.finditer(hcl_content):
      resource_name = match.group(1)
      start_pos = match.start()

      brace_count = 0
      end_pos = -1
      in_string = False
      escape = False

      for i in range(match.end() - 1, len(hcl_content)):
        char = hcl_content[i]
        if escape:
          escape = False
          continue
        if char == "\\":
          escape = True
          continue
        if char == '"':
          in_string = not in_string
          continue
        if not in_string:
          if char == "{":
            brace_count += 1
          elif char == "}":
            brace_count -= 1
            if brace_count == 0:
              end_pos = i + 1
              break

      if end_pos == -1:
        continue

      block_content = hcl_content[start_pos:end_pos]

      # Extract display_name
      display_name_match = re.search(
          r'display_name\s*=\s*"([^"]+)"', block_content
      )
      display_name = display_name_match.group(1) if display_name_match else ""

      # Extract PromQL queries
      queries = [
          q.group(1)
          for q in re.finditer(
              r"query\s*=\s*<<-?EOT\n(.*?)\n\s*EOT",
              block_content,
              re.DOTALL,
          )
      ]
      if not queries:
        for match in re.finditer(
            r"query\s*=\s*\"((?:[^\"\\]|\\[\s\S])*)\"", block_content
        ):
          raw_query = match.group(1)
          clean_query = re.sub(r"\\+\"", '"', raw_query).replace("\\\\", "\\")
          queries.append(clean_query)

      # Extract threshold filters
      filters = []
      filter_matches = re.finditer(
          r'filter\s*=\s*"((?:[^"\\]|\\.)*)"', block_content
      )
      for f_match in filter_matches:
        filters.append(f_match.group(1))

      # Infer signal type
      signal_type = "unknown"
      res_lower, disp_lower = resource_name.lower(), display_name.lower()
      rules = [
          ("latency", "latency", "latency"),
          ("error", "error", "errors"),
          ("traffic", "traffic", "traffic"),
          ("saturation", "saturation", "saturation"),
          ("cpu", "cpu", "saturation_cpu"),
          ("memory", "memory", "saturation_memory"),
          ("crash", "crash", "health_crashloop"),
          ("ready", "ready", "health_ready"),
      ]
      for res_pat, disp_pat, sig in rules:
        if res_pat in res_lower or disp_pat in disp_lower:
          signal_type = sig
          break

      policies.append({
          "resource_name": resource_name,
          "display_name": display_name,
          "signal_type": signal_type,
          "queries": queries,
          "filters": filters,
          "start_pos": start_pos,
          "end_pos": end_pos,
          "block_content": block_content,
      })

    return policies


def validate_directory_tf_files(directory, expected_cluster_var=None):
  """Scans and validates all *.tf files in a given directory."""
  tf_files = glob.glob(os.path.join(directory, "*.tf"))
  all_errors = []
  all_policies = []
  duplicates = []

  target_map = {}

  for filepath in tf_files:
    filename = os.path.basename(filepath)
    try:
      with open(filepath, "r") as f:
        content = f.read()
    except Exception as e:
      all_errors.append(f"File error in '{filename}': {e}")
      continue

    policies = HCLScanner.extract_alert_policies(content)
    for policy in policies:
      policy["filename"] = filename
      all_policies.append(policy)

      for query in policy["queries"]:
        lint_errs = PromQLLinter.lint_query(query)
        for err in lint_errs:
          all_errors.append(
              f"Lint error in '{filename}' -> resource"
              f" '{policy['resource_name']}': {err}"
          )

      # For duplicates, we check if we have multiple policies of the same signal type
      # in the same directory.
      key = policy["signal_type"]
      if key not in target_map:
        target_map[key] = []
      target_map[key].append(policy)

  for signal_type, matches in target_map.items():
    if len(matches) > 1 and signal_type != "unknown":
      duplicates.append({
          "signal_type": signal_type,
          "policies": [
              {
                  "filename": p["filename"],
                  "resource_name": p["resource_name"],
                  "display_name": p["display_name"],
              }
              for p in matches
          ],
      })

  for dup in duplicates:
    policy_list = ", ".join(
        f"'{p['resource_name']}' in '{p['filename']}'" for p in dup["policies"]
    )
    all_errors.append(
        "Duplicate Target Error: Multiple alert policies are targeting the"
        f" same signal '{dup['signal_type']}': [{policy_list}]."
        " Please merge them or ensure they target different resources/labels."
    )

  return {
      "valid": len(all_errors) == 0,
      "errors": all_errors,
      "policies_scanned_count": len(all_policies),
      "duplicates_found": duplicates,
  }


def main():
  parser = argparse.ArgumentParser(
      description=(
          "Lints HCL alerts and PromQL query targets in Kubernetes tf"
          " templates."
      )
  )
  parser.add_argument(
      "--directory",
      type=str,
      default=".",
      help="Directory containing *.tf files to scan.",
  )
  parser.add_argument(
      "--cluster-var",
      type=str,
      default="${var.cluster_name}",
      help="The expected variable or literal for the cluster name.",
  )
  parser.add_argument(
      "--file",
      type=str,
      help="Validate a single specific HCL file instead of scanning directory.",
  )
  args = parser.parse_args()

  if args.file:
    try:
      with open(args.file, "r") as f:
        content = f.read()
      policies = HCLScanner.extract_alert_policies(content)
      errors = []
      for p in policies:
        for q in p["queries"]:
          errors.extend(PromQLLinter.lint_query(q))
      if errors:
        print(f"Validation failed for '{args.file}':", file=sys.stderr)
        for err in errors:
          print(f"  - {err}", file=sys.stderr)
        sys.exit(1)
      else:
        print(f"Validation passed for '{args.file}'!")
        sys.exit(0)
    except Exception as e:
      print(f"Error reading file '{args.file}': {e}", file=sys.stderr)
      sys.exit(1)

  results = validate_directory_tf_files(args.directory, args.cluster_var)
  print(json.dumps(results, indent=2))
  if not results["valid"]:
    sys.exit(1)


if __name__ == "__main__":
  main()

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