Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install cloud-monitoring-chart-generation@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin cloud-monitoring-chart-generation v1.0.0 follows the Agent Plugins spec.
gh skills-hub install cloud-monitoring-chart-generation Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/cloud-monitoring-chart-generation/ Extract the ZIP to .github/skills/ in your repo. The folder name must match cloud-monitoring-chart-generation for Copilot to auto-discover it.
Skill Files (11)
SKILL.md 10.9 KB
---
name: cloud-monitoring-chart-generation
metadata:
version: "1.0.2"
category: CloudObservabilityAndMonitoring
description: >-
Generates Cloud Monitoring Server-Driven UI (SDUI) Widget and XyChart Protocol
Buffer textprotos on Google Cloud from resolved PromQL or ListTimeSeries
queries.
Use when:
- Generating valid google.monitoring.dashboard.v1.Widget textprotos,
containing PrometheusQuery or TimeSeriesFilter datasets, for use with the Cloud Monitoring
Dashboards API, gcloud CLI, or declarative dashboard definitions.
- Synthesizing Server-Driven UI (SDUI) widget titles, axis labels, and
plot types for Prometheus or ListTimeSeries queries.
Don't use for:
- Metric discovery or PromQL query generation. For those tasks, use the
cloud-monitoring-metric-selection or cloud-monitoring-promql-query skills.
---
# Cloud Monitoring Chart Generation Skill (`cloud-monitoring-chart-generation`)
Transforms PromQL or ListTimeSeries JSON request payloads and metric metadata
into valid Server-Driven UI (SDUI) `google.monitoring.dashboard.v1.Widget`
Protocol Buffer textprotos. These generated textprotos are designed to be
ingested by the Cloud Monitoring Dashboards API, gcloud CLI, or declarative
dashboard provisioning pipelines.
> [!IMPORTANT] **Preferred API & Mutually Exclusive Queries**:
> - **API Preference**: Always prefer generating `ListTimeSeries` (`time_series_filter`) configurations for widgets over PromQL, unless the user explicitly requested PromQL or the metric math strictly requires it.
> - **Mutually Exclusive**: A widget dataset `time_series_query` must contain **EITHER** a `time_series_filter` OR a `prometheus_query`. You must never populate both fields in the same dataset simultaneously.
> - **Strict Passthrough**: You MUST copy the provided PromQL query or ListTimeSeries JSON exact filter string character-for-character. DO NOT invent, rewrite, or modify the queries under any circumstances.
> [!CAUTION] **CRITICAL EXECUTION & WORKING DIRECTORY RULES**:
>
> - **DO NOT CHANGE WORKING DIRECTORY**: Keep your working directory at your
> workspace root. Do NOT `cd` into skill subdirectories.
> - **NO DISCOVERY OR SEARCH RULE**: The metric descriptor, PromQL query,
> ListTimeSeries JSON payload, unit, and resource type are ALWAYS present in
> the conversation context. **NEVER** run file or codebase search tools,
> like grep, find, directory listings, or codebase queries, to discover
> metric metadata or inspect repository structures.
> - **SCRIPT EXECUTION**: Execute the bundled Python scripts directly using
> python3.
> - **OUTPUT GENERATION**: The `assemble_widget_proto` script automatically
> generates a unique UUID-based filename to prevent parallel execution
> collisions. It will print the generated filename to standard error
> strongly prefixed with "Wrote widget textproto to:". You MUST parse this
> exact prefix from the logs to extract the generated path and use it for
> validation in Stage 4.
## Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-monitoring-chart-generation)"`
and append `agent-skills/1.0 (skill:cloud-monitoring-chart-generation)` to `User-Agent` headers.
## Prerequisites: Environment Setup
Install the required dependencies in your environment or sandbox:
```bash
pip install -r scripts/requirements.txt
```
## Follow the workflow pipeline
```
[ Stage 1: compute_labels ] ---> [ Stage 2: LLM Synthesis ] ---> [ Stage 3: assemble_widget_proto ]
Generates candidate labels Formulates SemanticPlotSpec Emits validated widget textproto
```
### Stage 1: Baseline Candidate Synthesis
Run Stage 1 using python3:
```bash
# For PromQL:
python3 scripts/compute_labels.py \
--metric_display_name "METRIC_DISPLAY_NAME" \
--resource_type "RESOURCE_TYPE" \
--metric_unit "UNIT" \
--promql_query 'PROMQL_QUERY'
# For ListTimeSeries:
python3 scripts/compute_labels.py \
--metric_display_name "METRIC_DISPLAY_NAME" \
--resource_type "RESOURCE_TYPE" \
--metric_unit "UNIT" \
--filter_string 'metric.type="m"...' \
--per_series_aligner "ALIGN_RATE" \
--cross_series_reducer "REDUCE_SUM"
```
### Stage 2: SemanticPlotSpec Prediction (LLM)
Review the user prompt, PromQL or LTS query structure, and Stage 1 baseline
candidates to formulate a 4-key `SemanticPlotSpec` JSON object:
1. **`title`**: Polish `titleCandidate` to ensure it is concise, human-readable,
and under 80 characters.
2. **`yAxisLabel`**: Set this to a concise, human-readable quantitative
descriptor or metric concept, like `"Utilization"`, `"Bytes"`, or `"Bytes
Rate"`. Do NOT append unit symbols or suffixes like `"(%)"`, `"(/s)"`, or
`"(By)"` to the label, because units are rendered automatically via
`unitOverride`.
3. **`plotType`**: Default to `LINE`. Use `STACKED_AREA` if requested by the
user or for distribution queries.
4. **`unitOverride`**: Set this to the Unified Code for Units of Measure (UCUM)
unit string, derived by applying the corresponding rules below:
#### List Time Series (LTS) Unit Strategy:
- **Trust the Candidate**: For List Time Series flows, set this directly to
the `unitOverrideCandidate` produced by Stage 1. Stage 1 mathematically
processes `ALIGN_RATE`, for example producing `By/s`, forces `%` for
`ALIGN_PERCENT_CHANGE`, and correctly outputs native normalizations
unconditionally.
#### PromQL Unit Strategy (LLM Manual Override):
Because PromQL expressions can geometrically compose, for example
`histogram_quantile(..., rate(...))`, rely on your own semantic reasoning to
govern the final unit:
- **Rate Functions (`rate(...)`, `irate(...)`)**: Convert cumulative counters
into per-second rates. Append `/s` to the raw metric unit. For example, a
raw metric unit of `By` with `rate(...)` results in `unitOverride: "By/s"`.
- **Exception**: If `rate()` is evaluated inside a `histogram_quantile()`,
the output is the raw bucket unit like `"s"`, not a rate.
- **Ratios & Percentages (`100 * (A / B)`)**: Ratios of identical metric units
typically represent percentages, resulting in `unitOverride: "%"`.
- **Normalizations**: Normalize `10^2.%` to `"%"`.
- **Preserved Units**: For simple aggregation functions like
`avg_over_time(...)` or `sum by (...)`, retain and output the underlying
metric unit without modification.
- **Legend Template**: Do NOT configure the `legend_template` field. It is
intentionally omitted so that the Cloud Monitoring frontend dynamically
renders its multi-column table legend at runtime.
Example `SemanticPlotSpec`:
```json
{
"title": "VM CPU Utilization us-central1-a",
"yAxisLabel": "Utilization",
"plotType": "LINE",
"unitOverride": "%"
}
```
### Stage 3: Protobuf Assembly & Output
Run Stage 3 using python3 to generate and save the widget textproto. Use
`--promql_query` for PromQL, or `--lts_request_json` for ListTimeSeries:
```bash
# For PromQL:
python3 scripts/assemble_widget_proto.py \
--promql_query 'PROMQL_QUERY' \
--spec_json 'SEMANTIC_PLOT_SPEC_JSON'
# For ListTimeSeries:
python3 scripts/assemble_widget_proto.py \
--lts_request_json '{"filter": "...", "aggregation": {...}}' \
--spec_json 'SEMANTIC_PLOT_SPEC_JSON'
```
> [!IMPORTANT] **MANDATORY FILE OUTPUT CONTRACT**: Do not attempt to guess or
> enforce the output filename. The script will automatically generate a
> guaranteed-unique filename and print it to standard error. Search stderr for
> the explicit prefix "Wrote widget textproto to:" to deterministically capture
> this filename, and then target it in Stage 4 validation.
- **Assigned Filename Feedback**: Whenever an output file is saved, the script
logs the file path to stderr. Read your command execution logs for the exact
filename created so you can target it in Stage 4 validation.
- **Text Chat Output**: Enclose the generated SDUI widget textproto inside
a ```` ```textproto```` code block in your response:
```textproto
title: "..."
xy_chart {
...
}
```
### Verify and auto-retry
> [!CAUTION] **DO NOT FINISH YOUR TURN UNTIL FILE VERIFICATION PASSES**: 1.
> **Validate Artifact**: Execute the validator script against the generated file
> output from Stage 3:
>
> ```bash
> # For PromQL charts:
> python3 scripts/validate_chart.py --input_file "GENERATED_FILE.textproto" \
> --expected_promql_substring "SOME_IDENTIFYING_SUBSTRING_FROM_QUERY" \
> --expected_unit_override "UNIT_OVERRIDE_CANDIDATE"
>
> # For ListTimeSeries (LTS) charts:
> python3 scripts/validate_chart.py --input_file "GENERATED_FILE.textproto" \
> --expected_lts_filter_substring "SOME_IDENTIFYING_SUBSTRING_FROM_FILTER" \
> --expected_unit_override "UNIT_OVERRIDE_CANDIDATE"
>
> # ALWAYS provide an identifying substring and the Stage 1 unit override candidate to verify you didn't mutate the data.
> # CRITICAL: If you generated multiple charts for multiple metrics, you MUST run this validation script independently for EACH file generated to ensure every chart is correct!
> ```
>
> 2. **Auto-Retry if Missing or Failed**: If `validate_chart` reports that the
> file is missing or invalid, verify your script parameters and immediately
> re-run Stage 3:
>
> ```bash
> python3 scripts/assemble_widget_proto.py \
> --promql_query 'PROMQL_QUERY' \
> --spec_json 'SEMANTIC_PLOT_SPEC_JSON'
> # Or use --lts_request_json if applicable
> ```
> 3. **Validation & Retries**: Run `validate_chart` to verify the generated
> textproto. If validation fails due to a schema or syntax error, correct
> the parameters and retry up to 2 times. If validation still fails after 2
> retries, stop retrying, notify the user of the validation error, and
> present the best-effort textproto.
> 4. **Execution vs. Validation Errors**: Note that schema/syntax validation
> errors from `validate_chart.py` are distinct from OS or environment
> execution restrictions, which are handled below in **Graceful Sandbox
> Fallback**.
#### Perform graceful sandbox fallback
If `compute_labels.py`, `assemble_widget_proto.py`, or `validate_chart.py`
cannot be executed due to environment or sandbox restrictions, do the
following:
1. Notify the user which script cannot be executed and why.
2. **Synthesize and output the complete widget textproto directly in your
response**, following all formatting and unit rules.
3. Provide a **"Local Verification"** section containing the standalone python3
commands so the user can run and validate the schema locally if desired.
## Supporting Links
- [Dashboards API](https://docs.cloud.google.com/monitoring/dashboards/api-dashboard)
- [Prometheus Docs](https://prometheus.io/docs/prometheus/latest/querying/)
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-monitoring-chart-generation)" \
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-chart-generation)` 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-chart-generation)
```
- **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.
assemble_widget_proto.py 8.2 KB
"""Stage 3: Assembles and validates google.monitoring.dashboard.v1.Widget textproto."""
import argparse
import json
import os
import sys
import uuid
VALID_ALIGNERS = {
"ALIGN_NONE",
"ALIGN_DELTA",
"ALIGN_RATE",
"ALIGN_INTERPOLATE",
"ALIGN_NEXT_OLDER",
"ALIGN_MIN",
"ALIGN_MAX",
"ALIGN_MEAN",
"ALIGN_COUNT",
"ALIGN_SUM",
"ALIGN_STDDEV",
"ALIGN_COUNT_TRUE",
"ALIGN_COUNT_FALSE",
"ALIGN_FRACTION_TRUE",
"ALIGN_PERCENTILE_99",
"ALIGN_PERCENTILE_95",
"ALIGN_PERCENTILE_50",
"ALIGN_PERCENTILE_05",
"ALIGN_PERCENT_CHANGE",
}
VALID_REDUCERS = {
"REDUCE_NONE",
"REDUCE_MEAN",
"REDUCE_MIN",
"REDUCE_MAX",
"REDUCE_SUM",
"REDUCE_STDDEV",
"REDUCE_COUNT",
"REDUCE_COUNT_TRUE",
"REDUCE_COUNT_FALSE",
"REDUCE_FRACTION_TRUE",
"REDUCE_PERCENTILE_99",
"REDUCE_PERCENTILE_95",
"REDUCE_PERCENTILE_50",
"REDUCE_PERCENTILE_05",
}
def format_proto_string(val: str) -> str:
"""Escapes and quotes a string for protobuf text format."""
escaped = val.replace("\\", "\\\\").replace('"', '\\"')
return f'"{escaped}"'
def parse_duration_seconds(duration_str: str) -> int:
"""Robustly parses a time duration string into seconds."""
if not duration_str:
raise ValueError("Empty duration_str provided to parse_duration_seconds")
duration_str = str(duration_str).strip()
try:
if duration_str.endswith("s"):
return int(float(duration_str.rstrip("s")))
if duration_str.endswith("m"):
return int(float(duration_str.rstrip("m")) * 60)
if duration_str.endswith("h"):
return int(float(duration_str.rstrip("h")) * 3600)
if duration_str.endswith("d"):
return int(float(duration_str.rstrip("d")) * 86400)
return int(float(duration_str))
except ValueError:
raise ValueError(f"Unsupported duration format: {duration_str}")
def assemble_widget_textproto(
title: str,
promql_query: str,
lts_filter: dict | None = None,
plot_type: str = "LINE",
y_axis_label: str = "",
unit_override: str = "",
scale: str = "LINEAR",
) -> str:
"""Assembles a valid Widget protobuf textproto string with omitted legend_template."""
clean_title = title.strip()
clean_promql = promql_query.strip()
clean_plot_type = plot_type.strip().upper() if plot_type else "LINE"
clean_scale = scale.strip().upper() if scale else "LINEAR"
if clean_plot_type not in ("LINE", "STACKED_AREA", "STACKED_BAR", "HEATMAP"):
clean_plot_type = "LINE"
lines = [
"widget {",
f" title: {format_proto_string(clean_title)}",
" xy_chart {",
" chart_options {",
" mode: COLOR",
" }",
" data_sets {",
" time_series_query {",
]
if lts_filter:
lines.extend([
" time_series_filter {",
(
" filter:"
f" {format_proto_string(lts_filter.get('filter', ''))}"
),
])
agg = lts_filter.get("aggregation", {})
if agg:
lines.append(" aggregation {")
if "alignmentPeriod" in agg:
secs = parse_duration_seconds(agg["alignmentPeriod"])
lines.extend([
" alignment_period {",
f" seconds: {secs}",
" }",
])
if "perSeriesAligner" in agg:
aligner = agg["perSeriesAligner"]
if aligner not in VALID_ALIGNERS:
raise ValueError(f"Invalid perSeriesAligner: {aligner}")
lines.append(f" per_series_aligner: {aligner}")
if "crossSeriesReducer" in agg:
reducer = agg["crossSeriesReducer"]
if reducer not in VALID_REDUCERS:
raise ValueError(f"Invalid crossSeriesReducer: {reducer}")
lines.append(f" cross_series_reducer: {reducer}")
for gb in agg.get("groupByFields", []):
lines.append(f" group_by_fields: {format_proto_string(gb)}")
lines.append(" }")
lines.append(" }")
else:
lines.append(
f" prometheus_query: {format_proto_string(clean_promql)}"
)
if unit_override and unit_override.strip():
lines.append(
f" unit_override: {format_proto_string(unit_override.strip())}"
)
lines.extend([
" }",
f" plot_type: {clean_plot_type}",
" target_axis: Y1",
" }",
" y_axis {",
])
if y_axis_label and y_axis_label.strip():
lines.append(f" label: {format_proto_string(y_axis_label.strip())}")
lines.extend([
f" scale: {clean_scale}",
" }",
" }",
"}",
])
return "\n".join(lines)
def get_auto_output_path(work_dir: str) -> str:
"""Safely generates a random, parallel-robust filename to avoid race conditions."""
# Adjust for Google3 environments where the agent may run from the CitC client root
# rather than the google3/ directory. This check is safely bypassed in public (GitHub)
# environments because the google3/ directory will not exist. Internally, the workspace
# contains a parent CitC directory (causing flakiness if the agent runs from there). Externally,
# the Git checkout is the true root, so agents won't accidentally run from a parent wrapper.
if not work_dir.endswith("google3") and os.path.basename(work_dir) != "google3":
if os.path.exists(os.path.join(work_dir, "google3")):
work_dir = os.path.join(work_dir, "google3")
while True:
random_id = uuid.uuid4().hex[:8]
candidate = os.path.join(work_dir, f"chart_{random_id}.textproto")
if not os.path.exists(candidate):
return candidate
def main() -> None:
parser = argparse.ArgumentParser(
description="Stage 3 Server-Driven UI (SDUI) widget textproto assembler."
)
parser.add_argument(
"--promql_query", "-q", default="", help="PromQL query expression."
)
parser.add_argument(
"--lts_request_json",
"-l",
default="",
help="ListTimeSeries request JSON.",
)
parser.add_argument("--title", "-t", default="", help="Widget chart title.")
parser.add_argument(
"--plot_type",
"-p",
default="LINE",
help="Plot type (for example: LINE, STACKED_AREA).",
)
parser.add_argument(
"--y_axis_label", "-y", default="", help="Y-axis label string."
)
parser.add_argument(
"--unit_override",
"-u",
default="",
help="Unit override string (for example: '%%', 'By/s').",
)
parser.add_argument(
"--scale", "-s", default="LINEAR", help="Y-axis scale (LINEAR or LOG10)."
)
parser.add_argument(
"--spec_json",
"-j",
default="",
help="JSON string of SemanticPlotSpec from Stage 2.",
)
args = parser.parse_args()
title = args.title
plot_type = args.plot_type
y_axis_label = args.y_axis_label
unit_override = args.unit_override
if args.spec_json:
try:
spec = json.loads(args.spec_json)
if isinstance(spec, dict):
title = spec.get("title", title)
plot_type = spec.get("plotType", plot_type)
y_axis_label = spec.get("yAxisLabel", y_axis_label)
unit_override = spec.get("unitOverride", unit_override)
except Exception:
pass
if not title:
title = "Monitoring Chart"
lts_filter = None
if args.lts_request_json:
try:
lts_filter = json.loads(args.lts_request_json)
except Exception as e:
print(f"ERROR: Failed to parse LTS JSON payload: {e}", file=sys.stderr)
sys.exit(1)
if not lts_filter.get("filter"):
print(
"ERROR: Provided LTS JSON payload is missing the mandatory 'filter'"
" key.",
file=sys.stderr,
)
sys.exit(1)
try:
proto_text = assemble_widget_textproto(
title=title,
promql_query=args.promql_query,
lts_filter=lts_filter,
plot_type=plot_type,
y_axis_label=y_axis_label,
unit_override=unit_override,
scale=args.scale,
)
except ValueError as e:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)
print(proto_text)
work_dir = os.environ.get("BUILD_WORKING_DIRECTORY", os.getcwd())
output_path = get_auto_output_path(work_dir)
with open(output_path, "w", encoding="utf-8") as f:
f.write(proto_text)
print(f"Wrote widget textproto to: {output_path}", file=sys.stderr)
if __name__ == "__main__":
main()
assemble_widget_proto_test.py 1.7 KB
"""Unit tests for assemble_widget_proto.py."""
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from absl.testing import absltest
import assemble_widget_proto # type: ignore[missing-import]
class AssembleWidgetProtoTest(absltest.TestCase):
def test_assemble_widget_textproto_basic(self):
proto_text = assemble_widget_proto.assemble_widget_textproto(
title="VM CPU Utilization",
promql_query='rate(compute_googleapis_com:instance_cpu_utilization[1m])',
plot_type="LINE",
y_axis_label="Utilization (%)",
unit_override="%",
)
self.assertIn('title: "VM CPU Utilization"', proto_text)
self.assertIn('prometheus_query: "rate(compute_googleapis_com:instance_cpu_utilization[1m])"', proto_text)
self.assertIn('unit_override: "%"', proto_text)
self.assertIn("plot_type: LINE", proto_text)
self.assertIn('label: "Utilization (%)"', proto_text)
self.assertNotIn("legend_template:", proto_text)
def test_assemble_widget_textproto_stacked_area(self):
proto_text = assemble_widget_proto.assemble_widget_textproto(
title="Hosts by Region",
promql_query='count by (region) (requests[2m])',
plot_type="STACKED_AREA",
)
self.assertIn("plot_type: STACKED_AREA", proto_text)
self.assertIn("target_axis: Y1", proto_text)
self.assertNotIn("legend_template:", proto_text)
def test_get_auto_output_path(self):
tmp_dir = self.create_tempdir().full_path
path = assemble_widget_proto.get_auto_output_path(tmp_dir)
self.assertTrue(os.path.basename(path).startswith("chart_"))
self.assertTrue(path.endswith(".textproto"))
if __name__ == "__main__":
absltest.main()
compute_labels.py 11.8 KB
"""Stage 1: Generates baseline title and axis labels for SDUI charts."""
import argparse
import json
import re
from typing import Any
# Built-in lookup map covering standard Google Cloud Monitored Resources.
COMMON_RESOURCE_DISPLAY_MAP = {
"gce_instance": "VM Instance",
"gce_disk": "Compute Engine Disk",
"k8s_container": "Kubernetes Container",
"k8s_pod": "Kubernetes Pod",
"k8s_node": "Kubernetes Node",
"k8s_cluster": "Kubernetes Cluster",
"k8s_service": "Kubernetes Service",
"cloudsql_database": "Cloud SQL Database",
"spanner_instance": "Cloud Spanner Instance",
"pubsub_topic": "Cloud Pub/Sub Topic",
"pubsub_subscription": "Cloud Pub/Sub Subscription",
"cloud_run_revision": "Cloud Run Revision",
"cloud_run_job": "Cloud Run Job",
"cloud_function": "Cloud Function",
"cloud_composer_environment": "Cloud Composer Environment",
"cloud_dataproc_cluster": "Cloud Dataproc Cluster",
"cloud_tasks_queue": "Cloud Tasks Queue",
"dataflow_job": "Dataflow Job",
"bigquery_dataset": "BigQuery Dataset",
"bigquery_project": "BigQuery Project",
"bigtable_cluster": "Cloud Bigtable Cluster",
"bigtable_table": "Cloud Bigtable Table",
"filestore_instance": "Filestore Instance",
"gae_app": "GAE Application",
"gae_instance": "GAE Instance",
"gcs_bucket": "GCS Bucket",
"redis_instance": "Memorystore Redis Instance",
"aws_ec2_instance": "AWS EC2 Instance",
"vpn_gateway": "VPN Gateway",
"generic_task": "Generic Task",
"generic_node": "Generic Node",
"global": "Global",
}
# Comprehensive UCUM & SDUI Display Name Mapping Dictionary.
CANONICAL_UNIT_DISPLAY_MAP = {
"1": "",
"%": "Utilization",
"10^2.%": "Utilization",
"By": "Bytes",
"By/s": "Bytes Rate",
"kBy": "Kilobytes",
"MBy": "Megabytes",
"GBy": "Gigabytes",
"s": "Seconds",
"ms": "Milliseconds",
"us": "Microseconds",
"ns": "Nanoseconds",
"1/s": "Operations Rate",
"s/s": "Utilization",
}
# Supported PromQL aggregation operators.
PROMQL_AGGREGATORS = (
"sum",
"avg",
"count",
"min",
"max",
"stddev",
"stdvar",
"topk",
"bottomk",
"count_values",
"quantile",
)
def compute_widget_title(
metric_display_name: str,
resource_type: str | None = None,
filters: dict[str, str] | None = None,
group_by_fields: list[str] | None = None,
aggregation_string: str | None = None,
is_ambiguous_metric_name: bool = False,
custom_resource_display_name: str | None = None,
) -> str:
"""Synthesizes human-readable, 80-char constrained widget titles."""
res_name = custom_resource_display_name or COMMON_RESOURCE_DISPLAY_MAP.get(
resource_type or "", resource_type
)
if res_name and is_ambiguous_metric_name:
descriptor_part = f"{res_name} - {metric_display_name}"
else:
descriptor_part = metric_display_name
filter_part = ""
if filters:
user_filters = [
v
for k, v in filters.items()
if k
not in ("project_id", "resource.type", "resource.labels.project_id")
]
if user_filters:
filter_part = " for " + ", ".join(user_filters[:2])
group_part = ""
if group_by_fields:
cleaned_groups = [
g.replace("metric.label.", "")
.replace("resource.label.", "")
.replace("metric.", "")
.replace("resource.", "")
for g in group_by_fields
]
group_part = " by " + ", ".join(cleaned_groups)
agg_part = f" [{aggregation_string.upper()}]" if aggregation_string else ""
full_title = f"{descriptor_part}{filter_part}{group_part}{agg_part}".strip()
# 80 char threshold & short mode compaction for readability.
if len(full_title) > 80:
if group_part and len(group_part) > 15:
group_part = " (grouped)"
if filter_part and len(filter_part) > 15:
filter_part = " (filtered)"
full_title = f"{descriptor_part}{filter_part}{group_part}{agg_part}".strip()
if len(full_title) > 80:
return full_title[:77] + "..."
return full_title
def normalize_ucum_unit(
raw_unit: str | None, has_rate_aligner: bool = False
) -> str:
"""Normalizes raw UCUM/MetricDescriptor units (e.g.
converting 10^2.% to %, or resolving rate).
"""
if not raw_unit or raw_unit == "{not_a_unit}":
return ""
unit = raw_unit.strip()
unit = re.sub(r"\s+", "", unit)
unit = unit.replace("(rate)", "/s")
if has_rate_aligner and not unit.endswith("/s") and unit != "1/s":
unit = f"{unit}/s" if unit != "1" else "1/s"
unit = re.sub(r"([^\.\/\{\}]+)(\{[^\{\}]+\})", r"\1", unit)
unit = re.sub(r"\{[^\{\}]+\}", "1", unit)
if unit == "10^2.%":
unit = "%"
return unit
def compute_axis_units(
raw_unit: str | None, has_rate_aligner: bool = False
) -> str:
"""Sanitizes raw UCUM/MetricDescriptor units into standard display formats."""
unit = normalize_ucum_unit(raw_unit, has_rate_aligner)
return CANONICAL_UNIT_DISPLAY_MAP.get(unit, unit)
def compute_axis_label(
metric_display_names: list[str],
raw_units: list[str | None],
has_rate_aligners: list[bool] | None = None,
) -> str:
"""Combines quantitative unit scaling and text axis label joining."""
sanitized_units: list[str] = []
for i, u in enumerate(raw_units):
is_rate = has_rate_aligners[i] if has_rate_aligners else False
su = compute_axis_units(u, is_rate)
if su and su not in sanitized_units:
sanitized_units.append(su)
if len(sanitized_units) == 1 and sanitized_units[0] != "":
return sanitized_units[0]
valid_names: list[str] = []
for name in metric_display_names:
clean = name.strip() if name else ""
if clean and clean not in valid_names:
valid_names.append(clean)
if valid_names:
return ", ".join(valid_names)
return "PromQL Metric Axis"
def extract_promql_features(promql_query: str) -> dict[str, Any]:
"""Extracts basic AST characteristics from a PromQL query string."""
query = promql_query.strip()
filters: dict[str, str] = {}
for match in re.finditer(r'(\w+)\s*=\s*(?:"([^"]*)"|\'([^\']*)\')', query):
k = match.group(1)
v = match.group(2) if match.group(2) is not None else match.group(3)
filters[k] = v
# Sanitize query for aggregator detection:
# 1. Remove string literals ("...", '...', `...`)
sanitized = re.sub(
r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|`(?:[^`\\]|\\.)*`', " ", query
)
# 2. Remove template variables (${...}, $var, [[...]])
sanitized = re.sub(
r"\$\{[^}]*\}|\$[a-zA-Z0-9_]+|\[\[[^\]]*\]\]", " ", sanitized
)
# 3. Remove label matcher blocks ({...})
sanitized = re.sub(r"\{[^}]*\}", " ", sanitized)
has_rate = bool(re.search(r"\b(rate|irate)\s*\(", sanitized, re.IGNORECASE))
group_bys: list[str] = []
by_match = re.search(r"\bby\s*\(([^)]+)\)", query, re.IGNORECASE)
if by_match:
group_bys = [g.strip() for g in by_match.group(1).split(",") if g.strip()]
# Find the first aggregator keyword in the sanitized query.
agg_pattern = (
r"\b(" + "|".join(re.escape(a) for a in PROMQL_AGGREGATORS) + r")\b"
)
first_agg: str | None = None
for match in re.finditer(agg_pattern, sanitized, re.IGNORECASE):
start, end = match.span()
# Avoid matching if part of a dotted, colon, or path metric identifier
if start > 0 and sanitized[start - 1] in (":", ".", "/"):
continue
if end < len(sanitized) and sanitized[end] in (":", ".", "/"):
continue
first_agg = match.group(1).upper()
break
if has_rate:
agg = "RATE"
elif first_agg:
agg = first_agg
else:
agg = None
return {
"has_rate": has_rate,
"aggregation": agg,
"group_by_fields": group_bys,
"filters": filters,
}
def extract_filter_features(
filter_str: str, per_series_aligner: str
) -> dict[str, Any]:
"""Extracts characteristics from a ListTimeSeries filter string."""
filters: dict[str, str] = {}
if not filter_str:
return {
"has_rate": False,
"filters": {},
"metric_type": "",
"resource_type": "",
}
for match in re.finditer(
r'([\w\.]+)\s*=\s*(?:"([^"]*)"|\'([^\']*)\')', filter_str
):
k = match.group(1)
v = match.group(2) if match.group(2) is not None else match.group(3)
filters[k] = v
metric_type = filters.pop("metric.type", "")
resource_type = filters.pop("resource.type", "")
has_rate = per_series_aligner == "ALIGN_RATE"
return {
"metric_type": metric_type,
"resource_type": resource_type,
"filters": filters,
"has_rate": has_rate,
}
def main() -> None:
parser = argparse.ArgumentParser(
description="Stage 1 baseline candidate label generator for Server-Driven UI (SDUI) charts."
)
parser.add_argument(
"--user_prompt",
"-p",
default="",
help="Natural language prompt for plot type and polish.",
)
parser.add_argument(
"--metric_type",
"-t",
default="",
help=(
"Metric type (for example:"
" 'compute.googleapis.com/instance/cpu/utilization')."
),
)
parser.add_argument(
"--metric_display_name",
"-m",
default="",
help="Metric display name (for example: 'Disk Read Bytes', 'CPU Utilization').",
)
parser.add_argument(
"--resource_type",
"-r",
default="",
help="Resource type (for example: 'gce_instance', 'k8s_container').",
)
parser.add_argument(
"--metric_unit",
"-u",
default="",
help="Raw metric unit (for example: 'By', 's', '%%').",
)
parser.add_argument(
"--promql_query", "-q", default="", help="PromQL expression."
)
parser.add_argument(
"--filter_string", "-f", default="", help="ListTimeSeries filter string."
)
parser.add_argument(
"--per_series_aligner",
"-a",
default="",
help="ListTimeSeries perSeriesAligner.",
)
parser.add_argument(
"--cross_series_reducer",
"-c",
default="",
help="ListTimeSeries crossSeriesReducer.",
)
parser.add_argument(
"--group_by",
"-g",
nargs="*",
default=None,
help="Optional list of group by fields.",
)
args = parser.parse_args()
promql_info = (
extract_promql_features(args.promql_query) if args.promql_query else {}
)
filter_info = (
extract_filter_features(args.filter_string, args.per_series_aligner)
if args.filter_string
else {}
)
metric_type = args.metric_type or filter_info.get("metric_type", "")
res_type = args.resource_type or filter_info.get("resource_type", "")
metric_name = args.metric_display_name or (
metric_type.split("/")[-1] if metric_type else "Metric Query"
)
group_bys = (
args.group_by
if args.group_by is not None
else promql_info.get("group_by_fields", [])
)
filters = {**filter_info.get("filters", {}), **promql_info.get("filters", {})}
agg = promql_info.get("aggregation", None) or (
args.cross_series_reducer or args.per_series_aligner or None
)
if agg and agg.startswith("REDUCE_"):
agg = agg[len("REDUCE_") :]
elif agg and agg.startswith("ALIGN_"):
agg = agg[len("ALIGN_") :]
has_rate = promql_info.get("has_rate", False) or filter_info.get(
"has_rate", False
)
title_candidate = compute_widget_title(
metric_display_name=metric_name,
resource_type=res_type,
filters=filters,
group_by_fields=group_bys,
aggregation_string=agg,
)
unit_override = normalize_ucum_unit(
args.metric_unit, has_rate_aligner=has_rate
)
if args.per_series_aligner == "ALIGN_PERCENT_CHANGE":
unit_override = "%"
axis_label_candidate = compute_axis_label(
metric_display_names=[metric_name],
raw_units=[args.metric_unit],
has_rate_aligners=[has_rate],
)
result = {
"titleCandidate": title_candidate,
"yAxisLabelCandidate": axis_label_candidate,
"unitOverrideCandidate": unit_override,
}
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()
compute_labels_test.py 6.8 KB
"""Unit tests for compute_labels.py."""
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from absl.testing import absltest
import compute_labels # type: ignore[missing-import]
class ComputeLabelsTest(absltest.TestCase):
def test_compute_widget_title_standard(self):
title = compute_labels.compute_widget_title(
metric_display_name="Disk Read Bytes",
resource_type="gce_instance",
filters={"zone": "us-east1-d"},
group_by_fields=["metric.label.device_name"],
aggregation_string="SUM",
)
self.assertEqual(
title, "Disk Read Bytes for us-east1-d by device_name [SUM]"
)
def test_compute_widget_title_ambiguous(self):
title = compute_labels.compute_widget_title(
metric_display_name="CPU Utilization",
resource_type="gce_instance",
is_ambiguous_metric_name=True,
)
self.assertEqual(title, "VM Instance - CPU Utilization")
def test_common_resource_display_map(self):
self.assertEqual(
compute_labels.COMMON_RESOURCE_DISPLAY_MAP["gce_disk"],
"Compute Engine Disk",
)
self.assertEqual(
compute_labels.COMMON_RESOURCE_DISPLAY_MAP["gae_app"],
"GAE Application",
)
self.assertEqual(
compute_labels.COMMON_RESOURCE_DISPLAY_MAP["cloud_run_job"],
"Cloud Run Job",
)
def test_compute_widget_title_long_truncation(self):
title = compute_labels.compute_widget_title(
metric_display_name=(
"Very Long Metric Display Name That Exceeds Normal Length"
" Constraints Significantly"
),
resource_type="gce_instance",
filters={"zone": "us-central1-a-very-long-filter-name-here"},
group_by_fields=["metric.label.long_group_by_field_name_xyz"],
aggregation_string="RATE",
)
self.assertLessEqual(len(title), 80)
self.assertTrue(title.endswith("..."))
def test_compute_axis_units_ucum(self):
self.assertEqual(
compute_labels.compute_axis_units("10^2.%"), "Utilization"
)
self.assertEqual(
compute_labels.compute_axis_units("By", has_rate_aligner=True),
"Bytes Rate",
)
self.assertEqual(
compute_labels.compute_axis_units("s{CPU}/s"),
"Utilization",
)
def test_compute_axis_label_single_unit(self):
label = compute_labels.compute_axis_label(
metric_display_names=["Disk Read Bytes"],
raw_units=["By"],
has_rate_aligners=[True],
)
self.assertEqual(label, "Bytes Rate")
def test_compute_axis_label_multiple_units_fallback_names(self):
label = compute_labels.compute_axis_label(
metric_display_names=["Disk Read Bytes", "Read Latency"],
raw_units=["By", "ms"],
)
self.assertEqual(label, "Disk Read Bytes, Read Latency")
def test_compute_axis_label_no_unit_metric_name(self):
label = compute_labels.compute_axis_label(
metric_display_names=["Disk Read Bytes"],
raw_units=[None],
)
self.assertEqual(label, "Disk Read Bytes")
def test_compute_axis_label_default_fallback(self):
label = compute_labels.compute_axis_label(
metric_display_names=[],
raw_units=["{not_a_unit}"],
)
self.assertEqual(label, "PromQL Metric Axis")
def test_extract_promql_features_standard(self):
query = (
"sum by (device_name)"
' (rate(compute_googleapis_com:instance_disk_read_bytes_count{zone="us-east1-d"}[1m]))'
)
features = compute_labels.extract_promql_features(query)
self.assertTrue(features["has_rate"])
self.assertEqual(features["aggregation"], "RATE")
self.assertEqual(features["group_by_fields"], ["device_name"])
self.assertEqual(features["filters"], {"zone": "us-east1-d"})
def test_extract_promql_features_aggregators(self):
aggregators_map = {
"sum(metric)": "SUM",
"avg(metric)": "AVG",
"count(metric)": "COUNT",
"min(metric)": "MIN",
"max(metric)": "MAX",
"stddev(metric)": "STDDEV",
"stdvar(metric)": "STDVAR",
"topk(5, metric)": "TOPK",
"bottomk(5, metric)": "BOTTOMK",
'count_values("version", metric)': "COUNT_VALUES",
"quantile(0.9, metric)": "QUANTILE",
}
for query, expected_agg in aggregators_map.items():
features = compute_labels.extract_promql_features(query)
self.assertEqual(
features["aggregation"],
expected_agg,
msg=f"Failed for query: {query}",
)
def test_extract_promql_features_ignore_metric_names_and_templates(self):
query_metric_name = (
"compute_googleapis_com:instance_cpu_maximum_utilization"
)
features1 = compute_labels.extract_promql_features(query_metric_name)
self.assertIsNone(features1["aggregation"])
query_template_and_string = (
'rate(http_requests_total{status="sum", env="${max_var}", label="it\'s'
' a value"}[5m])'
)
features2 = compute_labels.extract_promql_features(
query_template_and_string
)
self.assertTrue(features2["has_rate"])
self.assertEqual(features2["aggregation"], "RATE")
self.assertEqual(
features2["filters"],
{"status": "sum", "env": "${max_var}", "label": "it's a value"},
)
def test_extract_promql_features_first_aggregator_detected(self):
query = "max(sum(metric))"
features = compute_labels.extract_promql_features(query)
self.assertEqual(features["aggregation"], "MAX")
query_with_rate = "max(sum(rate(metric[1m])))"
features_rate = compute_labels.extract_promql_features(query_with_rate)
self.assertEqual(features_rate["aggregation"], "RATE")
def test_compute_widget_title_with_extracted_features(self):
query = (
"sum by (device_name)"
' (rate(compute_googleapis_com:instance_disk_read_bytes_count{zone="us-east1-d"}[1m]))'
)
features = compute_labels.extract_promql_features(query)
title = compute_labels.compute_widget_title(
metric_display_name="Disk Read Bytes",
resource_type="gce_instance",
filters=features["filters"],
group_by_fields=features["group_by_fields"],
aggregation_string=features["aggregation"],
)
self.assertEqual(
title, "Disk Read Bytes for us-east1-d by device_name [RATE]"
)
def test_extract_filter_features(self):
filter_str = (
'metric.type="compute.googleapis.com/instance/cpu/utilization"'
' resource.type="gce_instance" zone="us-central1-a"'
)
features = compute_labels.extract_filter_features(
filter_str, per_series_aligner="ALIGN_RATE"
)
self.assertEqual(
features["metric_type"],
"compute.googleapis.com/instance/cpu/utilization",
)
self.assertEqual(features["resource_type"], "gce_instance")
self.assertEqual(features["filters"], {"zone": "us-central1-a"})
self.assertTrue(features["has_rate"])
if __name__ == "__main__":
absltest.main()
requirements.txt 0.2 KB
# Standard Python 3.10+ library modules used for core scripts (re, json, argparse, sys, typing).
# No external PyPI packages required for runtime execution.
textproto_util.py 8.0 KB
"""Lightweight grammar-based textproto parser and SDUI Widget models."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Aggregation:
alignment_period: dict = field(default_factory=dict)
per_series_aligner: str = ""
cross_series_reducer: str = ""
group_by_fields: list[str] = field(default_factory=list)
@dataclass
class TimeSeriesFilter:
filter: str = ""
aggregation: Aggregation | None = None
@dataclass
class TimeSeriesQuery:
prometheus_query: str = ""
time_series_filter: TimeSeriesFilter | None = None
unit_override: str = ""
@dataclass
class DataSet:
time_series_query: TimeSeriesQuery = field(default_factory=TimeSeriesQuery)
plot_type: str = "LINE"
target_axis: str = "Y1"
@dataclass
class YAxis:
label: str = ""
scale: str = "LINEAR"
@dataclass
class ChartOptions:
mode: str = "COLOR"
@dataclass
class XyChart:
chart_options: ChartOptions = field(default_factory=ChartOptions)
data_sets: list[DataSet] = field(default_factory=list)
y_axis: YAxis = field(default_factory=YAxis)
@dataclass
class Widget:
title: str = ""
xy_chart: XyChart | None = None
def HasField(self, field_name: str) -> bool:
return getattr(self, field_name, None) is not None
def tokenize_textproto(text: str) -> list[tuple[str, str]]:
"""Tokenizes textproto string into (token_type, value) tuples."""
tokens = []
i = 0
n = len(text)
while i < n:
c = text[i]
if c.isspace():
i += 1
continue
if c == "#":
while i < n and text[i] != "\n":
i += 1
continue
if c in ("{", "}", ":", ";", ","):
if c in ("{", "}", ":"):
tokens.append((c, c))
i += 1
continue
if c in ('"', "'"):
quote = c
j = i + 1
val_chars = []
while j < n and text[j] != quote:
if text[j] == "\\" and j + 1 < n:
val_chars.append(text[j + 1])
j += 2
else:
val_chars.append(text[j])
j += 1
tokens.append(("STR", "".join(val_chars)))
i = j + 1
continue
j = i
while (
j < n
and not text[j].isspace()
and text[j] not in ("{", "}", ":", ";", ",", "#")
):
j += 1
tokens.append(("SYM", text[i:j]))
i = j
return tokens
def parse_textproto_tokens(
tokens: list[tuple[str, str]], idx: int = 0
) -> tuple[dict[str, Any], int]:
"""Parses token stream into a nested dictionary structure similar to json.loads."""
obj: dict[str, Any] = {}
n = len(tokens)
while idx < n:
ttype, tval = tokens[idx]
if ttype == "}":
return obj, idx + 1
if ttype == "SYM":
key = tval
idx += 1
if idx < n and tokens[idx][0] == ":":
idx += 1
if idx < n and tokens[idx][0] == "{":
nested_obj, idx = parse_textproto_tokens(tokens, idx + 1)
val = nested_obj
elif idx < n and tokens[idx][0] in ("STR", "SYM"):
val = tokens[idx][1]
idx += 1
else:
continue
if key in obj:
if not isinstance(obj[key], list):
obj[key] = [obj[key]]
obj[key].append(val)
else:
obj[key] = val
else:
idx += 1
return obj, idx
def dict_to_widget(data: dict[str, Any]) -> Widget:
"""Converts a parsed textproto dictionary into a structured Widget hierarchy, enforcing strict field boundaries."""
if "widget" in data and isinstance(data["widget"], dict):
# Only allow "widget" or expected fields at the top level
if set(data.keys()) - {"widget"} != set():
bad_keys = set(data.keys()) - {"widget"}
raise ValueError(f"Unknown properties at top level: {bad_keys}")
data = data["widget"]
expected_widget_keys = {"title", "xy_chart"}
bad_widget_keys = set(data.keys()) - expected_widget_keys
if bad_widget_keys:
raise ValueError(f"Unknown properties in Widget: {bad_widget_keys}")
title = str(data.get("title", ""))
xy_data = data.get("xy_chart")
if not xy_data or not isinstance(xy_data, dict):
return Widget(title=title, xy_chart=None)
expected_xy_keys = {"chart_options", "data_sets", "y_axis"}
bad_xy_keys = set(xy_data.keys()) - expected_xy_keys
if bad_xy_keys:
raise ValueError(f"Unknown properties in xy_chart: {bad_xy_keys}")
opts_data = xy_data.get("chart_options", {})
if isinstance(opts_data, dict):
bad_opts_keys = set(opts_data.keys()) - {"mode"}
if bad_opts_keys:
raise ValueError(f"Unknown properties in chart_options: {bad_opts_keys}")
mode = (
str(opts_data.get("mode", "COLOR"))
if isinstance(opts_data, dict)
else "COLOR"
)
chart_options = ChartOptions(mode=mode)
yaxis_data = xy_data.get("y_axis", {})
if isinstance(yaxis_data, dict):
bad_yaxis_keys = set(yaxis_data.keys()) - {"label", "scale"}
if bad_yaxis_keys:
raise ValueError(f"Unknown properties in y_axis: {bad_yaxis_keys}")
label = str(yaxis_data.get("label", ""))
scale = str(yaxis_data.get("scale", "LINEAR"))
else:
label, scale = "", "LINEAR"
y_axis = YAxis(label=label, scale=scale)
raw_ds_list = xy_data.get("data_sets", [])
if isinstance(raw_ds_list, dict):
raw_ds_list = [raw_ds_list]
elif not isinstance(raw_ds_list, list):
raw_ds_list = []
data_sets: list[DataSet] = []
for ds_dict in raw_ds_list:
if not isinstance(ds_dict, dict):
continue
bad_ds_keys = set(ds_dict.keys()) - {"time_series_query", "plot_type", "target_axis"}
if bad_ds_keys:
raise ValueError(f"Unknown properties in data_sets: {bad_ds_keys}")
ts_dict = ds_dict.get("time_series_query", {})
ts_filter = None
if isinstance(ts_dict, dict):
bad_ts_keys = set(ts_dict.keys()) - {"prometheus_query", "time_series_filter", "unit_override"}
if bad_ts_keys:
raise ValueError(f"Unknown properties in time_series_query: {bad_ts_keys}")
promql = str(ts_dict.get("prometheus_query", ""))
unit = str(ts_dict.get("unit_override", ""))
ts_filter_dict = ts_dict.get("time_series_filter")
if isinstance(ts_filter_dict, dict):
bad_lts_keys = set(ts_filter_dict.keys()) - {"filter", "aggregation"}
if bad_lts_keys:
raise ValueError(f"Unknown properties in time_series_filter: {bad_lts_keys}")
agg_dict = ts_filter_dict.get("aggregation", {})
agg_obj = None
if isinstance(agg_dict, dict) and agg_dict:
bad_agg_keys = set(agg_dict.keys()) - {"alignment_period", "per_series_aligner", "cross_series_reducer", "group_by_fields"}
if bad_agg_keys:
raise ValueError(f"Unknown properties in aggregation: {bad_agg_keys}")
group_by = agg_dict.get("group_by_fields", [])
if isinstance(group_by, str):
group_by = [group_by]
agg_obj = Aggregation(
alignment_period=agg_dict.get("alignment_period", {}),
per_series_aligner=str(agg_dict.get("per_series_aligner", "")),
cross_series_reducer=str(
agg_dict.get("cross_series_reducer", "")
),
group_by_fields=group_by,
)
ts_filter = TimeSeriesFilter(
filter=str(ts_filter_dict.get("filter", "")), aggregation=agg_obj
)
else:
promql, unit = "", ""
ts_query = TimeSeriesQuery(
prometheus_query=promql,
time_series_filter=ts_filter,
unit_override=unit,
)
plot_type = str(ds_dict.get("plot_type", "LINE"))
target_axis = str(ds_dict.get("target_axis", "Y1"))
data_sets.append(
DataSet(
time_series_query=ts_query,
plot_type=plot_type,
target_axis=target_axis,
)
)
xy_chart = XyChart(
chart_options=chart_options,
data_sets=data_sets,
y_axis=y_axis,
)
return Widget(title=title, xy_chart=xy_chart)
def parse_and_validate_widget(text: str) -> Widget:
"""Parses a textproto string into a Widget message hierarchy."""
tokens = tokenize_textproto(text)
raw_dict, _ = parse_textproto_tokens(tokens)
return dict_to_widget(raw_dict)
textproto_util_test.py 10.0 KB
"""Comprehensive unit tests for textproto_util.py."""
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from absl.testing import absltest
from dataclasses import asdict
import textproto_util # type: ignore[missing-import]
class TextprotoUtilTest(absltest.TestCase):
def test_tokenize_basic(self):
text = 'widget { title: "Hello World" }'
tokens = textproto_util.tokenize_textproto(text)
self.assertEqual(
tokens,
[
("SYM", "widget"),
("{", "{"),
("SYM", "title"),
(":", ":"),
("STR", "Hello World"),
("}", "}"),
],
)
def test_tokenize_with_comments(self):
text = """
# This is a comment
widget { # inline comment
title: "Test" # another comment
}
"""
tokens = textproto_util.tokenize_textproto(text)
self.assertEqual(
tokens,
[
("SYM", "widget"),
("{", "{"),
("SYM", "title"),
(":", ":"),
("STR", "Test"),
("}", "}"),
],
)
def test_tokenize_escaped_strings(self):
text = 'title: "Line 1 \\"quoted\\" \\\\ path"'
tokens = textproto_util.tokenize_textproto(text)
self.assertEqual(
tokens,
[
("SYM", "title"),
(":", ":"),
("STR", 'Line 1 "quoted" \\ path'),
],
)
def test_parse_textproto_tokens_nested(self):
text = """
xy_chart {
chart_options {
mode: COLOR
}
y_axis {
label: "Utilization"
scale: LINEAR
}
}
"""
tokens = textproto_util.tokenize_textproto(text)
obj, _ = textproto_util.parse_textproto_tokens(tokens)
self.assertEqual(
obj,
{
"xy_chart": {
"chart_options": {"mode": "COLOR"},
"y_axis": {"label": "Utilization", "scale": "LINEAR"},
}
},
)
def test_parse_textproto_repeated_fields(self):
text = """
data_sets { plot_type: LINE }
data_sets { plot_type: STACKED_AREA }
"""
tokens = textproto_util.tokenize_textproto(text)
obj, _ = textproto_util.parse_textproto_tokens(tokens)
self.assertIsInstance(obj["data_sets"], list)
self.assertEqual(len(obj["data_sets"]), 2)
self.assertEqual(obj["data_sets"][0]["plot_type"], "LINE")
self.assertEqual(obj["data_sets"][1]["plot_type"], "STACKED_AREA")
def test_parse_and_validate_widget_wrapped(self):
text = """
widget {
title: "CPU Utilization"
xy_chart {
chart_options { mode: COLOR }
data_sets {
time_series_query {
prometheus_query: "avg(cpu)"
unit_override: "%"
}
plot_type: LINE
target_axis: Y1
}
y_axis {
label: "CPU (%)"
scale: LINEAR
}
}
}
"""
widget = textproto_util.parse_and_validate_widget(text)
self.assertEqual(widget.title, "CPU Utilization")
self.assertTrue(widget.HasField("xy_chart"))
self.assertIsNotNone(widget.xy_chart)
assert widget.xy_chart is not None
self.assertEqual(widget.xy_chart.chart_options.mode, "COLOR")
self.assertEqual(len(widget.xy_chart.data_sets), 1)
ds = widget.xy_chart.data_sets[0]
self.assertEqual(ds.time_series_query.prometheus_query, "avg(cpu)")
self.assertEqual(ds.time_series_query.unit_override, "%")
self.assertEqual(ds.plot_type, "LINE")
self.assertEqual(widget.xy_chart.y_axis.label, "CPU (%)")
self.assertEqual(widget.xy_chart.y_axis.scale, "LINEAR")
def test_parse_and_validate_widget_unwrapped(self):
text = """
title: "Memory Used"
xy_chart {
data_sets {
time_series_query {
prometheus_query: "memory_query"
}
}
}
"""
widget = textproto_util.parse_and_validate_widget(text)
self.assertEqual(widget.title, "Memory Used")
self.assertTrue(widget.HasField("xy_chart"))
self.assertIsNotNone(widget.xy_chart)
assert widget.xy_chart is not None
self.assertEqual(
widget.xy_chart.data_sets[0].time_series_query.prometheus_query,
"memory_query",
)
self.assertEqual(widget.xy_chart.data_sets[0].plot_type, "LINE")
self.assertEqual(widget.xy_chart.y_axis.scale, "LINEAR")
def test_parse_and_validate_widget_missing_fields(self):
text = 'title: "Empty Chart"'
widget = textproto_util.parse_and_validate_widget(text)
self.assertEqual(widget.title, "Empty Chart")
self.assertFalse(widget.HasField("xy_chart"))
def test_parse_and_validate_widget_unknown_fields(self):
text = """
title: "Chart with unknown fields"
display_name: "I am a hallucination"
xy_chart {
data_sets {
time_series_query {
prometheus_query: "query1"
}
plot_type: LINE
}
}
"""
with self.assertRaisesRegex(ValueError, "Unknown properties in Widget"):
textproto_util.parse_and_validate_widget(text)
def test_parse_and_validate_widget_multiple_datasets(self):
text = """
title: "Multi Metric"
xy_chart {
data_sets {
time_series_query { prometheus_query: "query1" }
plot_type: LINE
}
data_sets {
time_series_query { prometheus_query: "query2" }
plot_type: STACKED_AREA
}
}
"""
widget = textproto_util.parse_and_validate_widget(text)
self.assertIsNotNone(widget.xy_chart)
assert widget.xy_chart is not None
self.assertEqual(len(widget.xy_chart.data_sets), 2)
self.assertEqual(
widget.xy_chart.data_sets[0].time_series_query.prometheus_query,
"query1",
)
self.assertEqual(widget.xy_chart.data_sets[1].plot_type, "STACKED_AREA")
def test_readable_dict_comparison_basic(self):
"""Easy-to-read structural comparison of parsed textproto against expected dict."""
textproto = """
widget {
title: "GCE Instance CPU Utilization"
xy_chart {
chart_options { mode: COLOR }
data_sets {
time_series_query {
prometheus_query: "100 * avg(compute_googleapis_com:instance_cpu_utilization)"
unit_override: "%"
}
plot_type: LINE
target_axis: Y1
}
y_axis {
label: "Utilization (%)"
scale: LINEAR
}
}
}
"""
widget = textproto_util.parse_and_validate_widget(textproto)
expected_dict = {
"title": "GCE Instance CPU Utilization",
"xy_chart": {
"chart_options": {"mode": "COLOR"},
"data_sets": [{
"time_series_query": {
"prometheus_query": (
"100 *"
" avg(compute_googleapis_com:instance_cpu_utilization)"
),
"time_series_filter": None,
"unit_override": "%",
},
"plot_type": "LINE",
"target_axis": "Y1",
}],
"y_axis": {
"label": "Utilization (%)",
"scale": "LINEAR",
},
},
}
self.assertEqual(asdict(widget), expected_dict)
def test_readable_dict_comparison_unwrapped_stacked_area(self):
"""Easy-to-read structural comparison for unwrapped STACKED_AREA charts without unit override."""
textproto = """
title: "Memory Percent Used"
xy_chart {
data_sets {
time_series_query {
prometheus_query: "avg(agent_googleapis_com:memory_percent_used)"
}
plot_type: STACKED_AREA
}
}
"""
widget = textproto_util.parse_and_validate_widget(textproto)
expected_dict = {
"title": "Memory Percent Used",
"xy_chart": {
"chart_options": {"mode": "COLOR"},
"data_sets": [{
"time_series_query": {
"prometheus_query": (
"avg(agent_googleapis_com:memory_percent_used)"
),
"time_series_filter": None,
"unit_override": "",
},
"plot_type": "STACKED_AREA",
"target_axis": "Y1",
}],
"y_axis": {
"label": "",
"scale": "LINEAR",
},
},
}
self.assertEqual(asdict(widget), expected_dict)
def test_readable_dict_comparison_multi_metric(self):
"""Easy-to-read structural comparison for multi-series charts."""
textproto = """
title: "Network Traffic"
xy_chart {
data_sets {
time_series_query {
prometheus_query: "rate(net_in[1m])"
unit_override: "By/s"
}
plot_type: LINE
}
data_sets {
time_series_query {
prometheus_query: "rate(net_out[1m])"
unit_override: "By/s"
}
plot_type: STACKED_AREA
}
y_axis {
label: "Bytes/s"
scale: LOG10
}
}
"""
widget = textproto_util.parse_and_validate_widget(textproto)
expected_dict = {
"title": "Network Traffic",
"xy_chart": {
"chart_options": {"mode": "COLOR"},
"data_sets": [
{
"time_series_query": {
"prometheus_query": "rate(net_in[1m])",
"time_series_filter": None,
"unit_override": "By/s",
},
"plot_type": "LINE",
"target_axis": "Y1",
},
{
"time_series_query": {
"prometheus_query": "rate(net_out[1m])",
"time_series_filter": None,
"unit_override": "By/s",
},
"plot_type": "STACKED_AREA",
"target_axis": "Y1",
},
],
"y_axis": {
"label": "Bytes/s",
"scale": "LOG10",
},
},
}
self.assertEqual(asdict(widget), expected_dict)
if __name__ == "__main__":
absltest.main()
validate_chart.py 8.1 KB
"""Validation utility for chart_generation widget textprotos."""
from __future__ import annotations
import argparse
from collections.abc import Sequence
import glob
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import textproto_util # type: ignore[missing-import]
parse_and_validate_widget = textproto_util.parse_and_validate_widget
def validate_widget(
widget: textproto_util.Widget,
expected_promql_substring: str = "",
expected_lts_filter_substring: str = "",
expected_unit_override: str = "",
expected_plot_type: str = "",
) -> None:
"""Validates the Widget message structure and fields."""
if not widget.title:
raise ValueError("Widget title must not be empty")
if len(widget.title) > 80:
raise ValueError(f"Widget title exceeds 80 chars: {len(widget.title)}")
if not (widget.HasField("xy_chart") and widget.xy_chart is not None):
raise ValueError("Widget must contain an xy_chart")
xy_chart = widget.xy_chart
if len(xy_chart.data_sets) == 0:
raise ValueError("xy_chart must contain at least one data_set")
# Phase 1: Structural exclusivity applies to ALL datasets
for idx, ds in enumerate(xy_chart.data_sets):
has_promql = bool(ds.time_series_query.prometheus_query)
has_lts = bool(ds.time_series_query.time_series_filter)
if not (has_promql or has_lts):
raise ValueError(f"data_set[{idx}] must contain either prometheus_query or time_series_filter")
if has_promql and has_lts:
raise ValueError(f"data_set[{idx}] cannot contain BOTH prometheus_query and time_series_filter")
# Phase 2: Find at least one explicitly matching dataset for the assertions
last_err = None
for ds in xy_chart.data_sets:
try:
has_promql = bool(ds.time_series_query.prometheus_query)
has_lts = bool(ds.time_series_query.time_series_filter)
if expected_promql_substring:
if not has_promql:
raise ValueError("Expected PromQL but found LTS filter")
if expected_promql_substring not in ds.time_series_query.prometheus_query:
raise ValueError(
"PromQL query missing expected substring"
f" '{expected_promql_substring}':"
f" {ds.time_series_query.prometheus_query}"
)
if expected_lts_filter_substring:
if not has_lts:
raise ValueError("Expected LTS filter but found PromQL")
if (
expected_lts_filter_substring
not in ds.time_series_query.time_series_filter.filter
):
raise ValueError(
"LTS filter missing expected substring"
f" '{expected_lts_filter_substring}':"
f" {ds.time_series_query.time_series_filter.filter}"
)
if expected_unit_override:
if ds.time_series_query.unit_override != expected_unit_override:
raise ValueError(
f"Expected unit_override '{expected_unit_override}', got"
f" '{ds.time_series_query.unit_override}'"
)
if expected_plot_type:
if ds.plot_type != expected_plot_type:
raise ValueError(
f"Expected plot_type '{expected_plot_type}', got '{ds.plot_type}'"
)
return # Found a dataset that completely matches the criteria!
except ValueError as e:
last_err = e
# If we exhausted all datasets in this widget and none matched perfectly:
raise ValueError(f"No matching data_set found in widget. Last dataset error: {last_err}")
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Validate widget textproto for chart_generation skill."
)
parser.add_argument(
"--input_file",
"-i",
default="",
help=(
"Path to Widget textproto file or '-' for STDIN. If empty, searches"
" all .textproto files."
),
)
parser.add_argument(
"--expected_promql_substring",
default="",
help="Expected substring in PromQL query.",
)
parser.add_argument(
"--expected_lts_filter_substring",
default="",
help="Expected LTS Filter substring.",
)
parser.add_argument(
"--expected_unit_override",
default="",
help="Expected unit_override string (for example: '%%', 'By/s').",
)
parser.add_argument(
"--expected_plot_type",
default="",
help="Expected plot_type (for example: 'LINE', 'STACKED_AREA').",
)
args = parser.parse_args(argv)
try:
files_to_check = []
if args.input_file == "-":
if not sys.stdin.isatty():
files_to_check.append(("-", sys.stdin.read()))
elif args.input_file:
work_dir = os.environ.get("BUILD_WORKING_DIRECTORY", os.getcwd())
input_path = args.input_file
if not os.path.isabs(input_path):
input_path = os.path.join(work_dir, input_path)
if os.path.exists(input_path):
with open(input_path, "r", encoding="utf-8") as f:
files_to_check.append((input_path, f.read()))
else:
print(
f"ERROR: Input file '{args.input_file}' not found on disk.",
file=sys.stderr,
)
return 1
else:
work_dir = os.environ.get("BUILD_WORKING_DIRECTORY", os.getcwd())
search_dirs = [work_dir]
# Adjust for Google3 environments where the agent may run from the CitC client root
# rather than the google3/ directory. This check is safely bypassed in public (GitHub)
# environments because the google3/ directory will not exist. Internally, the workspace
# contains a parent CitC directory (causing flakiness if the agent runs from there). Externally,
# the Git checkout is the true root, so agents won't accidentally run from a parent wrapper.
if not work_dir.endswith("google3") and os.path.exists(
os.path.join(work_dir, "google3")
):
search_dirs.append(os.path.join(work_dir, "google3"))
for d in search_dirs:
for p in glob.glob(os.path.join(d, "*.textproto")):
with open(p, "r", encoding="utf-8") as f:
files_to_check.append((p, f.read()))
if not files_to_check:
print(
"ERROR: No .textproto files found in the workspace directories:"
f" {search_dirs}",
file=sys.stderr,
)
return 1
# Phase 1: Guarantee ALL generated files are structurally valid.
parsed_widgets = []
for path, content in files_to_check:
try:
widget = textproto_util.parse_and_validate_widget(content)
validate_widget(widget) # Strict structural rules
parsed_widgets.append((path, widget))
except Exception as e:
print(f"ERROR: File '{path}' is structurally invalid: {e}", file=sys.stderr)
return 1
# Phase 2: If we have specific expectations, find at least one matching file.
if not (args.expected_promql_substring or args.expected_lts_filter_substring
or args.expected_unit_override or args.expected_plot_type):
# No specific assertions required, so passing structure is enough.
for path, widget in parsed_widgets:
print(f"Successfully validated structure of Widget '{path}'")
return 0
last_err = None
for path, widget in parsed_widgets:
try:
validate_widget(
widget=widget,
expected_promql_substring=args.expected_promql_substring,
expected_lts_filter_substring=args.expected_lts_filter_substring,
expected_unit_override=args.expected_unit_override,
expected_plot_type=args.expected_plot_type,
)
print(
f"Successfully validated Widget textproto '{path}'. Title:"
f" '{widget.title}'"
)
return 0
except Exception as e:
last_err = e
continue
# If we tried files but none passed:
print(
"ERROR: Failed to validate any Widget textproto finding a match. Last"
f" error: {last_err}",
file=sys.stderr,
)
return 1
except Exception as e: # pylint: disable=broad-except
print(f"ERROR: Failed to validate Widget textproto: {e}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
validate_chart_test.py 3.0 KB
"""Unit test for validate_chart.py."""
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from absl.testing import absltest
import validate_chart # type: ignore[missing-import]
class ValidateChartTest(absltest.TestCase):
def test_parse_and_validate_wrapped_widget(self):
textproto = """
widget {
title: "GCE Instance CPU Utilization"
xy_chart {
chart_options {
mode: COLOR
}
data_sets {
time_series_query {
prometheus_query: "100 * avg(compute_googleapis_com:instance_cpu_utilization)"
unit_override: "%"
}
plot_type: LINE
target_axis: Y1
}
y_axis {
label: "Utilization (%)"
scale: LINEAR
}
}
}
"""
widget = validate_chart.parse_and_validate_widget(textproto)
self.assertEqual(widget.title, "GCE Instance CPU Utilization")
validate_chart.validate_widget(
widget=widget,
expected_promql_substring="instance_cpu_utilization",
expected_unit_override="%",
expected_plot_type="LINE",
)
def test_parse_and_validate_unwrapped_widget(self):
textproto = """
title: "Memory Percent Used"
xy_chart {
data_sets {
time_series_query {
prometheus_query: "avg(agent_googleapis_com:memory_percent_used)"
unit_override: "%"
}
plot_type: LINE
}
}
"""
widget = validate_chart.parse_and_validate_widget(textproto)
self.assertEqual(widget.title, "Memory Percent Used")
validate_chart.validate_widget(
widget=widget,
expected_promql_substring="memory_percent_used",
expected_unit_override="%",
expected_plot_type="LINE",
)
def test_validate_widget_empty_title_fails(self):
textproto = """
xy_chart {
data_sets {
time_series_query {
prometheus_query: "query"
}
}
}
"""
widget = validate_chart.parse_and_validate_widget(textproto)
with self.assertRaises(ValueError):
validate_chart.validate_widget(widget=widget)
def test_validate_widget_dual_query_fails(self):
textproto = """
title: "Invalid Dual Query Chart"
xy_chart {
data_sets {
time_series_query {
prometheus_query: "query"
time_series_filter {
filter: "metric.type=\\"foo\\""
}
}
}
}
"""
widget = validate_chart.parse_and_validate_widget(textproto)
with self.assertRaisesRegex(ValueError, "cannot contain BOTH"):
validate_chart.validate_widget(widget=widget)
def test_main_validate_from_stdin(self):
textproto = """
title: "Disk Read Bytes"
xy_chart {
data_sets {
time_series_query {
prometheus_query: "rate(compute_googleapis_com:instance_disk_read_bytes_count[1m])"
unit_override: "By/s"
}
plot_type: LINE
}
}
"""
import io
import sys
sys.stdin = io.StringIO(textproto)
ret = validate_chart.main([
"--input_file",
"-",
"--expected_promql_substring",
"instance_disk_read_bytes_count",
"--expected_unit_override",
"By/s",
])
self.assertEqual(ret, 0)
if __name__ == "__main__":
absltest.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