Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install cloud-logging-finops@skills-hub

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

Install with the gh extension
gh skills-hub install cloud-logging-finops

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

Download and extract to your repository:

.github/skills/cloud-logging-finops/

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

Skill Files (25)

SKILL.md 19.5 KB
---
name: cloud-logging-finops
metadata:
  version: "1.0.1"
  category: CloudObservabilityAndMonitoring
description: >-
  Audits Cloud Logging costs for a Google Cloud project: the charges for log entries written to log buckets, the services, log streams and severities that drive them, and the log sinks that route them. Reconciles Cloud Billing export costs with Cloud Monitoring volume metrics, and generates a FinOps report with charts and copy-paste exclusion filters. Use when auditing Cloud Logging spend, finding logging waste, identifying top logging contributors, generating log cost reduction reports, or creating log sink exclusion filters. Don't use for querying log entries (use cloud-logging-query-generation), configuring Cloud Monitoring alerts, or querying metrics/traces.
---

# Cloud Logging Finops

**Non-interactive runs.** When no user can answer (e.g. a scheduled or
automated run), ask nothing: audit the project named in the request, or the
active gcloud project; use `--billing-mode=search`; cover all five report topics
(Step 2.5); and never enable an API or upgrade a log bucket. Put anything that
needed a user (a disabled API, a missing role, the upgrade advisory) in the
report instead.

## Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).

## Step 0: Locate the Cloud Billing Export

The audit covers one Google Cloud project, `{project_id}`: the project the user
names or, if they don't name one, the active gcloud project (`gcloud config get
project`), confirmed with the user.

Discover everything else (log buckets, Observability Analytics, sinks,
exclusions, metrics) yourself; never ask the user about those. The billing export is the
exception: finding it unaided can mean scanning every project on the billing
account, so ask once, before running anything, and don't start a search until
the user has chosen answer 3 (single-select, using the host's question tool if
it has one):

> **Do you know where the Cloud Billing export for `{project_id}` is?**
>
> 1.  **Yes** — here it is *(the BigQuery table ID `project.dataset.table`, or
>     just the project and dataset)*
> 2.  **There's no billing export** for this project
> 3.  **No / not sure** — search for it *(seconds on a small project; on a large
>     billing account it can take a long time)*

Answer | Flags                                                                                         | Cost figures
------ | --------------------------------------------------------------------------------------------- | ------------
1      | `--billing-mode=explicit` plus `--billing-table` (or `--billing-project`/`--billing-dataset`) | invoiced
2      | `--billing-mode=none`                                                                         | list-price estimates
3      | `--billing-mode=search` *(default)*                                                           | invoiced if found, else estimates

Answer 3's search has no time limit: it checks `{project_id}` first (usually
under 10 s, 1–2 min with many tables), then every project on its billing account
(can take many minutes; progress prints every 30 s). Tell the user this before
launching. If the wait is unacceptable, offer to switch to answer 1 (they look up
the table) or answer 2 (skip the export and use list-price estimates). Don't
suggest setting up an export to make the search faster.

If the search found an export, tell the user: *"Next time, pass
`--billing-table=<table>` and discovery drops to about two seconds."*

## Step 1: Environment Setup

Check these prerequisites before Step 2; fix only what is missing:

*   **gcloud:** if `gcloud` is not installed, follow
    https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt.
*   **Project:** run `gcloud config get project`; if it isn't `{project_id}`
    (from Step 0), run `gcloud config set project {project_id}`.
*   **Credentials:** the scripts use Application Default Credentials. Run
    `gcloud auth application-default login`, or set
    `GOOGLE_APPLICATION_CREDENTIALS` to a service account key.
*   **Billing:** the project must have an active billing account attached.
*   **APIs:** don't enable APIs up front; the Logging, Monitoring, BigQuery and
    Observability APIs are on by default in new projects. Only if the collector
    reports an API as disabled (`SERVICE_DISABLED`, "has not been used in
    project"), name it, ask the user, and on approval run `gcloud services
    enable {api} --project={project_id}` (tagged as described below):
    *   `logging`, `monitoring`: required; without them there is nothing to
        audit.
    *   `bigquery`: invoiced costs from the billing export.
    *   `observability`: resolves the project's default log scope, so log
        samples match what Logs Explorer shows.
    *   `cloudasset`, `cloudbilling`: only answer 3's search across the billing
        account.

IAM roles for the identity running the audit. The skill never grants roles: the
scripts run with the user's own credentials and read only what those
credentials can. When a step fails on permissions, its advisory names the step;
tell the user which role below it needs:

Role                                                                 | Needed for
-------------------------------------------------------------------- | ----------
`roles/logging.viewer`, `roles/monitoring.viewer`                    | Every audit: log buckets, sinks, log samples, volume metrics
`roles/bigquery.jobUser`, `roles/bigquery.dataViewer` (on the export dataset) | Invoiced costs from the billing export
`roles/logging.viewAccessor` on log views in other projects        | Reading samples through a default log scope that includes them
`roles/cloudasset.viewer`, `roles/billing.viewer` (billing account)  | `--billing-mode=search` across the billing account
`roles/logging.configWriter`                                         | Only the optional Observability Analytics upgrade (Step 3B)

```bash
[ -f /tmp/finops_venv/bin/python ] || (uv venv /tmp/finops_venv && uv pip install -r scripts/requirements.txt --python /tmp/finops_venv/bin/python)
```

The bundled scripts tag their Google Cloud API requests. For commands you run
yourself, follow [Usage Attribution](references/attribution.md).

## Step 2: Data Collection

Start the collector below as a background process (it takes from seconds to
many minutes), then go to Step 2.5 while it runs:

```bash
/tmp/finops_venv/bin/python scripts/collect_logging_data.py \
  --project-id {project_id} --billing-mode={none|explicit|search}
```

Optional: `--billing-project`, `--billing-dataset`, `--billing-table` (e.g.
`billing-proj.ds.gcp_billing_export_v1_XXXX` or a curated FinOps view).

Outputs: `logging_usage_summary.json`, `monthly_details/`, `service_details/`,
and `[FINOPS ADVISORY]` lines (see Step 3). The collector's output ends with a
`[COLLECTION PROFILE]` table of per-stage timings; if the run took longer than
the times in Step 0, or the user asks why the audit took so long, read that
table before guessing.

## Step 2.5: Ask What the Report Is For

Always ask this while the collector runs (multi-select). If the user skips it,
cover all five topics:

> **What should this report answer?**
>
> -   Where is the money going — attribution by service and stream
> -   Is spend growing — trends and projection
> -   What can I safely turn off — concrete savings actions
> -   What are these logs actually saying — noisiest patterns and samples
> -   Severity and audit-log posture

The user's choices decide which outputs you read in depth and what your
summary leads with; they never change what the collector gathers:

Interest         | Read deeply
---------------- | -----------
Attribution      | `service_details/*.json`, `daily_services`
Growth           | `monthly_details/*.json`, `mom_patterns`, `cost_projection`
Savings actions  | `reduction_actions`, `extraneous_spend`
What logs say    | `severity_summary.samples_by_service`, `granular_analytics.top_signatures` (Observability Analytics only)
Severity / audit | `severity_summary`, withheld-rule reasons

Your narrative goes in `insights/executive_summary.html` (see
[Executive Summary Authoring](references/executive_summary_authoring.md)).
You don't write the savings actions: the generated report's Cost Optimizer tab
lists them from `reduction_actions`.

> [!CAUTION] Never edit `assets/report_template.html`.

## Step 3: Follow the Advisories

### A. Tell the User What the Cost Figures Are Based On

> [!IMPORTANT] Unless figures are invoiced (`billing_metadata.invoiced`), tell
> the user in plain language where you looked, what you found, and what the
> numbers are based on. Keep internals (stage numbers, mode names, HTTP codes,
> "quota project", "Cloud Asset Inventory") in the log and
> `billing_metadata.fallback_chain`.

*   **Answer 1, the location gave no costs** (`explicit_table` or
    `explicit_scope` step not `found`): the collector never searches beyond what
    the user named. Tell them what was wrong, from the step's `detail` (no rows
    for this project, no export table there, or the query failed), that costs
    are list-price estimates, and offer to rerun with a corrected location or
    with answer 3.
*   **Answer 2** (`user_declared_no_export`): "I didn't search — you told me
    there's no billing export — so costs are list-price estimates, not invoiced
    amounts." Never call a skipped search exhausted.
*   **Answer 3, found nothing** (`billing_account` status `not_found`): "I
    searched this project and your billing account and found no billing export.
    Costs are list-price estimates (quote each SKU's price and free tier from
    `pricing.skus`) over a trailing 30 days." Only this case supports
    recommending export setup. Cite the official pricing page
    (https://cloud.google.com/products/observability/pricing) as the source of
    list prices.
*   **Answer 3, search failed on permissions** (any step status
    `inconclusive`): tell the user the lookup couldn't complete, so costs are
    estimates. Never tell them no billing export exists; the search didn't
    finish.
*   **Answer 3, this project's table rejected** (`local_project` status
    `no_project_records`): "This project has a billing export, but it holds no
    records for this project, so I searched the rest of the billing account."
    Then report the outcome of that wider search as above.
*   **Partial history:** months are labelled `actual_bq_billing` or
    `usage_estimated`; state the exact date boundary in the executive summary.

When on list pricing, recommend export for accuracy: future audits would use the
actual invoice, including discounts, over multiple months.

### B. Observability Analytics

Observability Analytics was formerly called Log Analytics; the scripts'
advisories and field names still use the old name.

*   **Disabled:** present the advisory, including that upgrading the log bucket
    is irreversible, then end your reply with a direct question, e.g. *"Do you
    want me to upgrade the `_Default` log bucket to Observability Analytics?
    This can't be undone."* Telling the user how to run it themselves is not
    asking. Only after they approve upgrading that log bucket, run `/tmp/finops_venv/bin/python
    scripts/enable_log_analytics.py --project-id {project_id}`. The audit
    proceeds on Cloud Monitoring either way.

> [!CAUTION] Never run `enable_log_analytics.py` or `gcloud logging buckets
> update --enable-analytics` in the same turn you raise the advisory, or on
> general permission like "do whatever you need".

*   **< 24 hours old:** the 14-day Cloud Monitoring baseline is used until
    samples accumulate (~1–2 hours).
*   **1–13 days:** cite the sample window in the report.
*   **≥ 14 days:** full SQL analytics.
*   **`Representative logs unavailable` advisory:** samples are missing because
    your environment can't read log entries (needs `roles/logging.viewer`), not
    because streams are empty. Relay the error and role; per-stream detail is in
    `severity_summary.sample_errors`.
*   **Samples empty but the stream has volume:** samples are read through the
    project's default log scope, like Logs Explorer
    (`analytics_metadata.log_read_scope`). If its `source` is `project` and it
    has a `note`, the scope couldn't be resolved, so logs held outside this
    project's log buckets weren't read. Say that and relay the `note`; never say the
    stream has no logs.

### C. Measurement Integrity

> [!CAUTION] Never quote cost or volume derived from Observability Analytics
> payload byte sums; they overstate billed volume about 2x.

Question                     | Source
---------------------------- | ------
Cost, GiB ingested           | Billing export (`billing.query_logging_billing_costs`, `daily_gib`, `monthly_costs`)
Service mix                  | `logging.googleapis.com/billing/bytes_ingested` (`resource_type`)
Log stream / severity volume | `logging.googleapis.com/byte_count` (`log`, `severity`)
Severity mix, entry content  | Observability Analytics SQL (`constants.PAYLOAD_BYTES_SQL`)

*   Totals come from the invoice when it exists; metrics only supply shares.
    Never put a metric-derived total next to an invoiced one.
*   `byte_count` (received) and `billing/bytes_ingested` (billed) differ by
    ~1.5x or more; never divide one by the other.
*   If `telemetry_integrity.status` is `degraded`, say dips on the listed days
    look like a metric defect that won't self-correct, and repeat the limits in
    `telemetry_integrity.note`. Never claim with certainty that nothing changed.
*   A month with `is_partial: true` is month-to-date. Label it so, and never
    call it a complete month or "last month".

### D. Extraneous Spend

`extraneous_spend.headline` is a conservative floor: the sum of the
`reduction_actions.actions` with `counted: true` (duplicate bucket routing,
flow-log sampling, DEBUG logs, stale exclusions), each priced on exactly what
its remedy removes. Everything else is surfaced, never counted: over-retention
(not quantified), sampled exclusion rules (estimates), and Data Access audit
logs (in `withheld`).

1.  Report it as a floor (`≥ X%`), never a point estimate or "up to".
2.  If `status` is `insufficient_data`, give no figure — not a guess, a
    benchmark, or $0.
3.  Quote any action's `flag` verbatim; it is written for the reader.
4.  Uncounted actions and `uncounted_total_pct` may be mentioned as upside,
    never added to the headline.
5.  If `headline.exceeds_sanity_ceiling`, say the headline isn't reliable, name
    the largest counted action, and flag it for manual review. Offer no number.
6.  If `inventory_unavailable` is non-empty, say log sink, exclusion and
    flow-log actions weren't checked; never say none exist.
7.  Whenever Data Access audit logs come up (a `withheld` entry, or the user
    names them), say they are left out of the number because they need a
    compliance decision: disabling or excluding them is frequently prohibited
    by compliance or security policy, so the owner must confirm before acting.

### E. Exclusion Filters and Actions

*   Only Cost Optimizer actions carry filters and savings; Service Details
    volumes are not savings. Report `sample_coverage.shown_pct`.
*   Quote an action's monthly figures (`monthly_gib`, `monthly_usd`), never a
    rule's sample-window GiB (`granular_analytics.exclusion_candidates`).
*   `rule_scope: stream` drops every log entry of that severity in the stream; say so.
*   If `refused_claims` is non-empty, name the streams the safety gate removed.

Never offered as actions: `CRITICAL`/`ALERT`/`EMERGENCY` (incident signal), free
`_Required` streams ($0, audit retention), Data Access audit logs (often
compliance-mandated; report, never count), and streams with no measured volume.

> [!CAUTION] Hand-written exclusion filters must: include a severity predicate
> (`severity = "DEFAULT"` for DEFAULT — omitting it matches everything); use the
> URL-encoded log ID (`compute.googleapis.com%2Ffirewall`); never embed
> unescaped log text or rotating tokens (UUIDs, IPs, long integers, times) in a
> regex; and respect the list above.

## Step 4: Build and Deliver the Report

```bash
/tmp/finops_venv/bin/python scripts/build_report.py --summary logging_usage_summary.json --insights-dir insights/ --output log_usage_report.html
```

`build_report.py` writes an executive summary unless you provide
`insights/executive_summary.html`.

Give the user one link that, when clicked, opens the fully rendered report — not
raw HTML, not a missing file — from wherever the user actually is. Confirm that
will happen before you post it.

Then list what they can explore (charts, service drilldowns, ranked actions with
copyable filters, ✓ Prove It drawers) and suggest 3–4 follow-up questions drawn
from this project's data, phrased to ask as-is.

If the user asked something specific, answer it directly with both GiB and USD,
from `monthly_aggregations` (`latest_complete_month` names the newest whole
month; each month's `top_service` is its Top Cost Driver), `mom_patterns`,
`cost_projection`, `trailing_30d_summary` (its `top_driver` is the report's Top
Cost Driver without an invoice), `granular_analytics` (present only when
Observability Analytics ran), or the per-service/month detail files.

## Step 5: Follow-Up Questions

**Phase 1 (default):** answer from the JSON on disk in a few sentences or a
small table, name what the data can't settle, then stop and offer 3–4 ways to go
deeper. Don't re-run collection or re-query sources.

Question about         | Read
---------------------- | ----
A severity             | `severity_summary`, `granular_analytics.top_signatures` for that severity
A service              | `service_details/{service}.json`, `top_signatures` and `top_log_names` for it
An optimization action | its entry in `reduction_actions.actions` (`claims`, `refused_claims`, `flag`, `counted`)

**Phase 2 (only after the user picks a direction):** go as deep as it needs. Run
Observability Analytics SQL against `analytics_metadata.table_name`, the `_AllLogs` view
the collector measured. Step 3 still applies.

## Step 6: Prove It

`provenance.claims[<id>]` records each headline figure's `formula`, `sources`
(exact query, Google Cloud console link, steps; only the 10 largest streams per action),
known `differences` from the console, and runnable `checks` (covering every
stream). Ids include `latest_complete_spend`, `mtd_run_rate`,
`trailing_30d_volume`, `estimated_run_rate`, `top_cost_driver`,
`extraneous_spend`, `severity_costs`, `service_mix`, `action::<action id>`. A
claim built from others lists them in `see_also` (`extraneous_spend` → its
counted actions); prove those too, and `verify_claim.py` re-checks them with it.

When asked to prove a figure:

1.  **Now, from disk:** walk the formula with its inputs; list each source with
    its Google Cloud console link, its query exactly as recorded, and steps; then the
    `differences`.
2.  **Same turn, in the background:** run `/tmp/finops_venv/bin/python
    scripts/verify_claim.py --summary <summary> --claim "<id>"`; don't wait.
3.  **When it finishes:** a table (check | report | live | Δ | ✓/△/✗) and a
    one-line verdict. Explain △ with the recorded `differences`; give ✗ causes
    in one line each.

> [!CAUTION] Prove It is the only request that may re-query sources, and only
> via `verify_claim.py`. Don't re-run collection or alter the recorded queries.

Disclose when relevant: whether the claim was priced (`pricing.mode`) `per_sku`
(each SKU's price and free tier in `pricing.skus`) or `blended` (reason in
`pricing.notes`); that service and severity figures exclude credits; and, if
`cross_project_billing`, that reproducing it needs `roles/bigquery.dataViewer`
on the billing export dataset and `roles/bigquery.jobUser`.
assets/
report_template.html 134.3 KB
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Cloud Logging Cost Report (Beta): {{PROJECT_ID}}</title>
  <style>
    :root {
      --bg: #0f172a;
      --bg-card: #1e293b;
      --bg-muted: #334155;
      --bg-input: #0f172a;
      --border: #334155;
      --border-subtle: #1e293b;
      --text: #f8fafc;
      --text-muted: #94a3b8;
      --primary: #3b82f6;
      --primary-hover: #2563eb;
      --primary-subtle: rgba(59, 130, 246, 0.15);
      --success: #10b981;
      --success-subtle: rgba(16, 185, 129, 0.15);
      --warning: #f59e0b;
      --warning-subtle: rgba(245, 158, 11, 0.15);
      --danger: #ef4444;
      --danger-subtle: rgba(239, 68, 68, 0.15);
      --purple: #a855f7;
      --purple-subtle: rgba(168, 85, 247, 0.15);
      --font: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
      --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
      --radius: 12px;
    }

    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      background-color: var(--bg);
      color: var(--text);
      font-family: var(--font);
      line-height: 1.5;
      padding: 24px;
      min-height: 100vh;
    }

    .container { max-width: 1280px; margin: 0 auto; display: flex; flex-direction: column; gap: 24px; }
    
    /* Header */
    .header {
      background: var(--bg-card);
      border: 1px solid var(--border);
      border-radius: var(--radius);
      padding: 24px;
      display: flex;
      flex-direction: column;
      gap: 12px;
    }
    
    .title { font-size: 24px; font-weight: 700; letter-spacing: -0.02em; }
    .meta-text { font-size: 13px; color: var(--text-muted); display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
    .code-pill { font-family: var(--font-mono); background: var(--bg-muted); padding: 2px 6px; border-radius: 4px; font-size: 12px; color: var(--text); }
    
    .banner-warning {
      background: rgba(245, 158, 11, 0.1);
      border: 1px solid rgba(245, 158, 11, 0.3);
      border-radius: 8px;
      padding: 12px 16px;
      font-size: 13px;
      color: #fbbf24;
      line-height: 1.45;
    }

    /* Badges */
    .badge {
      display: inline-flex;
      align-items: center;
      padding: 4px 10px;
      border-radius: 9999px;
      font-size: 12px;
      font-weight: 600;
      background: var(--bg-muted);
      color: var(--text-muted);
      border: 1px solid var(--border);
    }
    .badge-primary { background: var(--primary-subtle); color: #60a5fa; border-color: rgba(96, 165, 250, 0.3); }
    .badge-success { background: var(--success-subtle); color: #34d399; border-color: rgba(52, 211, 153, 0.3); }
    .badge-warning { background: var(--warning-subtle); color: #fbbf24; border-color: rgba(251, 191, 36, 0.3); }

    /* Header: title block left, controls right. Below 900px they no longer
       fit side by side, so the meta items stack and the controls become one
       toolbar row (toggle left, Report an Issue right). The "Dashboard Metric"
       label is hidden there; the toggle labels already say it. */
    .header-top { display: flex; justify-content: space-between; align-items: center; gap: 16px; }
    .header-titles { display: flex; flex-direction: column; gap: 8px; }
    .meta-item { display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; }
    .header-controls { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; flex-shrink: 0; }
    .header-metric-label { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted); }
    @media(max-width: 899px) {
      .header-top { flex-direction: column; align-items: stretch; }
      .header-titles .meta-text { flex-direction: column; align-items: flex-start; }
      .meta-sep, .header-metric-label { display: none; }
      .header-controls { flex-direction: row; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px; }
      .header-controls .toggle-group { order: -1; }
    }

    /* Report an Issue: opens a pre-filled GitHub issue in a new tab. */
    .report-issue-btn {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      font-size: 12px;
      font-weight: 600;
      color: var(--text-muted);
      text-decoration: none;
      border: 1px solid var(--border);
      border-radius: 6px;
      padding: 5px 10px;
      white-space: nowrap;
      transition: all 0.15s ease;
    }
    .report-issue-btn:hover { color: var(--text); border-color: var(--primary); background: var(--primary-subtle); }

    /* Navigation */
    .nav-tabs {
      display: flex;
      gap: 16px;
      border-bottom: 1px solid var(--border);
      overflow-x: auto;
      padding-bottom: 2px;
    }
    .tab-btn {
      background: none;
      border: none;
      border-bottom: 2px solid transparent;
      color: var(--text-muted);
      font-size: 14px;
      font-weight: 600;
      padding: 10px 14px;
      cursor: pointer;
      transition: all 0.2s ease;
      white-space: nowrap;
    }
    .tab-btn:hover { color: var(--text); }
    .tab-btn.active {
      color: var(--primary);
      border-bottom-color: var(--primary);
    }

    /* Sub-Navigation */
    .subnav-tabs {
      display: flex;
      gap: 10px;
      border-bottom: 1px solid var(--border);
      padding-bottom: 8px;
    }
    .subtab-btn {
      background: var(--bg);
      border: 1px solid var(--border);
      color: var(--text-muted);
      font-size: 13px;
      font-weight: 600;
      padding: 6px 14px;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.15s ease;
    }
    .subtab-btn:hover {
      color: var(--text);
      border-color: var(--primary);
    }
    .subtab-btn.active {
      background: var(--primary-subtle);
      color: #60a5fa;
      border-color: rgba(96, 165, 250, 0.4);
    }
    .subtab-pane { display: flex; flex-direction: column; gap: 24px; }
    .subtab-pane.hidden { display: none; }

    .two-col-equal-grid {
      display: grid;
      grid-template-columns: 1fr;
      gap: 16px;
    }
    @media(min-width: 768px) { .two-col-equal-grid { grid-template-columns: repeat(2, 1fr); } }

    .tab-pane { display: flex; flex-direction: column; gap: 24px; }
    .tab-pane.hidden { display: none; }

    /* Cards Grid */
    .kpi-grid {
      display: grid;
      grid-template-columns: repeat(1, 1fr);
      gap: 16px;
    }
    @media(min-width: 640px) { .kpi-grid { grid-template-columns: repeat(2, 1fr); } }
    @media(min-width: 1024px) { .kpi-grid { grid-template-columns: repeat(4, 1fr); } }

    .card {
      background: var(--bg-card);
      border: 1px solid var(--border);
      border-radius: var(--radius);
      padding: 20px;
      display: flex;
      flex-direction: column;
      gap: 8px;
    }
    .card-header { display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: var(--text-muted); font-weight: 500; }
    .kpi-val { font-size: 26px; font-weight: 700; letter-spacing: -0.02em; }
    .kpi-subtext { font-size: 12px; color: var(--text-muted); }

    /* Trend Chart Section */
    .chart-container {
      background: var(--bg-card);
      border: 1px solid var(--border);
      border-radius: var(--radius);
      padding: 24px;
      display: flex;
      flex-direction: column;
      gap: 16px;
    }
    .chart-title-bar { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px; }
    .section-title { font-size: 16px; font-weight: 700; }
    
    .toggle-group {
      display: flex;
      background: var(--bg);
      border: 1px solid var(--border);
      border-radius: 8px;
      padding: 2px;
      gap: 2px;
    }
    .metric-toggle-btn {
      background: none;
      border: none;
      color: var(--text-muted);
      font-size: 12px;
      font-weight: 600;
      padding: 6px 14px;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.15s ease;
    }
    .metric-toggle-btn.active {
      background: var(--bg-muted);
      color: var(--text);
    }

    /* Service Explorer (Tab 2) */
    .two-col-grid {
      display: grid;
      grid-template-columns: 1fr;
      gap: 24px;
    }
    @media(min-width: 1024px) { .two-col-grid { grid-template-columns: 5fr 7fr; } }

    .search-box {
      width: 100%;
      background: var(--bg);
      border: 1px solid var(--border);
      border-radius: 8px;
      color: var(--text);
      padding: 10px 12px;
      font-size: 13px;
      outline: none;
    }
    .search-box:focus { border-color: var(--primary); }

    .services-list {
      display: flex;
      flex-direction: column;
      gap: 8px;
      max-height: 540px;
      overflow-y: auto;
      padding-right: 4px;
    }
    .service-row {
      background: var(--bg);
      border: 1px solid var(--border);
      border-radius: 8px;
      padding: 12px 14px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
      font-size: 13px;
      transition: all 0.15s ease;
    }
    .service-row:hover { border-color: var(--primary); background: var(--bg-muted); }
    .service-row.active { border-color: var(--primary); background: var(--primary-subtle); }
    .service-name { font-weight: 600; max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .service-sub { font-size: 11px; color: var(--text-muted); }

    /* Severity Bar */
    .severity-bar {
      display: flex;
      height: 16px;
      border-radius: 8px;
      overflow: hidden;
      background: var(--bg-muted);
      width: 100%;
    }
    .sev-segment { height: 100%; transition: width 0.3s ease; }

    /* Data Table */
    .data-table {
      width: 100%;
      border-collapse: collapse;
      font-size: 12px;
      text-align: left;
    }
    .data-table th { padding: 10px 8px; border-bottom: 1px solid var(--border); color: var(--text-muted); font-weight: 600; }
    .data-table td { padding: 10px 8px; border-bottom: 1px solid var(--border-subtle); color: var(--text); }
    .severity-row {
      cursor: pointer;
      transition: background-color 0.15s ease;
    }
    .severity-row:hover {
      background-color: rgba(255, 255, 255, 0.05) !important;
    }
    .accordion-arrow {
      display: inline-block;
      transition: transform 0.2s ease;
      font-size: 10px;
      color: var(--text-muted);
      margin-right: 6px;
    }
    .severity-accordion-cell {
      padding: 0 !important;
      background: rgba(15, 23, 42, 0.6);
      border-bottom: 1px solid var(--border);
    }
    .sample-logs-wrap {
      padding: 14px;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
    .sample-card {
      background: var(--bg-card);
      border: 1px solid var(--border);
      border-radius: 10px;
      padding: 14px 16px;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
    .payload-box {
      background: #090d16;
      border: 1px solid rgba(255, 255, 255, 0.08);
      border-radius: 6px;
      padding: 10px 12px;
      font-family: var(--font-mono);
      font-size: 11px;
      color: #cbd5e1;
      line-height: 1.5;
      max-height: 115px;
      overflow-y: auto;
      white-space: pre-wrap;
      word-break: break-word;
      transition: max-height 0.25s ease;
    }
    .payload-box.expanded {
      max-height: 520px;
    }

    .copy-btn {
      background: var(--primary);
      color: #fff;
      border: none;
      padding: 6px 12px;
      border-radius: 6px;
      font-size: 12px;
      font-weight: 600;
      cursor: pointer;
      transition: background 0.2s;
    }
    .copy-btn:hover { background: var(--primary-hover); }

    /* Prove It: shows where a number came from and how to reproduce it in the
       console. It is self-contained (no agent handoff), so it behaves the same
       in every host: agent artifact panes, IDE previews and plain browsers. */
    .prove-btn {
      display: inline-flex;
      align-items: center;
      gap: 5px;
      background: rgba(16, 185, 129, 0.12);
      color: #34d399;
      border: 1px solid rgba(16, 185, 129, 0.45);
      border-radius: 6px;
      padding: 3px 9px;
      font-size: 11px;
      font-weight: 600;
      cursor: pointer;
      white-space: nowrap;
      transition: all 0.15s ease-in-out;
    }
    .prove-btn:hover {
      background: rgba(16, 185, 129, 0.25);
      border-color: #34d399;
      color: #d1fae5;
    }
    .prove-btn .check { font-size: 11px; line-height: 1; }
    .kpi-actions { display: flex; gap: 8px; align-items: center; margin-top: 4px; flex-wrap: wrap; }

    .prove-overlay {
      position: fixed; inset: 0; background: rgba(2, 6, 23, 0.55);
      z-index: 9000; display: none;
    }
    .prove-overlay.open { display: block; }
    .prove-drawer {
      position: fixed; top: 0; right: 0; bottom: 0;
      width: min(720px, 100vw);
      background: var(--bg-card); border-left: 1px solid var(--border);
      box-shadow: -12px 0 30px rgba(0,0,0,0.4);
      z-index: 9001; overflow-y: auto; padding: 20px 22px;
      display: none; flex-direction: column; gap: 16px;
    }
    .prove-drawer.open { display: flex; }
    .prove-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
    .prove-kicker { font-size: 10px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; color: #34d399; }
    .prove-title { font-size: 18px; font-weight: 700; color: var(--text); margin-top: 2px; }
    .prove-value { font-size: 14px; font-weight: 600; color: var(--text-muted); margin-top: 2px; }
    .prove-close { background: none; border: 1px solid var(--border); color: var(--text-muted); border-radius: 6px; padding: 2px 9px; cursor: pointer; font-size: 14px; }
    .prove-section-title { font-size: 11px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; color: var(--text-muted); margin-bottom: 6px; }
    .prove-formula { font-family: var(--font-mono); font-size: 11.5px; line-height: 1.6; color: var(--text); background: var(--bg-input); border: 1px solid var(--border); border-radius: 6px; padding: 10px 12px; white-space: pre-wrap; overflow-wrap: anywhere; }
    .prove-source { border: 1px solid var(--border); border-radius: 8px; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
    .prove-source-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 10px; }
    .prove-source-name { font-weight: 600; font-size: 13px; color: var(--text); }
    .prove-source-role { font-size: 11px; color: var(--text-muted); }
    .prove-kind { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; color: #60a5fa; }
    .prove-link { display: inline-flex; align-items: center; gap: 4px; font-size: 11px; font-weight: 600; color: #60a5fa; text-decoration: none; border: 1px solid rgba(96,165,250,0.4); border-radius: 6px; padding: 3px 9px; white-space: nowrap; }
    .prove-link:hover { background: rgba(96,165,250,0.12); }
    .prove-code { font-family: var(--font-mono); font-size: 11px; background: var(--bg-input); border: 1px solid var(--border); border-radius: 6px; padding: 8px 10px; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 220px; overflow-y: auto; color: var(--text); margin: 0; }
    .prove-steps { margin: 0; padding-left: 18px; font-size: 12px; line-height: 1.55; color: var(--text); }
    .prove-diffs { margin: 0; padding-left: 18px; font-size: 12px; line-height: 1.55; color: var(--text-muted); }
    .prove-foot { font-size: 11px; color: var(--text-muted); border-top: 1px solid var(--border); padding-top: 10px; }


    /* Telemetry Integrity Warning Collapsible Banner */
    details.telemetry-banner {
      background: rgba(245, 158, 11, 0.07);
      border: 1px solid rgba(245, 158, 11, 0.28);
      border-radius: 8px;
      padding: 8px 14px;
      margin-bottom: 20px;
      font-size: 11px;
      transition: background 0.15s ease, border-color 0.15s ease;
    }
    details.telemetry-banner[open] {
      background: rgba(245, 158, 11, 0.11);
      border-color: rgba(245, 158, 11, 0.4);
    }
    summary.telemetry-banner-summary {
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #fbbf24;
      font-size: 12px;
      font-weight: 500;
      user-select: none;
      list-style: none;
    }
    summary.telemetry-banner-summary::-webkit-details-marker {
      display: none;
    }
    summary.telemetry-banner-summary:hover .telemetry-banner-title {
      color: #fef08a;
    }
    .telemetry-banner-header-left {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    .telemetry-banner-icon {
      font-size: 14px;
      line-height: 1;
    }
    .telemetry-banner-toggle {
      display: inline-flex;
      align-items: center;
      gap: 5px;
      font-size: 11px;
      font-weight: 600;
      color: #fbbf24;
      background: rgba(245, 158, 11, 0.15);
      border: 1px solid rgba(245, 158, 11, 0.3);
      padding: 2px 8px;
      border-radius: 4px;
      transition: all 0.15s ease;
    }
    details[open] summary .telemetry-toggle-arrow {
      transform: rotate(180deg);
      display: inline-block;
      transition: transform 0.15s ease;
    }
    summary .telemetry-toggle-arrow {
      display: inline-block;
      transition: transform 0.15s ease;
    }
    .telemetry-banner-body {
      margin-top: 10px;
      padding-top: 10px;
      border-top: 1px solid rgba(245, 158, 11, 0.2);
      font-size: 11px;
      line-height: 1.6;
      color: #cbd5e1;
    }
    .telemetry-banner-body p {
      margin: 4px 0;
    }

    /* Cost Optimizer: one full-width card per action. The coloured left edge
       and the label above the title carry the verdict from `actions.py`. */
    .action-list { display: flex; flex-direction: column; gap: 14px; }
    .action-card {
      background: var(--bg-card);
      border: 1px solid var(--border);
      border-left: 4px solid var(--text-muted);
      border-radius: 10px;
      padding: 16px 18px;
      display: flex;
      flex-direction: column;
      gap: 12px;
      min-width: 0;
    }
    .action-card.level-ready { border-left-color: var(--success); }
    .action-card.level-confirm,
    .action-card.level-estimated { border-left-color: var(--warning); }
    .action-card.level-judgement { border-left-color: var(--purple); }
    .action-head {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      gap: 12px;
    }
    .action-label {
      font-size: 10px;
      font-weight: 700;
      letter-spacing: 0.04em;
      text-transform: uppercase;
      color: var(--text-muted);
      margin-bottom: 2px;
    }
    .level-ready .action-label { color: var(--success); }
    .level-confirm .action-label,
    .level-estimated .action-label { color: var(--warning); }
    .level-judgement .action-label { color: #c084fc; }
    .action-title { font-weight: 600; font-size: 14px; }
    .action-saving { text-align: right; white-space: nowrap; flex-shrink: 0; }
    .action-saving-usd { font-size: 18px; font-weight: 700; color: var(--success); }
    .action-saving-gib { font-size: 11px; color: var(--text-muted); }
    .action-saving-none { font-size: 14px; font-weight: 500; color: var(--text-muted); }
    .action-bar { height: 4px; border-radius: 2px; background: var(--bg-muted); overflow: hidden; }
    .action-bar > span { display: block; height: 100%; background: var(--success); opacity: 0.7; }
    .action-body { display: grid; grid-template-columns: 1fr; gap: 16px; }
    @media(min-width: 900px) {
      .action-body { grid-template-columns: 1fr 1fr; }
      .action-body.action-body-single { grid-template-columns: 1fr; }
    }
    .action-body > * { min-width: 0; display: flex; flex-direction: column; gap: 6px; }
    .action-section-title {
      font-size: 10px;
      font-weight: 700;
      letter-spacing: 0.04em;
      text-transform: uppercase;
      color: var(--text-muted);
    }
    .action-text { font-size: 12px; line-height: 1.55; color: var(--text); }
    .action-muted { color: var(--text-muted); }
    /* Must not read as one more neutral sentence: this is the line that stops
       someone dropping their firewall logs. */
    .action-caveat {
      padding: 8px 10px;
      border-radius: 6px;
      background: var(--warning-subtle);
      color: var(--text);
      font-size: 12px;
      font-weight: 500;
      line-height: 1.5;
    }
    /* A filter is one unbreakable 90-character token; it gets its own scroll
       box so it cannot drag the card past the edge of a narrow pane. */
    .action-filter {
      display: block;
      padding: 8px 10px;
      background: var(--bg-input);
      border: 1px solid var(--border);
      border-radius: 6px;
      font-family: var(--font-mono);
      font-size: 11px;
      color: var(--text);
      white-space: pre-wrap;
      overflow-wrap: anywhere;
      max-height: 140px;
      overflow-y: auto;
    }
    .action-copy { padding: 4px 10px; font-size: 11px; }
    .action-details { display: block; min-width: 0; }
    .action-details summary {
      cursor: pointer;
      font-size: 11px;
      font-weight: 600;
      color: var(--text-muted);
      user-select: none;
    }
    .action-details summary:hover { color: var(--text); }
    .action-details .payload-box { margin-top: 6px; }
    .action-withheld { gap: 6px; }

    /* Slots */
    .slot-box { display: flex; flex-direction: column; gap: 12px; }

    /* Narrow-viewport containment.

       A grid or flex item is min-width:auto by default, which resolves to the
       min-content width of its contents. One unbreakable 90-character
       `logName = "projects/<id>/logs/<encoded>"` inside the Optimization
       Actions card therefore widened its column, its grid, and the page --
       the card ran off the side of the viewport instead of scrolling inside
       it. Every container that can hold a log name or a filter is allowed to
       shrink below its content here, and the content is told how to reflow. */
    .two-col-grid > *,
    .two-col-equal-grid > *,
    .kpi-grid > *,
    .card,
    .tab-pane,
    .subtab-pane { min-width: 0; }

    /* Filter text stays on one line and scrolls, rather than forcing the card
       wider than the pane. */
    .code-pill { max-width: 100%; }

    /* Wide tables scroll within their card instead of pushing it open. */
    .table-scroll { width: 100%; overflow-x: auto; }
    .data-table { min-width: 0; }

    /* The artifact pane can be a few hundred pixels wide; 24px of padding on
       each side is a meaningful share of it. */
    @media(max-width: 640px) {
      body { padding: 12px; }
      .header, .card, .action-card { padding: 16px; }
    }
  </style>
</head>
<body>
  <div class="container">
    
    <!-- Header -->
    <header class="header">
      <div class="header-top">
        <div class="header-titles">
          <h1 class="title">Cloud Logging FinOps & Cost Audit (Beta)</h1>
          <div class="meta-text">
            <span class="meta-item"><span>Project:</span> <code class="code-pill">{{PROJECT_ID}}</code></span>
            <span class="meta-sep">•</span>
            <span class="meta-item"><span>Generated:</span> <span id="header-time">{{SNAPSHOT_TIME}}</span></span>
            <span id="provenance-sep" class="meta-sep">•</span>
            <span id="provenance-badge" class="badge"></span>
          </div>
        </div>
        <div class="header-controls">
          <a id="report-issue-btn" class="report-issue-btn"
             href="https://github.com/google/skills/issues/new"
             target="_blank" rel="noopener noreferrer"
             title="Open a pre-filled GitHub issue about this report (GitHub issues are public)">Report an Issue ↗</a>
          <div class="header-metric-label">Dashboard Metric</div>
          <div class="toggle-group" id="global-unit-toggle">
            <button onclick="setGlobalMetric('cost')" class="metric-toggle-btn active" id="btn-global-cost" data-metric="cost">Spend ($)</button>
            <button onclick="setGlobalMetric('volume')" class="metric-toggle-btn" id="btn-global-volume" data-metric="volume">Volume (GiB)</button>
          </div>
        </div>
      </div>
      <div id="header-billing-banner" class="banner-warning" style="display: none; margin-top: 6px;"></div>

      <!-- Degraded Telemetry Integrity Warning (Collapsible).
           Lives in the header rather than the Overview tab: the compromised
           days are still charted in the Service and Severity breakdowns, so
           the notice has to stay on screen on the tab where those dips are
           read. -->
      <details id="telemetry-integrity-banner" class="telemetry-banner" style="display: none;">
        <summary class="telemetry-banner-summary">
          <div class="telemetry-banner-header-left">
            <span class="telemetry-banner-icon">⚠</span>
            <span class="telemetry-banner-title"><strong>Notice:</strong> Cloud Monitoring metric under-reported log volume on some days</span>
          </div>
          <span class="telemetry-banner-toggle">
            <span class="telemetry-toggle-text">View details</span>
            <span class="telemetry-toggle-arrow">▼</span>
          </span>
        </summary>
        <div id="telemetry-integrity-body" class="telemetry-banner-body"></div>
      </details>
    </header>

    <!-- Navigation Tabs -->
    <nav class="nav-tabs" role="tablist">
      <button onclick="switchTab('tab-overview')" id="btn-tab-overview" class="tab-btn active">Overview</button>
      <button onclick="switchTab('tab-services')" id="btn-tab-services" class="tab-btn">Service & Severity Breakdowns</button>
      <button onclick="switchTab('tab-optimization')" id="btn-tab-optimization" class="tab-btn">Cost Optimizer</button>
    </nav>

    <!-- TAB 1: OVERVIEW -->
    <div id="tab-overview" class="tab-pane">
      <!-- KPI Metric Cards -->
      <div class="kpi-grid">
        <div class="card">
          <div class="card-header">
            <span id="kpi-cost-title">Latest Complete Spend</span>
            <span class="badge badge-success" id="kpi-cost-badge">—</span>
          </div>
          <div class="kpi-val" style="color: #34d399;" id="kpi-cost-val">—</div>
          <div class="kpi-subtext" id="kpi-cost-subtext">No complete month measured</div>
          <div class="kpi-actions">
            <button class="prove-btn" id="kpi-cost-prove" data-claim="latest_complete_spend" onclick="proveIt(this.dataset.claim)" style="display: none;"
                    title="Where this number comes from, and how to check it yourself"><span class="check">✓</span> Prove It</button>
          </div>
        </div>

        <div class="card">
          <div class="card-header">
            <span id="kpi-mtd-title">Current MTD Run-Rate</span>
            <span class="badge badge-primary" id="kpi-mtd-badge">—</span>
          </div>
          <div class="kpi-val" id="kpi-mtd-val">—</div>
          <div class="kpi-subtext" id="kpi-mtd-subtext">Run-rate not measured</div>
          <div class="kpi-actions">
            <button class="prove-btn" id="kpi-mtd-prove" data-claim="mtd_run_rate" onclick="proveIt(this.dataset.claim)" style="display: none;"
                    title="Where this number comes from, and how to check it yourself"><span class="check">✓</span> Prove It</button>
          </div>
        </div>

        <div class="card">
          <div class="card-header">
            <span>Top Cost Driver</span>
            <span class="badge badge-warning" id="kpi-driver-badge">—</span>
          </div>
          <div class="kpi-val" style="font-size: 20px; text-overflow: ellipsis; overflow: hidden; white-space: nowrap;" id="kpi-driver-name">—</div>
          <div class="kpi-subtext" id="kpi-driver-stat">Driver volume not measured</div>
          <div class="kpi-actions">
            <button class="prove-btn" data-claim="top_cost_driver" onclick="proveIt(this.dataset.claim)" style="display: none;"
                    title="Where this number comes from, and how to check it yourself"><span class="check">✓</span> Prove It</button>
          </div>
        </div>

        <div class="card">
          <div class="card-header">
            <span>Extraneous Log Spend</span>
            <span class="badge" style="background: var(--purple-subtle); color: #c084fc;" id="kpi-waste-badge">Floor</span>
          </div>
          <!-- Populated by renderExtraneousSpend(); shows an em-dash when unmeasured. -->
          <div class="kpi-val" style="color: #c084fc;" id="kpi-waste-val">—</div>
          <div class="kpi-subtext" id="kpi-waste-subtext">Awaiting waste analysis</div>
          <div class="kpi-actions">
            <button onclick="toggleExtraneousDetails(this)" id="kpi-waste-details-btn" class="copy-btn"
                    style="display: none; align-self: flex-start; padding: 3px 10px; font-size: 11px;">See details</button>
            <button class="prove-btn" data-claim="extraneous_spend" onclick="proveIt('extraneous_spend')" style="display: none;"
                    title="Where this number comes from, and how to check it yourself"><span class="check">✓</span> Prove It</button>
          </div>
        </div>
      </div>

      <!-- Extraneous Log Spend: inline detail panel (shown via the card's "See details" button) -->
      <div id="extraneous-details" class="chart-container" style="display: none;"></div>

      <!-- Executive Summary Slot -->
      <div class="slot-box">
        <!-- SLOT:EXECUTIVE_SUMMARY -->
      </div>

      <!-- 6-Month Visual Chart Section -->
      <div class="chart-container">
        <div class="chart-title-bar">
          <div>
            <h2 class="section-title" id="trend-chart-title">6-Month Ingestion & Spend History</h2>
            <p class="kpi-subtext" id="trend-chart-subtitle" style="margin-top: 2px;">Monthly ingestion volume (GiB) and cost trajectory over time</p>
          </div>
        </div>

        <!-- SVG Visual Bar Chart Container -->
        <div id="trend-svg-chart-container" style="width: 100%; min-height: 250px; padding: 10px 0;">
          <!-- Rendered dynamically by JS -->
        </div>
      </div>


    </div>

    <!-- TAB 2: SERVICES & SEVERITY -->
    <div id="tab-services" class="tab-pane hidden">
      <!-- Sub-Tab Navigation -->
      <div class="subnav-tabs" role="tablist">
        <button onclick="switchSubTab('subtab-severity')" id="btn-subtab-severity" class="subtab-btn active">By Severity</button>
        <button onclick="switchSubTab('subtab-service')" id="btn-subtab-service" class="subtab-btn">By Service</button>
        <button onclick="switchSubTab('subtab-details')" id="btn-subtab-details" class="subtab-btn">Service Details</button>
      </div>

      <!-- SUB-TAB 1: BY SEVERITY -->
      <div id="subtab-severity" class="subtab-pane">
        <!-- Daily 14-day Stacked Severity Bar Chart -->
        <div class="chart-container">
          <div class="chart-title-bar">
            <div>
              <h2 class="section-title" id="sev-daily-heading">14-Day Daily Severity Breakdown</h2>
              <p class="kpi-subtext" style="margin-top: 2px;">Daily log entry volume broken down by severity level</p>
              <div id="severity-missing-windows" style="display: none; font-size: 11px; color: var(--warning); margin-top: 6px; font-weight: 500;"></div>
            </div>
            <div id="severity-daily-legend" style="display: flex; flex-wrap: wrap; gap: 12px; font-size: 11px; color: var(--text-muted);">
              <!-- Rendered dynamically -->
            </div>
          </div>
          <div id="severity-daily-svg-chart-container" style="width: 100%; min-height: 250px; padding: 10px 0;">
            <!-- Rendered dynamically by JS -->
          </div>
        </div>

        <!-- 7 and 14 Day Severity Distributions -->
        <div>
          <h2 class="section-title" style="margin-bottom: 12px;" id="sev-dist-heading">Severity Distributions</h2>
          <div class="two-col-equal-grid">
            <div class="card" id="sev-pie-card-7d">
              <div class="card-header">
                <span style="font-weight: 700; color: var(--text);" id="sev-pie-title-7d">Prior 7 Days</span>
                <span class="badge badge-primary" id="sev-pie-badge-7d">7-Day Sum</span>
              </div>
              <div id="sev-donut-7d" style="width: 100%; min-height: 220px;"></div>
            </div>
            <div class="card" id="sev-pie-card-14d">
              <div class="card-header">
                <span style="font-weight: 700; color: var(--text);" id="sev-pie-title-14d">Prior 14 Days</span>
                <span class="badge badge-primary" id="sev-pie-badge-14d">14-Day Sum</span>
              </div>
              <div id="sev-donut-14d" style="width: 100%; min-height: 220px;"></div>
            </div>
          </div>
        </div>

        <!-- Severity Breakdown Table -->
        <div class="card" style="gap: 16px;">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <div>
              <h2 class="section-title">Severity Breakdown &amp; Analysis</h2>
              <p class="kpi-subtext" style="margin-top: 2px;">Ingestion volume and estimated cost per severity level</p>
            </div>
            <button class="prove-btn" data-claim="severity_costs" onclick="proveIt('severity_costs')" style="display: none;"
                    title="How these volumes and costs are derived, and how to check them yourself"><span class="check">✓</span> Prove It</button>
          </div>
          <div style="overflow-x: auto;">
            <table class="data-table">
              <thead>
                <tr>
                  <th>Severity</th>
                  <th id="sev-vol-col-label">14-Day Volume</th>
                  <th>Est. Cost</th>
                  <th>Share</th>
                </tr>
              </thead>
              <tbody id="severity-summary-tbody">
                <!-- Populated dynamically -->
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- SUB-TAB 2: BY SERVICE -->
      <div id="subtab-service" class="subtab-pane hidden">
        <!-- Daily 14-day Stacked Service Bar Chart -->
        <div class="chart-container">
          <div class="chart-title-bar">
            <div>
              <h2 class="section-title" id="svc-daily-heading">14-Day Daily Service Breakdown</h2>
              <p class="kpi-subtext" style="margin-top: 2px;">Daily log volume (GiB) broken down by top service</p>
            </div>
            <div id="service-daily-legend" style="display: flex; flex-wrap: wrap; gap: 12px; font-size: 11px; color: var(--text-muted);">
              <!-- Rendered dynamically -->
            </div>
          </div>
          <div id="service-daily-svg-chart-container" style="width: 100%; min-height: 250px; padding: 10px 0;">
            <!-- Rendered dynamically by JS -->
          </div>
        </div>

        <!-- 7 and 14 Day Service Distributions -->
        <div>
          <h2 class="section-title" style="margin-bottom: 12px;" id="svc-dist-heading">Service Distributions</h2>
          <div class="two-col-equal-grid">
            <div class="card" id="svc-pie-card-7d">
              <div class="card-header">
                <span style="font-weight: 700; color: var(--text);" id="svc-pie-title-7d">Prior 7 Days</span>
                <span class="badge badge-success" id="svc-pie-badge-7d">7-Day Sum</span>
              </div>
              <div id="svc-donut-7d" style="width: 100%; min-height: 220px;"></div>
            </div>
            <div class="card" id="svc-pie-card-14d">
              <div class="card-header">
                <span style="font-weight: 700; color: var(--text);" id="svc-pie-title-14d">Prior 14 Days</span>
                <span class="badge badge-success" id="svc-pie-badge-14d">14-Day Sum</span>
              </div>
              <div id="svc-donut-14d" style="width: 100%; min-height: 220px;"></div>
            </div>
          </div>
        </div>

        <!-- Service Breakdown Table -->
        <div class="card" style="gap: 16px;">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <div>
              <h2 class="section-title">Top Services Breakdown &amp; Analysis</h2>
              <p class="kpi-subtext" style="margin-top: 2px;">Ingestion volume and estimated cost per service</p>
            </div>
            <button class="prove-btn" data-claim="service_mix" onclick="proveIt('service_mix')" style="display: none;"
                    title="How these volumes and costs are derived, and how to check them yourself"><span class="check">✓</span> Prove It</button>
          </div>
          <div style="overflow-x: auto;">
            <table class="data-table">
              <thead>
                <tr>
                  <th>Service</th>
                  <th id="svc-vol-col-label">14-Day Volume</th>
                  <th>Est. Cost</th>
                  <th>Share</th>
                </tr>
              </thead>
              <tbody id="service-summary-tbody">
                <!-- Populated dynamically -->
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- SUB-TAB 3: SERVICE DETAILS -->
      <div id="subtab-details" class="subtab-pane hidden">
        <div class="two-col-grid">
          <!-- Left: Service List -->
          <div class="card" style="gap: 16px;">
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <h2 class="section-title">All Services</h2>
              <span class="badge" id="services-count-badge">—</span>
            </div>
            <input type="text" id="service-search-input" placeholder="Filter services by name..." class="search-box" oninput="filterServices(this.value)" />
            <div id="services-list-container" class="services-list">
              <!-- Populated by JS -->
            </div>
          </div>

          <!-- Right: Selected Service Details -->
          <div class="card" style="gap: 20px;">
            <div style="display: flex; justify-content: space-between; align-items: flex-start; border-bottom: 1px solid var(--border); padding-bottom: 14px;">
              <div>
                <div class="meta-text">SELECTED SERVICE</div>
                <h3 class="section-title" style="font-size: 20px; color: var(--text);" id="selected-svc-title">—</h3>
              </div>
              <div style="text-align: right; display: flex; flex-direction: column; align-items: flex-end;">
                <div class="meta-text">Volume / Cost</div>
                <div style="font-size: 16px; font-weight: 700; color: #34d399;" id="selected-svc-cost">—</div>
                <div style="font-size: 12px; color: var(--text-muted);" id="selected-svc-vol">—</div>
              </div>
            </div>

            <!-- Severity Bar -->
            <div style="display: flex; flex-direction: column; gap: 8px;">
              <div style="display: flex; justify-content: space-between; font-size: 12px;">
                <span style="font-weight: 600;" id="severity-breakdown-title">14-Day Severity Breakdown (SQL Analytics)</span>
                <span style="color: var(--text-muted);" id="selected-svc-sample-total">Sample: --</span>
              </div>
              <div id="severity-distribution-bar" class="severity-bar">
                <!-- Dynamically populated segments -->
              </div>
              <div style="display: flex; flex-wrap: wrap; gap: 14px; font-size: 11px; color: var(--text-muted); padding-top: 4px;">
                <div style="display: flex; align-items: center; gap: 6px;"><span style="width: 10px; height: 10px; border-radius: 50%; background: #94a3b8;"></span> DEFAULT</div>
                <div style="display: flex; align-items: center; gap: 6px;"><span style="width: 10px; height: 10px; border-radius: 50%; background: #3b82f6;"></span> DEBUG</div>
                <div style="display: flex; align-items: center; gap: 6px;"><span style="width: 10px; height: 10px; border-radius: 50%; background: #10b981;"></span> INFO</div>
                <div style="display: flex; align-items: center; gap: 6px;"><span style="width: 10px; height: 10px; border-radius: 50%; background: #ec4899;"></span> NOTICE</div>
                <div style="display: flex; align-items: center; gap: 6px;"><span style="width: 10px; height: 10px; border-radius: 50%; background: #f59e0b;"></span> WARNING</div>
                <div style="display: flex; align-items: center; gap: 6px;"><span style="width: 10px; height: 10px; border-radius: 50%; background: #ef4444;"></span> ERROR</div>
              </div>
            </div>

            <!-- Severity Table -->
            <div style="overflow-x: auto;">
              <table class="data-table">
                <thead>
                  <tr>
                    <th>Severity</th>
                    <th>Volume (Est.)</th>
                    <th>Cost (Est.)</th>
                    <th>Share</th>
                  </tr>
                </thead>
                <tbody id="selected-svc-tbody">
                  <!-- Dynamically populated -->
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- TAB 3: OPTIMIZATION & LEVERS -->
    <div id="tab-optimization" class="tab-pane hidden">
      <div id="optimization-actions" class="action-list">
        <!-- Populated by renderOptimizationActions() -->
      </div>
    </div>

  </div>

  <!-- Prove It drawer: rendered from `provenance.claims[<id>]` by proveIt(). -->
  <div id="prove-overlay" class="prove-overlay" onclick="closeProveIt()"></div>
  <aside id="prove-drawer" class="prove-drawer" role="dialog" aria-modal="true" aria-label="Prove It"></aside>

  <!-- Embedded JSON Data Payload -->
  <script id="finops-data" type="application/json">
{{FINOPS_JSON_DATA}}
  </script>

  <!-- Client-Side Hydration Script -->
  <script>
    let reportData = {};
    let activeService = null;

    let currentTrendMetric = 'cost';

    // Report an Issue. GitHub pre-fills a new issue from the `title` and
    // `body` query parameters. Issues there are public, so the body carries
    // only how this report was produced -- never the project ID, cost figures,
    // service names or log content.
    const ISSUE_TRACKER_URL = 'https://github.com/google/skills/issues/new';
    const ISSUE_TITLE_PREFIX = '[cloud-logging-finops] ';

    function buildIssueUrl() {
      const d = reportData || {};
      const status = (block) => (d[block] && d[block].status) || 'unknown';
      const activeTab = document.querySelector('.tab-btn.active');
      const generated = document.getElementById('header-time');
      const body = [
        // Rendered as a hidden comment in the issue. The markers are split so
        // this inline script never contains a literal HTML comment opener.
        '<' + '!-- GitHub issues are PUBLIC. Do not paste project IDs, cost figures, service names or log contents. --' + '>',
        '',
        '### What went wrong?',
        '',
        '',
        '### What did you expect instead?',
        '',
        '',
        '### Report details (filled in automatically)',
        '',
        '- Skill: cloud-logging-finops (Beta)',
        `- Report generated: ${generated ? generated.textContent.trim() : 'unknown'}`,
        `- Tab open when reporting: ${activeTab ? activeTab.textContent.trim() : 'unknown'}`,
        `- Billing data: ${status('billing_metadata')}`,
        `- Log Analytics: ${status('analytics_metadata')}`,
        `- Telemetry integrity: ${status('telemetry_integrity')}`,
        `- Pricing mode: ${(d.pricing && d.pricing.mode) || 'unknown'}`,
        `- Browser: ${navigator.userAgent}`,
      ].join('\n');
      const params = new URLSearchParams({ title: ISSUE_TITLE_PREFIX, body });
      return `${ISSUE_TRACKER_URL}?${params.toString()}`;
    }

    function wireIssueButton() {
      const btn = document.getElementById('report-issue-btn');
      if (!btn) return;
      btn.href = buildIssueUrl();
      // Rebuilt on click so the tab the reader is on is the one reported.
      btn.addEventListener('click', () => { btn.href = buildIssueUrl(); });
    }

    function initReport() {
      try {
        const rawJson = document.getElementById('finops-data').textContent;
        reportData = JSON.parse(rawJson);
        hydrateDashboard();
        revealProveButtons();
      } catch (err) {
        console.error('Error hydrating report:', err);
      } finally {
        // A reader whose report failed to render most needs a way to say so.
        try { wireIssueButton(); } catch (err) { console.error(err); }
      }
    }

    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', initReport);
    } else {
      initReport();
    }

    function switchTab(tabId) {
      document.querySelectorAll('.tab-pane').forEach(el => el.classList.add('hidden'));
      document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
      const target = document.getElementById(tabId);
      if (target) target.classList.remove('hidden');
      const btn = document.getElementById('btn-' + tabId);
      if (btn) btn.classList.add('active');
      if (tabId === 'tab-services') {
        const activeSubBtn = document.querySelector('.subnav-tabs .subtab-btn.active');
        const activeSubId = activeSubBtn ? activeSubBtn.id.replace('btn-', '') : 'subtab-severity';
        switchSubTab(activeSubId);
      }
    }

    function switchSubTab(subTabId) {
      document.querySelectorAll('.subtab-pane').forEach(el => el.classList.add('hidden'));
      document.querySelectorAll('.subtab-btn').forEach(btn => btn.classList.remove('active'));
      const target = document.getElementById(subTabId);
      if (target) target.classList.remove('hidden');
      const btn = document.getElementById('btn-' + subTabId);
      if (btn) btn.classList.add('active');
      if (subTabId === 'subtab-severity') {
        renderDailySeverityChart();
        renderSeverityPies();
      } else if (subTabId === 'subtab-service') {
        renderDailyServiceChart();
        renderServicePies();
      }
      syncSharedWindowLabels();
    }



    function setGlobalMetric(metric) {
      currentTrendMetric = metric;
      document.querySelectorAll('.metric-toggle-btn[data-metric]').forEach(btn => {
        btn.classList.toggle('active', btn.dataset.metric === metric);
      });
      renderTrendChart();
      renderDailySeverityChart();
      renderSeverityPies();
      renderDailyServiceChart();
      renderServicePies();

      const monthlyAggs = reportData.monthly_aggregations;
      const fullMonthKey = reportData.latest_complete_month;
      const fullMonth = fullMonthKey ? monthlyAggs[fullMonthKey] : null;
      const svcMap = fullMonth ? fullMonth.services_details : {};
      const services = Object.entries(svcMap).sort((a, b) => serviceGib(b[1]) - serviceGib(a[1]));
      renderServicesList(services, fullMonth);
    }

    function formatDollars(val) {
      if (val === undefined || val === null || isNaN(val)) return '—';
      return '$' + Number(val).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    function formatGiBCompact(gib) {
      if (gib === undefined || gib === null || isNaN(gib)) return '—';
      if (gib >= 1024) return (gib / 1024).toFixed(2) + ' TiB';
      return Number(gib).toFixed(2) + ' GiB';
    }



    // Invoiced months restate each service's measured share on the invoiced
    // volume, matching its cost_usd.
    function serviceGib(s) {
      return s.billed_gib ?? s.gib;
    }

    function hydrateDashboard() {
      const isTelemetryMode = !reportData.billing_metadata.invoiced;

      const banner = document.getElementById('header-billing-banner');
      const provBadge = document.getElementById('provenance-badge');
      // Two disclaimers for one fact read as two different facts. In estimated
      // mode the banner below says it in full, so the badge is suppressed
      // rather than repeating "Estimated" in three words of unexplained
      // shorthand. In invoiced mode there is no banner, so the badge is the
      // only place the provenance appears and it stays.
      if (provBadge) {
        if (isTelemetryMode) {
          provBadge.textContent = '';
          provBadge.style.display = 'none';
        } else {
          provBadge.textContent = 'Invoiced (Actual BQ Billing)';
          provBadge.className = 'badge badge-success';
          provBadge.style.display = '';
        }
        // The separator only makes sense when the badge follows it.
        const provSep = document.getElementById('provenance-sep');
        if (provSep) provSep.style.display = provBadge.style.display;
      }
      if (banner) {
        if (isTelemetryMode) {
          // Not built from `billing_metadata.fallback_chain`: which tiers were
          // searched does not change how a reader should read these numbers.
          const terms = Object.values(reportData.pricing.skus).map(t =>
            `${t.label} $${t.unit_price_per_gib.toFixed(2)}/GiB`
            + (t.free_gib ? ` after the ${t.free_gib} GiB/month free tier` : '')).join('; ');
          banner.textContent = `Because BigQuery Billing Export is not enabled, pricing is estimated from list prices (${terms}). Enable Billing Export for exact pricing data.`;
          banner.style.display = 'block';
        } else {
          // The banner's copy claims list pricing. Outside telemetry mode every
          // figure is priced off the invoice, so showing it would contradict
          // the rest of the report.
          banner.style.display = 'none';
        }
      }


      const t30 = reportData.trailing_30d_summary;
      const monthlyAggs = reportData.monthly_aggregations;
      const sortedMonths = Object.keys(monthlyAggs).sort();
      
      // The MTD card shows the projected month, never an older one.
      const proj = reportData.cost_projection;
      const currentMonthKey = monthlyAggs[proj.month] ? proj.month : null;
      const fullMonthKey = reportData.latest_complete_month;

      const fullMonth = fullMonthKey ? monthlyAggs[fullMonthKey] : null;
      const currentMonth = currentMonthKey ? monthlyAggs[currentMonthKey] : null;

      // Update Chart Title based on reporting mode
      const chartTitleEl = document.getElementById('trend-chart-title');
      const chartSubEl = document.getElementById('trend-chart-subtitle');
      if (chartTitleEl) {
        chartTitleEl.textContent = `${sortedMonths.length}-Month Ingestion & Spend History`;
      }
      if (isTelemetryMode && chartTitleEl) {
        chartTitleEl.textContent = "Trailing 4-Week Ingestion & Cost Trend";
        if (chartSubEl) chartSubEl.textContent = "Weekly volume and estimated cost trajectory (W-4 to W-1) within Cloud Monitoring retention";
      }

      // 1. Overview KPIs
      if (isTelemetryMode && t30) {
        const title1 = document.getElementById('kpi-cost-title');
        if (title1) title1.textContent = "Trailing 30-Day Volume";
        document.getElementById('kpi-cost-badge').textContent = "Last 30 Days";
        document.getElementById('kpi-cost-val').textContent = formatGiBCompact(t30.total_gib);
        document.getElementById('kpi-cost-subtext').textContent = `Daily Avg: ${t30.daily_avg_gib.toFixed(2)} GiB/day`;

        const title2 = document.getElementById('kpi-mtd-title');
        if (title2) title2.textContent = "Estimated Monthly Run-Rate";
        document.getElementById('kpi-mtd-badge').textContent = "Projected";
        document.getElementById('kpi-mtd-val').textContent = formatDollars(t30.projected_monthly_cost_usd);
        document.getElementById('kpi-mtd-subtext').textContent = `Annualized: ${formatDollars(t30.projected_annual_cost_usd)}`;

        // These cards show different figures from the invoiced ones, so their
        // Prove It buttons open the claims that prove these figures
        // (provenance.py: _trailing_30d_volume, _estimated_run_rate).
        const costProve = document.getElementById('kpi-cost-prove');
        if (costProve) costProve.dataset.claim = 'trailing_30d_volume';
        const mtdProve = document.getElementById('kpi-mtd-prove');
        if (mtdProve) mtdProve.dataset.claim = 'estimated_run_rate';

        // Ranked once by the collector (aggregations.top_driver).
        const top = t30.top_services.find(s => s.service === t30.top_driver);
        if (top) {
          document.getElementById('kpi-driver-name').textContent = top.service;
          document.getElementById('kpi-driver-badge').textContent = top.pct_of_total.toFixed(1) + '%';
          document.getElementById('kpi-driver-stat').textContent = top.gib.toFixed(2) + ' GiB • ' + formatDollars(top.cost_usd) + '/mo';
        } else {
          document.getElementById('kpi-driver-name').textContent = '—';
          document.getElementById('kpi-driver-badge').textContent = '—';
          document.getElementById('kpi-driver-stat').textContent = 'Driver volume not measured';
        }
      } else {
        if (fullMonth) {
          // A month before the export began is a telemetry estimate; never
          // present it as complete invoiced spend.
          const estimated = fullMonth.data_source !== 'actual_bq_billing';
          document.getElementById('kpi-cost-title').textContent =
            estimated ? 'Latest Complete Month (Estimated)' : 'Latest Complete Spend';
          document.getElementById('kpi-cost-badge').textContent = fullMonthKey;
          document.getElementById('kpi-cost-val').textContent = formatDollars(fullMonth.net_cost_usd);
          document.getElementById('kpi-cost-subtext').textContent = fullMonth.total_gib.toFixed(2) + ' GiB ingested'
            + (estimated ? ' · list-price estimate, before the billing export began' : '');
        } else {
          document.getElementById('kpi-cost-badge').textContent = '—';
          document.getElementById('kpi-cost-val').textContent = '—';
          if (sortedMonths.length > 0) {
            const reason = monthlyAggs[sortedMonths[sortedMonths.length-1]].partial_reason || 'partial data';
            document.getElementById('kpi-cost-subtext').textContent = 'No complete month (' + reason + ')';
          } else {
            document.getElementById('kpi-cost-subtext').textContent = 'No complete month measured';
          }
        }

        if (currentMonth) {
          document.getElementById('kpi-mtd-badge').textContent = currentMonthKey + ' (MTD)';
          document.getElementById('kpi-mtd-val').textContent = formatDollars(currentMonth.net_cost_usd);
          document.getElementById('kpi-mtd-subtext').textContent = 'Projected EOM: ' + formatDollars(proj.projected_eom_cost_usd);
        } else {
          document.getElementById('kpi-mtd-badge').textContent = '—';
          document.getElementById('kpi-mtd-val').textContent = '—';
          document.getElementById('kpi-mtd-subtext').textContent = 'Run-rate not measured';
        }

        // Ranked once by the collector (monthly_aggregations[m].top_service).
        const topName = fullMonth ? fullMonth.top_service : null;
        if (topName) {
          const top = fullMonth.services_details[topName];
          document.getElementById('kpi-driver-name').textContent = topName;
          document.getElementById('kpi-driver-badge').textContent = top.pct_of_volume.toFixed(1) + '%';
          document.getElementById('kpi-driver-stat').textContent = serviceGib(top).toFixed(2) + ' GiB • ' + formatDollars(top.cost_usd);
        } else {
          document.getElementById('kpi-driver-name').textContent = '—';
          document.getElementById('kpi-driver-badge').textContent = '—';
          document.getElementById('kpi-driver-stat').textContent = 'Driver volume not measured';
        }
      }

      // 4th KPI card: measured extraneous (excludable) spend floor.
      renderExtraneousSpend();

      const telemetryIntegrity = reportData.telemetry_integrity;
      const metricsBanner = document.getElementById('telemetry-integrity-banner');
      const metricsBody = document.getElementById('telemetry-integrity-body');
      if (metricsBanner) {
        const ti = telemetryIntegrity;
        if (ti.status === 'degraded' && ti.compromised_days.length) {
          const volumeBasis = reportData.trailing_30d_summary.volume_basis;
          // Two different reassurances, because with no billing export the
          // money figures rest on the same damaged metric and promising the
          // reader they are correct would be false.
          const scope = volumeBasis === 'invoiced_daily_usage'
            ? 'Spend, volume and run-rate figures in this report are read from your Cloud Billing export and are unaffected. What is affected is the breakdown by service and by severity, which can only be measured from this metric.'
            : 'This project has no Cloud Billing export, so the spend and volume figures rest on the same metric and should be treated as a lower bound.';
          if (metricsBody) {
            // The affected days stay in the charts -- the metric is the only
            // source the breakdowns have -- so the reader is told to read those
            // days as a metric defect rather than as a drop in logging.
            metricsBody.innerHTML =
              '<p style="margin-bottom: 6px;"><strong>A Google Cloud metric under-reported this project\u2019s log volume.</strong> ' + escapeHtml(scope) + '</p>' +
              '<p style="margin-bottom: 6px;"><strong>Effect on the breakdowns:</strong> the Service &amp; Severity tabs still plot every day in the window, so the affected days appear as dips that the metric invented rather than volume your project stopped sending.</p>' +
              (ti.note ? '<p style="margin-bottom: 6px; color: var(--text-muted);">' + escapeHtml(ti.note) + '</p>' : '') +
              '<p style="color: var(--text-muted); font-size: 10px;">This is a known defect in Google\u2019s metric pipeline rather than anything to fix in your project, and the affected days will not correct themselves.</p>';
          }
          const toggleText = metricsBanner.querySelector('.telemetry-toggle-text');
          if (toggleText && !metricsBanner._hasToggleListener) {
            metricsBanner._hasToggleListener = true;
            metricsBanner.addEventListener('toggle', () => {
              toggleText.textContent = metricsBanner.open ? 'Hide details' : 'View details';
            });
          }
          metricsBanner.style.display = 'block';
        } else {
          metricsBanner.style.display = 'none';
        }
      }

      const activeServicesMonth = fullMonth || currentMonth;
      const svcMap = activeServicesMonth ? activeServicesMonth.services_details : {};
      const services = Object.entries(svcMap).sort((a, b) => serviceGib(b[1]) - serviceGib(a[1]));

      // Render 6-month or 4-week visual SVG chart
      renderTrendChart();
      // Render Sub-tab charts
      renderDailySeverityChart();
      renderDailyServiceChart();
      renderSeverityPies();
      renderServicePies();
      syncSharedWindowLabels();
      // Render Services Tab Details
      renderServicesList(services, activeServicesMonth);
      renderOptimizationActions();
    }

    function renderTrendChart() {
      const container = document.getElementById('trend-svg-chart-container');
      if (!container) return;

      const isCost = currentTrendMetric === 'cost';
      const isTelemetryMode = !reportData.billing_metadata.invoiced;

      let items = [];
      const width = 800;
      const height = 230;
      const padLeft = 65;
      const padRight = 30;
      const padTop = 30;
      const padBottom = 35;
      const chartW = width - padLeft - padRight;
      const chartH = height - padTop - padBottom;

      if (isTelemetryMode && Object.keys(reportData.weekly_aggregations).length > 0) {
        const weeklyAggs = reportData.weekly_aggregations;
        const weekKeys = ['W-4', 'W-3', 'W-2', 'W-1'].filter(k => weeklyAggs[k]);
        items = weekKeys.map((w, idx) => {
          const wData = weeklyAggs[w];
          const val = isCost ? wData.cost_usd : wData.total_gib;
          const isLatest = idx === weekKeys.length - 1;
          const dateRange = `${wData.start_date.slice(5)} to ${wData.end_date.slice(5)}`;
          return {
            key: w,
            val: val,
            isCurrent: isLatest,
            topLabel: isCost ? formatDollars(val) : formatGiBCompact(val),
            xLabel: `${w} (${dateRange})`,
            tooltip: `${w} (${wData.start_date} to ${wData.end_date}): ${formatDollars(wData.cost_usd)} (${wData.total_gib.toFixed(2)} GiB)`
          };
        });
      } else {
        const monthlyAggs = reportData.monthly_aggregations;
        const months = Object.keys(monthlyAggs).sort();
        if (months.length === 0) return;

        items = months.map((m, idx) => {
          const mData = monthlyAggs[m];
          const val = isCost ? mData.net_cost_usd : mData.total_gib;
          const isCurrent = idx === months.length - 1;
          const parts = m.split('-');
          const monthNum = parseInt(parts[1], 10);
          const monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
          const monthShort = monthNames[monthNum - 1] || m;
          let xLabel = isCurrent ? `${monthShort} (MTD)` : `${monthShort} '${parts[0].slice(2)}`;
          if (!isCurrent && mData.is_partial === true) {
            const reason = mData.partial_reason || `${mData.coverage_days || 0}d`;
            xLabel += ` (${escapeHtml(reason)})`;
          }
          return {
            key: m,
            val: val,
            isCurrent: isCurrent,
            topLabel: isCost ? formatDollars(val) : formatGiBCompact(val),
            xLabel: xLabel,
            tooltip: `${escapeHtml(m)}: ${formatDollars(mData.net_cost_usd)} (${formatGiBCompact(mData.total_gib)})`
          };
        });
      }

      if (items.length === 0) return;

      const values = items.map(it => it.val);
      const maxVal = Math.max(...values, 1);
      const yMax = maxVal * 1.2;

      const barWidth = Math.min(60, (chartW / items.length) * 0.52);
      const step = chartW / items.length;

      let yAxisSvg = '';
      const yTicks = 4;
      for (let i = 0; i <= yTicks; i++) {
        const val = (yMax / yTicks) * i;
        const yPos = padTop + chartH - (i / yTicks) * chartH;
        let label = '';
        if (isCost) {
          label = '$' + (val >= 1000 ? (val / 1000).toFixed(val % 1000 === 0 ? 0 : 1) + 'k' : val.toFixed(0));
        } else {
          label = (val >= 1000 ? (val / 1000).toFixed(val % 1000 === 0 ? 0 : 1) + 'k' : val.toFixed(0)) + ' GiB';
        }
        yAxisSvg += `
          <line x1="${padLeft}" y1="${yPos}" x2="${width - padRight}" y2="${yPos}" stroke="#334155" stroke-dasharray="3,3" stroke-width="1" />
          <text x="${padLeft - 10}" y="${yPos + 4}" text-anchor="end" fill="#94a3b8" font-size="11" font-family="system-ui, sans-serif">${label}</text>
        `;
      }

      let barsSvg = '';
      items.forEach((it, idx) => {
        const val = it.val;
        const barH = Math.max(4, (val / yMax) * chartH);
        const x = padLeft + (idx * step) + (step - barWidth) / 2;
        const y = padTop + chartH - barH;

        const isCurrent = it.isCurrent;
        const barFill = isCurrent ? 'url(#striped-accent)' : (isCost ? '#10b981' : '#3b82f6');
        const strokeColor = isCurrent ? (isCost ? '#34d399' : '#60a5fa') : 'none';

        barsSvg += `
          <g style="cursor: pointer;">
            <!-- Top Value -->
            <text x="${x + barWidth / 2}" y="${y - 8}" text-anchor="middle" fill="${isCurrent ? '#fbbf24' : '#f8fafc'}" font-size="11" font-weight="700" font-family="system-ui, sans-serif">${it.topLabel}</text>
            <!-- Bar -->
            <rect x="${x}" y="${y}" width="${barWidth}" height="${barH}" rx="5" ry="5" fill="${barFill}" stroke="${strokeColor}" stroke-width="${isCurrent ? 2 : 0}">
              <title>${escapeHtml(it.tooltip)}</title>
            </rect>
            <!-- X Axis Label -->
            <text x="${x + barWidth / 2}" y="${height - 8}" text-anchor="middle" fill="${isCurrent ? '#fbbf24' : '#94a3b8'}" font-size="11" font-weight="${isCurrent ? '700' : '500'}" font-family="system-ui, sans-serif">${it.xLabel}</text>
          </g>
        `;
      });

      const svgHtml = `
        <svg viewBox="0 0 ${width} ${height}" style="width: 100%; height: auto; display: block; overflow: visible;">
          <defs>
            <pattern id="striped-accent" width="8" height="8" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse">
              <line x1="0" y1="0" x2="0" y2="8" stroke="${isCost ? '#10b981' : '#3b82f6'}" stroke-width="3" />
              <line x1="4" y1="0" x2="4" y2="8" stroke="#1e293b" stroke-width="5" />
            </pattern>
          </defs>
          ${yAxisSvg}
          ${barsSvg}
        </svg>
      `;

      container.innerHTML = svgHtml;
    }




    const sevColors = {
      'DEFAULT': '#94a3b8',
      'DEBUG': '#3b82f6',
      'INFO': '#10b981',
      // Must stay clearly apart from INFO's green: teal (#14b8a6) was
      // reported as indistinguishable from it.
      'NOTICE': '#ec4899',
      'WARNING': '#f59e0b',
      'ERROR': '#ef4444',
      'CRITICAL': '#be123c',
      'ALERT': '#9333ea',
      'EMERGENCY': '#7f1d1d'
    };
    const sevOrder = ['DEFAULT', 'DEBUG', 'INFO', 'NOTICE', 'WARNING', 'ERROR', 'CRITICAL', 'ALERT', 'EMERGENCY'];

    // No daily series means the views render their empty states; nothing is
    // spread over invented days.
    function getDailySeverityData() {
      return reportData.severity_summary.daily_severity;
    }

    function getDailyServicesData() {
      return reportData.daily_services;
    }

    // The severity and service breakdowns share one window so their "N-Day"
    // labels describe the same days: the union of both maps' days (a day in
    // only one map is still real data), restricted to days with billed bytes
    // in daily_services, since every rendered volume -- severity included --
    // is apportioned from them.
    const SHARED_WINDOW_MAX_DAYS = 14;
    const SHARED_WINDOW_SHORT_DAYS = 7;
    let _sharedWindowCache = null;

    function getSharedWindowDates(maxDays = SHARED_WINDOW_MAX_DAYS) {
      if (_sharedWindowCache && _sharedWindowCache.maxDays === maxDays) {
        return _sharedWindowCache.dates;
      }
      const dailySvc = getDailyServicesData();
      const hasByteBasis = d =>
        Object.values(dailySvc[d] || {}).reduce((a, b) => a + b, 0) > 0;
      const days = new Set([
        ...Object.keys(getDailySeverityData()),
        ...Object.keys(dailySvc)
      ]);
      const dates = Array.from(days).filter(hasByteBasis).sort().slice(-maxDays);
      _sharedWindowCache = { maxDays, dates };
      return dates;
    }

    // One place sets every "14-Day" label, so the headline day count can never
    // drift from the window the charts actually plot: a project holding only a
    // few days of telemetry says so instead of claiming a full window.
    function syncSharedWindowLabels() {
      const n = getSharedWindowDates().length;
      if (!n) return;
      const set = (id, text) => {
        const el = document.getElementById(id);
        if (el) el.textContent = text;
      };
      set('sev-vol-col-label', `${n}-Day Volume`);
      set('svc-vol-col-label', `${n}-Day Volume`);
      set('sev-daily-heading', `${n}-Day Daily Severity Breakdown`);
      set('svc-daily-heading', `${n}-Day Daily Service Breakdown`);
      set('sev-pie-title-14d', `Prior ${n} Days`);
      set('svc-pie-title-14d', `Prior ${n} Days`);
      const shortWindow = Math.min(SHARED_WINDOW_SHORT_DAYS, n);
      set('sev-pie-title-7d', `Prior ${shortWindow} Days`);
      set('svc-pie-title-7d', `Prior ${shortWindow} Days`);
      set('sev-dist-heading', `Severity Distributions (${shortWindow} and ${n} Days)`);
      set('svc-dist-heading', `Service Distributions (${shortWindow} and ${n} Days)`);
    }

    // Log Storage and Vended Logs Storage are billed at different unit prices
    // and only Log Storage has a free tier. `pricing` (see pricing.py)
    // publishes each SKU's effective rate -- its baseline cost over its
    // baseline GiB -- and which resource types it bills. A blended book has
    // one `blended` SKU that prices every service.
    function rateForService(name) {
      const p = reportData.pricing;
      if (p.mode !== 'per_sku') return p.skus.blended.effective_rate_per_gib;
      const vended = p.vended_resource_types.indexOf(name) >= 0;
      const sku = p.skus[vended ? 'vended' : 'log_storage'] || p.skus.log_storage;
      return sku.effective_rate_per_gib;
    }

    function getDailySeverityMetrics() {
      const dailySev = getDailySeverityData();
      const dailySvc = getDailyServicesData();

      // Every day in the shared window is guaranteed to carry billed bytes, so
      // the weights below always have a level to be applied to.
      const dates = getSharedWindowDates();

      const data = {};
      dates.forEach(d => {
        data[d] = {};
        const dSev = dailySev[d] || {};
        // daily_severity carries bytes, not entry counts (see
        // aggregations.get_severity_summary). Only the weights are used here:
        // the absolute level always comes from the billed service bytes below,
        // never from the Log Analytics content bytes these weights are made of.
        const rawSevTotal = Object.values(dSev).reduce((a, b) => a + b, 0);

        const dSvc = dailySvc[d] || {};
        const dSvcBytes = Object.values(dSvc).reduce((a, b) => a + b, 0);
        const dayTotalGiB = dSvcBytes / (1024 * 1024 * 1024);
        // The day's dollars priced service by service, so a severity's share
        // of the day carries the day's real SKU mix.
        const dayCost = Object.entries(dSvc).reduce(
          (acc, [sName, bytes]) => acc + (bytes / (1024 * 1024 * 1024)) * rateForService(sName), 0);

        Object.entries(dSev).forEach(([sev, rawVal]) => {
          const frac = rawSevTotal > 0 ? (rawVal / rawSevTotal) : 0;
          const sevGiB = frac * dayTotalGiB;
          data[d][sev] = {
            gib: sevGiB,
            cost: frac * dayCost,
            weight: rawVal,
            pct: frac * 100
          };
        });
      });
      return { dates, data };
    }

    function getDailyServiceMetrics() {
      const dailySvc = getDailyServicesData();
      const dates = getSharedWindowDates();

      const data = {};
      dates.forEach(d => {
        data[d] = {};
        const dSvc = dailySvc[d] || {};
        const dSvcBytes = Object.values(dSvc).reduce((a, b) => a + b, 0);

        Object.entries(dSvc).forEach(([sName, bytes]) => {
          const sGib = bytes / (1024 * 1024 * 1024);
          const frac = dSvcBytes > 0 ? (bytes / dSvcBytes) : 0;
          data[d][sName] = {
            gib: sGib,
            cost: sGib * rateForService(sName),
            bytes: bytes,
            pct: frac * 100
          };
        });
      });
      return { dates, data };
    }

    function renderSvgDonut(containerId, slices, totalCenterText, subCenterText, maxLegend = 5) {
      const container = document.getElementById(containerId);
      if (!container) return;

      const validSlices = slices.filter(s => s.value > 0);
      const total = validSlices.reduce((acc, s) => acc + s.value, 0);

      if (total <= 0 || validSlices.length === 0) {
        container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:180px;color:var(--text-muted);font-size:12px;">No data available</div>';
        return;
      }

      const size = 180;
      const cx = size / 2;
      const cy = size / 2;
      const rOut = 75;
      const rIn = 48;

      let pathsSvg = '';
      let currentAngle = -Math.PI / 2;

      if (validSlices.length === 1) {
        const s = validSlices[0];
        pathsSvg = `
          <circle cx="${cx}" cy="${cy}" r="${(rOut + rIn) / 2}" fill="none" stroke="${s.color}" stroke-width="${rOut - rIn}">
            <title>${escapeHtml(s.label)}: ${escapeHtml(s.formattedValue)} (100%)</title>
          </circle>
        `;
      } else {
        validSlices.forEach(s => {
          const fraction = s.value / total;
          const angle = fraction * 2 * Math.PI;
          const aStart = currentAngle;
          const aEnd = currentAngle + angle;

          const x1 = cx + rOut * Math.cos(aStart);
          const y1 = cy + rOut * Math.sin(aStart);
          const x2 = cx + rOut * Math.cos(aEnd);
          const y2 = cy + rOut * Math.sin(aEnd);
          const x3 = cx + rIn * Math.cos(aEnd);
          const y3 = cy + rIn * Math.sin(aEnd);
          const x4 = cx + rIn * Math.cos(aStart);
          const y4 = cy + rIn * Math.sin(aStart);

          const largeArc = angle > Math.PI ? 1 : 0;
          const pathD = `M ${x1.toFixed(2)} ${y1.toFixed(2)} A ${rOut} ${rOut} 0 ${largeArc} 1 ${x2.toFixed(2)} ${y2.toFixed(2)} L ${x3.toFixed(2)} ${y3.toFixed(2)} A ${rIn} ${rIn} 0 ${largeArc} 0 ${x4.toFixed(2)} ${y4.toFixed(2)} Z`;

          pathsSvg += `
            <path d="${pathD}" fill="${s.color}" stroke="var(--bg-card, #1e293b)" stroke-width="1.5">
              <title>${escapeHtml(s.label)}: ${escapeHtml(s.formattedValue)} (${(fraction * 100).toFixed(1)}%)</title>
            </path>
          `;

          currentAngle += angle;
        });
      }

      const limit = (typeof maxLegend === 'number' && maxLegend > 0 && isFinite(maxLegend)) ? maxLegend : null;
      const displaySlices = limit ? validSlices.slice(0, limit) : validSlices;

      let legendHtml = '<div style="display:flex;flex-direction:column;gap:5px;margin-top:12px;width:100%;font-size:11px;">';
      displaySlices.forEach(s => {
        const pct = (s.value / total * 100).toFixed(1);
        legendHtml += `
          <div style="display:flex;justify-content:space-between;align-items:center;">
            <div style="display:flex;align-items:center;gap:6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:130px;">
              <span style="width:8px;height:8px;border-radius:50%;background:${s.color};flex-shrink:0;"></span>
              <span style="color:var(--text);overflow:hidden;text-overflow:ellipsis;" title="${escapeHtml(s.label)}">${escapeHtml(s.label)}</span>
            </div>
            <div style="display:flex;gap:6px;color:var(--text-muted);font-weight:600;">
              <span>${escapeHtml(s.formattedValue)}</span>
              <span style="color:var(--text);width:36px;text-align:right;">${pct}%</span>
            </div>
          </div>
        `;
      });
      if (limit && validSlices.length > limit) {
        const otherVal = validSlices.slice(limit).reduce((acc, s) => acc + s.value, 0);
        const otherPct = (otherVal / total * 100).toFixed(1);
        legendHtml += `
          <div style="display:flex;justify-content:space-between;align-items:center;color:var(--text-muted);">
            <div style="display:flex;align-items:center;gap:6px;">
              <span style="width:8px;height:8px;border-radius:50%;background:#64748b;flex-shrink:0;"></span>
              <span>+ ${validSlices.length - limit} more</span>
            </div>
            <span style="width:36px;text-align:right;">${otherPct}%</span>
          </div>
        `;
      }
      legendHtml += '</div>';

      container.innerHTML = `
        <div style="display:flex;flex-direction:column;align-items:center;width:100%;">
          <div style="position:relative;width:${size}px;height:${size}px;">
            <svg viewBox="0 0 ${size} ${size}" style="width:100%;height:100%;display:block;">
              ${pathsSvg}
            </svg>
            <div style="position:absolute;top:0;left:0;width:100%;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;pointer-events:none;text-align:center;padding:8px;">
              <div style="font-size:13px;font-weight:700;color:var(--text);line-height:1.2;">${escapeHtml(totalCenterText)}</div>
              <div style="font-size:10px;color:var(--text-muted);margin-top:2px;">${escapeHtml(subCenterText)}</div>
            </div>
          </div>
          ${legendHtml}
        </div>
      `;
    }

    function renderDailySeverityChart() {
      const container = document.getElementById('severity-daily-svg-chart-container');
      const legend = document.getElementById('severity-daily-legend');
      if (!container) return;

      const { dates, data: dailyMetrics } = getDailySeverityMetrics();
      const isCost = currentTrendMetric === 'cost';
      const titleEl = document.querySelector('#subtab-severity .section-title');
      if (titleEl && dates.length > 0) titleEl.textContent = `${dates.length}-Day Daily Severity Breakdown`;
      const subEl = document.querySelector('#subtab-severity .kpi-subtext');
      if (subEl) subEl.textContent = isCost ? 'Daily estimated spend trajectory ($) broken down by severity level' : 'Daily log entry volume broken down by severity level';

      const hasSeverity = dates.some(d => Object.keys(dailyMetrics[d] || {}).length > 0);
      if (!hasSeverity) {
        container.innerHTML = '<div style="color:var(--text-muted);padding:20px;text-align:center;">No severity daily telemetry available.</div>';
        return;
      }

      const missingWindowsEl = document.getElementById('severity-missing-windows');
      const missingWindows = reportData.severity_summary.missing_windows;
      if (missingWindowsEl) {
        if (missingWindows.length > 0) {
          missingWindowsEl.innerHTML = `⚠ <strong>LOWER BOUND:</strong> Partial Cloud Monitoring fetch. Missing data for: ${escapeHtml(missingWindows.join(', '))}`;
          missingWindowsEl.style.display = 'block';
        } else {
          missingWindowsEl.style.display = 'none';
        }
      }

      if (legend) {
        const presentSevs = new Set();
        dates.forEach(d => Object.keys(dailyMetrics[d] || {}).forEach(s => presentSevs.add(s)));
        let legHtml = '';
        sevOrder.filter(s => presentSevs.has(s)).forEach(s => {
          legHtml += `
            <div style="display:flex;align-items:center;gap:6px;">
              <span style="width:10px;height:10px;border-radius:50%;background:${sevColors[s] || '#94a3b8'};"></span>
              <span>${escapeHtml(s)}</span>
            </div>
          `;
        });
        legend.innerHTML = legHtml;
      }

      const dailyTotals = dates.map(d => {
        const dObj = dailyMetrics[d] || {};
        return Object.values(dObj).reduce((acc, item) => acc + (isCost ? item.cost : item.gib), 0);
      });

      const maxVal = Math.max(...dailyTotals, 0.1);
      const yMax = maxVal * 1.25;

      const width = 800;
      const height = 230;
      const padLeft = 65;
      const padRight = 30;
      const padTop = 30;
      const padBottom = 35;
      const chartW = width - padLeft - padRight;
      const chartH = height - padTop - padBottom;

      const barWidth = Math.min(42, (chartW / dates.length) * 0.65);
      const step = chartW / dates.length;

      let yAxisSvg = '';
      const yTicks = 4;
      for (let i = 0; i <= yTicks; i++) {
        const val = (yMax / yTicks) * i;
        const yPos = padTop + chartH - (i / yTicks) * chartH;
        let label = isCost
          ? ('$' + (val >= 1000 ? (val / 1000).toFixed(val % 1000 === 0 ? 0 : 1) + 'k' : val.toFixed(val < 10 ? 2 : 0)))
          : ((val >= 1000 ? (val / 1000).toFixed(val % 1000 === 0 ? 0 : 1) + 'k' : val.toFixed(val < 10 ? 1 : 0)) + ' GiB');
        yAxisSvg += `
          <line x1="${padLeft}" y1="${yPos}" x2="${width - padRight}" y2="${yPos}" stroke="#334155" stroke-dasharray="3,3" stroke-width="1" />
          <text x="${padLeft - 10}" y="${yPos + 4}" text-anchor="end" fill="#94a3b8" font-size="11" font-family="system-ui, sans-serif">${label}</text>
        `;
      }

      let barsSvg = '';
      dates.forEach((d, idx) => {
        const dObj = dailyMetrics[d] || {};
        const total = dailyTotals[idx];
        const x = padLeft + (idx * step) + (step - barWidth) / 2;

        let curY = padTop + chartH;
        let segsSvg = '';

        sevOrder.forEach(sev => {
          const item = dObj[sev];
          const val = item ? (isCost ? item.cost : item.gib) : 0;
          if (item && val > 0) {
            const segH = (val / yMax) * chartH;
            curY -= segH;
            const pct = item.pct.toFixed(1);
            const formattedVal = isCost ? formatDollars(item.cost) : formatGiBCompact(item.gib);
            const tip = `${d} • ${escapeHtml(sev)}: ${formattedVal} (${pct}%)`;
            segsSvg += `
              <rect x="${x}" y="${curY}" width="${barWidth}" height="${segH}" fill="${sevColors[sev] || '#94a3b8'}">
                <title>${escapeHtml(tip)}</title>
              </rect>
            `;
          }
        });

        const dParts = d.split('-');
        const monthNum = parseInt(dParts[1], 10);
        const monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
        const xLabel = `${monthNames[monthNum - 1]} ${dParts[2]}`;
        const topLabel = isCost ? formatDollars(total) : formatGiBCompact(total);

        barsSvg += `
          <g style="cursor: pointer;">
            <text x="${x + barWidth / 2}" y="${curY - 8}" text-anchor="middle" fill="#f8fafc" font-size="10" font-weight="700" font-family="system-ui, sans-serif">${topLabel}</text>
            ${segsSvg}
            <text x="${x + barWidth / 2}" y="${height - 8}" text-anchor="middle" fill="#94a3b8" font-size="11" font-weight="500" font-family="system-ui, sans-serif">${xLabel}</text>
          </g>
        `;
      });

      container.innerHTML = `
        <svg viewBox="0 0 ${width} ${height}" style="width: 100%; height: auto; display: block; overflow: visible;">
          ${yAxisSvg}
          ${barsSvg}
        </svg>
      `;
    }

    function renderSeverityPies() {
      const { dates, data: dailyMetrics } = getDailySeverityMetrics();
      if (dates.length === 0) return;

      const isCost = currentTrendMetric === 'cost';
      const windows = [
        { id: 'sev-donut-7d', badgeId: 'sev-pie-badge-7d', days: SHARED_WINDOW_SHORT_DAYS },
        { id: 'sev-donut-14d', badgeId: 'sev-pie-badge-14d', days: SHARED_WINDOW_MAX_DAYS },
      ];

      windows.forEach(w => {
        const sliceDates = dates.slice(-w.days);
        const badge = document.getElementById(w.badgeId);
        if (badge && sliceDates.length > 0) {
          badge.textContent = sliceDates.length === 1 ? sliceDates[0] : `${sliceDates[0]} to ${sliceDates[sliceDates.length - 1]}`;
        }

        const sevSum = {};
        sliceDates.forEach(d => {
          const dObj = dailyMetrics[d] || {};
          Object.entries(dObj).forEach(([sev, item]) => {
            if (!sevSum[sev]) sevSum[sev] = { gib: 0, cost: 0 };
            sevSum[sev].gib += item.gib;
            sevSum[sev].cost += item.cost;
          });
        });

        const totalGib = Object.values(sevSum).reduce((acc, item) => acc + item.gib, 0);
        const totalVal = isCost ? Object.values(sevSum).reduce((acc, item) => acc + item.cost, 0) : totalGib;
        const slices = sevOrder.filter(s => sevSum[s] && sevSum[s].gib > 0).map(s => {
          const val = isCost ? sevSum[s].cost : sevSum[s].gib;
          return {
            label: s,
            value: val,
            formattedValue: isCost ? formatDollars(val) : formatGiBCompact(val),
            color: sevColors[s] || '#94a3b8'
          };
        });

        renderSvgDonut(w.id, slices, isCost ? formatDollars(totalVal) : formatGiBCompact(totalGib), `${sliceDates.length}-Day Total`, 6);
      });

      // Populate severity-summary-tbody (14-day window breakdown)
      const tbody = document.getElementById('severity-summary-tbody');
      if (!tbody) return;
      tbody.innerHTML = '';

      const sev14 = {};
      dates.forEach(d => {
        const dObj = dailyMetrics[d] || {};
        Object.entries(dObj).forEach(([sev, item]) => {
          if (!sev14[sev]) sev14[sev] = { gib: 0, cost: 0 };
          sev14[sev].gib += item.gib;
          sev14[sev].cost += item.cost;
        });
      });

      const total14Gib = Object.values(sev14).reduce((acc, item) => acc + item.gib, 0);
      const activeSevs = sevOrder.filter(s => sev14[s] && sev14[s].gib > 0);

      if (activeSevs.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 16px;">No severity metrics available.</td></tr>';
        return;
      }

      activeSevs.forEach(sev => {
        const item = sev14[sev];
        const pct = total14Gib > 0 ? (item.gib / total14Gib * 100) : 0;
        const costEst = item.cost;
        const volStr = formatGiBCompact(item.gib);
        const costStr = formatDollars(costEst);

        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>
            <div style="display: flex; align-items: center; gap: 8px;">
              <span style="width: 10px; height: 10px; border-radius: 50%; background: ${sevColors[sev] || '#94a3b8'}; flex-shrink: 0;"></span>
              <span style="font-weight: 600; color: var(--text);">${escapeHtml(sev)}</span>
            </div>
          </td>
          <td style="font-weight: 500;">${volStr}</td>
          <td style="color: #34d399; font-weight: 600;">${costStr}</td>
          <td style="font-weight: 600;">${pct.toFixed(1)}%</td>
        `;
        tbody.appendChild(tr);
      });
    }

    const serviceColors = [
      '#3b82f6', '#10b981', '#f59e0b', '#a855f7', '#ec4899',
      '#06b6d4', '#84cc16', '#f97316', '#6366f1', '#14b8a6'
    ];

    function renderDailyServiceChart() {
      const container = document.getElementById('service-daily-svg-chart-container');
      const legend = document.getElementById('service-daily-legend');
      if (!container) return;

      const { dates, data: dailyMetrics } = getDailyServiceMetrics();
      const isCost = currentTrendMetric === 'cost';
      const titleEl = document.querySelector('#subtab-service .section-title');
      if (titleEl && dates.length > 0) titleEl.textContent = `${dates.length}-Day Daily Service Breakdown`;
      const subEl = document.querySelector('#subtab-service .kpi-subtext');
      if (subEl) subEl.textContent = isCost ? 'Daily estimated spend trajectory ($) broken down by top service' : 'Daily log volume (GiB) broken down by top service';

      if (dates.length === 0) {
        container.innerHTML = '<div style="color:var(--text-muted);padding:20px;text-align:center;">No service daily telemetry available.</div>';
        return;
      }

      const srvTotals = {};
      dates.forEach(d => {
        const dObj = dailyMetrics[d] || {};
        Object.entries(dObj).forEach(([s, item]) => {
          const val = isCost ? item.cost : item.gib;
          srvTotals[s] = (srvTotals[s] || 0) + val;
        });
      });

      const topServices = Object.keys(srvTotals).sort((a, b) => srvTotals[b] - srvTotals[a]).slice(0, 6);
      const colorMap = {};
      topServices.forEach((s, i) => {
        colorMap[s] = serviceColors[i % serviceColors.length];
      });
      colorMap['Other'] = '#64748b';

      if (legend) {
        let legHtml = '';
        topServices.forEach(s => {
          legHtml += `
            <div style="display:flex;align-items:center;gap:6px;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
              <span style="width:10px;height:10px;border-radius:50%;background:${colorMap[s]};flex-shrink:0;"></span>
              <span title="${escapeHtml(s)}" style="overflow:hidden;text-overflow:ellipsis;">${escapeHtml(s)}</span>
            </div>
          `;
        });
        legHtml += `
          <div style="display:flex;align-items:center;gap:6px;">
            <span style="width:10px;height:10px;border-radius:50%;background:#64748b;"></span>
            <span>Other</span>
          </div>
        `;
        legend.innerHTML = legHtml;
      }

      const dailyTotals = dates.map(d => {
        const dObj = dailyMetrics[d] || {};
        return Object.values(dObj).reduce((acc, item) => acc + (isCost ? item.cost : item.gib), 0);
      });

      const maxVal = Math.max(...dailyTotals, 0.1);
      const yMax = maxVal * 1.25;

      const width = 800;
      const height = 230;
      const padLeft = 65;
      const padRight = 30;
      const padTop = 30;
      const padBottom = 35;
      const chartW = width - padLeft - padRight;
      const chartH = height - padTop - padBottom;

      const barWidth = Math.min(42, (chartW / dates.length) * 0.65);
      const step = chartW / dates.length;

      let yAxisSvg = '';
      const yTicks = 4;
      for (let i = 0; i <= yTicks; i++) {
        const val = (yMax / yTicks) * i;
        const yPos = padTop + chartH - (i / yTicks) * chartH;
        let label = isCost
          ? ('$' + (val >= 1000 ? (val / 1000).toFixed(val % 1000 === 0 ? 0 : 1) + 'k' : val.toFixed(val < 10 ? 2 : 0)))
          : ((val >= 1000 ? (val / 1000).toFixed(val % 1000 === 0 ? 0 : 1) + 'k' : val.toFixed(val < 10 ? 1 : 0)) + ' GiB');
        yAxisSvg += `
          <line x1="${padLeft}" y1="${yPos}" x2="${width - padRight}" y2="${yPos}" stroke="#334155" stroke-dasharray="3,3" stroke-width="1" />
          <text x="${padLeft - 10}" y="${yPos + 4}" text-anchor="end" fill="#94a3b8" font-size="11" font-family="system-ui, sans-serif">${label}</text>
        `;
      }

      let barsSvg = '';
      dates.forEach((d, idx) => {
        const dObj = dailyMetrics[d] || {};
        const total = dailyTotals[idx];
        const x = padLeft + (idx * step) + (step - barWidth) / 2;

        let curY = padTop + chartH;
        let segsSvg = '';

        topServices.forEach(s => {
          const item = dObj[s];
          const val = item ? (isCost ? item.cost : item.gib) : 0;
          if (item && val > 0) {
            const segH = (val / yMax) * chartH;
            curY -= segH;
            const pct = total > 0 ? ((val / total) * 100).toFixed(1) : '0';
            const formattedVal = isCost ? formatDollars(item.cost) : formatGiBCompact(item.gib);
            const tip = `${d} • ${escapeHtml(s)}: ${formattedVal} (${pct}%)`;
            segsSvg += `
              <rect x="${x}" y="${curY}" width="${barWidth}" height="${segH}" fill="${colorMap[s]}">
                <title>${escapeHtml(tip)}</title>
              </rect>
            `;
          }
        });

        let otherGiB = 0;
        let otherCost = 0;
        Object.entries(dObj).forEach(([s, item]) => {
          if (!topServices.includes(s)) {
            otherGiB += item.gib;
            otherCost += item.cost;
          }
        });

        const otherSegVal = isCost ? otherCost : otherGiB;
        if (otherSegVal > 0) {
          const segH = (otherSegVal / yMax) * chartH;
          curY -= segH;
          const pct = total > 0 ? ((otherSegVal / total) * 100).toFixed(1) : '0';
          const formattedVal = isCost ? formatDollars(otherCost) : formatGiBCompact(otherGiB);
          const tip = `${d} • Other: ${formattedVal} (${pct}%)`;
          segsSvg += `
            <rect x="${x}" y="${curY}" width="${barWidth}" height="${segH}" fill="#64748b">
              <title>${escapeHtml(tip)}</title>
            </rect>
          `;
        }

        const dParts = d.split('-');
        const monthNum = parseInt(dParts[1], 10);
        const monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
        const xLabel = `${monthNames[monthNum - 1]} ${dParts[2]}`;
        const topLabel = isCost ? formatDollars(total) : formatGiBCompact(total);

        barsSvg += `
          <g style="cursor: pointer;">
            <text x="${x + barWidth / 2}" y="${curY - 8}" text-anchor="middle" fill="#f8fafc" font-size="10" font-weight="700" font-family="system-ui, sans-serif">${topLabel}</text>
            ${segsSvg}
            <text x="${x + barWidth / 2}" y="${height - 8}" text-anchor="middle" fill="#94a3b8" font-size="11" font-weight="500" font-family="system-ui, sans-serif">${xLabel}</text>
          </g>
        `;
      });

      container.innerHTML = `
        <svg viewBox="0 0 ${width} ${height}" style="width: 100%; height: auto; display: block; overflow: visible;">
          ${yAxisSvg}
          ${barsSvg}
        </svg>
      `;
    }

    function renderServicePies() {
      const { dates, data: dailyMetrics } = getDailyServiceMetrics();
      if (dates.length === 0) return;

      const isCost = currentTrendMetric === 'cost';
      const windows = [
        { id: 'svc-donut-7d', badgeId: 'svc-pie-badge-7d', days: SHARED_WINDOW_SHORT_DAYS },
        { id: 'svc-donut-14d', badgeId: 'svc-pie-badge-14d', days: SHARED_WINDOW_MAX_DAYS },
      ];

      windows.forEach(w => {
        const sliceDates = dates.slice(-w.days);
        const badge = document.getElementById(w.badgeId);
        if (badge && sliceDates.length > 0) {
          badge.textContent = sliceDates.length === 1 ? sliceDates[0] : `${sliceDates[0]} to ${sliceDates[sliceDates.length - 1]}`;
        }

        const srvSum = {};
        sliceDates.forEach(d => {
          const dObj = dailyMetrics[d] || {};
          Object.entries(dObj).forEach(([s, item]) => {
            if (!srvSum[s]) srvSum[s] = { gib: 0, cost: 0 };
            srvSum[s].gib += item.gib;
            srvSum[s].cost += item.cost;
          });
        });

        const totalGib = Object.values(srvSum).reduce((acc, v) => acc + v.gib, 0);
        const totalVal = isCost ? Object.values(srvSum).reduce((acc, v) => acc + v.cost, 0) : totalGib;
        const sortedSrv = Object.keys(srvSum).sort((a, b) => (isCost ? srvSum[b].cost - srvSum[a].cost : srvSum[b].gib - srvSum[a].gib));
        const topSrv = sortedSrv.slice(0, 5);

        const slices = topSrv.map((s, idx) => {
          const val = isCost ? srvSum[s].cost : srvSum[s].gib;
          return {
            label: s,
            value: val,
            formattedValue: isCost ? formatDollars(val) : formatGiBCompact(val),
            color: serviceColors[idx % serviceColors.length]
          };
        });

        if (sortedSrv.length > 5) {
          const otherVal = sortedSrv.slice(5).reduce((acc, s) => acc + (isCost ? srvSum[s].cost : srvSum[s].gib), 0);
          slices.push({
            label: 'Other',
            value: otherVal,
            formattedValue: isCost ? formatDollars(otherVal) : formatGiBCompact(otherVal),
            color: '#64748b'
          });
        }

        renderSvgDonut(w.id, slices, isCost ? formatDollars(totalVal) : formatGiBCompact(totalVal), `${sliceDates.length}-Day Total`, 5);
      });

      // Populate service-summary-tbody (14-day window breakdown)
      const tbody = document.getElementById('service-summary-tbody');
      if (!tbody) return;
      tbody.innerHTML = '';

      const srv14 = {};
      dates.forEach(d => {
        const dObj = dailyMetrics[d] || {};
        Object.entries(dObj).forEach(([s, item]) => {
          srv14[s] = (srv14[s] || 0) + item.gib;
        });
      });

      const total14Gib = Object.values(srv14).reduce((acc, v) => acc + v, 0);
      const sortedSrv14 = Object.keys(srv14).sort((a, b) => srv14[b] - srv14[a]);

      if (sortedSrv14.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 16px;">No service metrics available.</td></tr>';
        return;
      }

      sortedSrv14.forEach((sName, idx) => {
        const gib = srv14[sName];
        const pct = total14Gib > 0 ? (gib / total14Gib * 100) : 0;
        const costEst = gib * rateForService(sName);
        const volStr = formatGiBCompact(gib);
        const costStr = formatDollars(costEst);
        const sColor = idx < serviceColors.length ? serviceColors[idx] : '#64748b';

        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>
            <div style="display: flex; align-items: center; gap: 8px;">
              <span style="width: 10px; height: 10px; border-radius: 50%; background: ${sColor}; flex-shrink: 0;"></span>
              <span style="font-weight: 600; color: var(--text);">${escapeHtml(sName)}</span>
            </div>
          </td>
          <td style="font-weight: 500;">${volStr}</td>
          <td style="color: #34d399; font-weight: 600;">${costStr}</td>
          <td style="font-weight: 600;">${pct.toFixed(1)}%</td>
        `;
        tbody.appendChild(tr);
      });
    }

    function renderServicesList(services, monthData) {
      const container = document.getElementById('services-list-container');
      if (!container) return;
      container.innerHTML = '';

      
      document.getElementById('services-count-badge').textContent = services.length + ' services';

      services.forEach(([sName, metric], idx) => {
        const gib = serviceGib(metric);
        const cost = metric.cost_usd;

        const row = document.createElement('div');
        row.className = 'service-row' + (sName === activeService || (!activeService && idx === 0) ? ' active' : '');
        row.dataset.service = sName;
        row.onclick = () => selectService(sName, services, monthData);

        const isCost = currentTrendMetric === 'cost';


        const primaryDisplay = isCost ? formatDollars(cost) : gib.toFixed(2) + ' GiB';
        const primaryColor = isCost ? '#34d399' : '#60a5fa';
        const secondaryDisplay = isCost ? gib.toFixed(2) + ' GiB' : formatDollars(cost);

        row.innerHTML = `
          <div style="overflow: hidden; padding-right: 8px; flex: 1; min-width: 0;">
            <div class="service-name">${escapeHtml(sName)}</div>
            <div class="service-sub" style="color: var(--text-muted);">${secondaryDisplay}</div>
          </div>
          <div style="text-align: right; white-space: nowrap; display: flex; align-items: center; gap: 8px;">
            <div style="font-weight: 700; color: ${primaryColor};">${primaryDisplay}</div>
          </div>
        `;
        container.appendChild(row);
      });

      const currentActive = activeService || (services.length > 0 ? services[0][0] : null);
      if (currentActive) {
        selectService(currentActive, services, monthData);
      } else {
        const titleEl = document.getElementById('selected-svc-title');
        if (titleEl) titleEl.textContent = '—';
        const volEl = document.getElementById('selected-svc-vol');
        if (volEl) volEl.textContent = '—';
        const costEl = document.getElementById('selected-svc-cost');
        if (costEl) costEl.textContent = '—';
      }
    }

    function selectService(sName, services, monthData) {
      activeService = sName;
      document.querySelectorAll('.service-row').forEach(r => {
        if (r.dataset.service === sName) r.classList.add('active');
        else r.classList.remove('active');
      });

      const metric = monthData.services_details[sName];
      const gib = serviceGib(metric);
      const cost = metric.cost_usd;

      document.getElementById('selected-svc-title').textContent = sName;
      document.getElementById('selected-svc-vol').textContent = gib.toFixed(2) + ' GiB';
      document.getElementById('selected-svc-cost').textContent = formatDollars(cost);

      const sevData = reportData.severity_summary;
      const sevSource = sevData.severity_source === 'log_analytics' ? 'Log Analytics' : 'Cloud Monitoring';
      const breakdownsTitle = document.getElementById('severity-breakdown-title');
      if (breakdownsTitle) breakdownsTitle.textContent = `${sevData.window_days}-Day Severity Breakdown (${sevSource})`;

      // Severity Breakdown
      const rawSev = sevData.severity_by_service[sName] || {};
      const bar = document.getElementById('severity-distribution-bar');
      bar.innerHTML = '';
      const tbody = document.getElementById('selected-svc-tbody');
      tbody.innerHTML = '';

      let totalRaw = 0;
      Object.values(rawSev).forEach(v => {
        totalRaw += v;
      });

      if (totalRaw > 0) {
        document.getElementById('selected-svc-sample-total').textContent = 
          'Sample Volume: ' + gib.toFixed(2) + ' GiB (' + formatDollars(cost) + ')';

        sevOrder.forEach(sev => {
          const rawVal = rawSev[sev] || 0;
          if (rawVal > 0) {
            const pct = (rawVal / totalRaw) * 100;
            const sevGib = (pct / 100) * gib;
            const sevCost = (pct / 100) * cost;

            const seg = document.createElement('div');
            seg.className = 'sev-segment';
            seg.style.width = pct + '%';
            seg.style.backgroundColor = sevColors[sev] || '#94a3b8';
            seg.title = `${escapeHtml(sev)}: ${pct.toFixed(1)}% (${sevGib.toFixed(2)} GiB, ${formatDollars(sevCost)})`;
            bar.appendChild(seg);

            const tr = document.createElement('tr');
            tr.className = 'severity-row';
            tr.setAttribute('onclick', `toggleSeverityAccordion('${escapeJs(sName)}', '${escapeJs(sev)}')`);
            tr.title = 'Click to expand/collapse sample log messages';

            const samples = (sevData.samples_by_service[sName] || {})[sev] || [];
            const sampleCountBadge = samples.length > 0
              ? `<span class="badge" style="font-size: 10px; padding: 1px 6px; margin-left: 6px; font-weight: normal;">${samples.length} logs</span>`
              : '';

            tr.innerHTML = `
              <td>
                <div style="display: flex; align-items: center;">
                  <span id="arrow-${escapeHtml(sName)}-${escapeHtml(sev)}" class="accordion-arrow">▶</span>
                  <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${sevColors[sev] || '#94a3b8'}; margin-right: 6px;"></span>
                  <span style="font-weight: 600;">${escapeHtml(sev)}</span>
                  ${sampleCountBadge}
                </div>
              </td>
              <td>${sevGib.toFixed(2)} GiB</td>
              <td style="color: #34d399; font-weight: 600;">${formatDollars(sevCost)}</td>
              <td style="font-weight: 600;">${pct.toFixed(1)}%</td>
            `;
            tbody.appendChild(tr);

            const accTr = document.createElement('tr');
            accTr.id = `accordion-${escapeHtml(sName)}-${escapeHtml(sev)}`;
            accTr.className = 'severity-accordion-row';
            accTr.style.display = 'none';

            let samplesHtml = '';
            if (samples.length > 0) {
              // Five patterns could be 90% of this stream or 2% of it. Without
              // the remainder the reader cannot tell which, and would be right
              // to assume the larger.
              const cov = (sevData.sample_coverage && sevData.sample_coverage[sName] && sevData.sample_coverage[sName][sev]) || null;
              const covNote = (cov && cov.shown_pct !== null && cov.shown_pct !== undefined)
                ? `${cov.shown_pct.toFixed(1)}% of this stream's volume · remainder spread across other patterns`
                : 'share of stream not measured';
              samplesHtml = `
                <div class="sample-logs-wrap">
                  <div style="border-bottom: 1px solid rgba(255,255,255,0.08); padding-bottom: 6px;">
                    <span style="font-size: 11px; font-weight: 700; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.05em;">
                      Representative Logs (${samples.length})
                    </span>
                    <span style="font-size: 11px; color: var(--text-muted); margin-left: 8px;">
                      ${escapeHtml(covNote)}
                    </span>
                  </div>
                  ${samples.map((sm, sIdx) => renderSampleCard(sm, sName, sev, sIdx, cov)).join('')}
                </div>
              `;
            } else {
              const sErr = (sevData.sample_errors && sevData.sample_errors[sName] && sevData.sample_errors[sName][sev]) || '';
              samplesHtml = `
                <div class="sample-logs-wrap">
                  <p style="font-size: 12px; color: var(--text-muted); text-align: center; padding: 12px 0;">
                    No representative log entries for ${escapeHtml(sev)} in ${escapeHtml(sName)}${sErr ? ': ' + escapeHtml(sErr) : '.'}
                  </p>
                </div>
              `;
            }

            accTr.innerHTML = `<td colspan="4" class="severity-accordion-cell">${samplesHtml}</td>`;
            tbody.appendChild(accTr);
          }
        });
      } else {
        document.getElementById('selected-svc-sample-total').textContent = 'Sample: Baseline standard telemetry';
        bar.innerHTML = '<div style="width: 100%; height: 100%; background: #475569;" title="Standard telemetry"></div>';
        tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 14px;">No granular SQL severity sample available.</td></tr>';
      }
    }

    function toggleSeverityAccordion(sName, sev) {
      const accId = `accordion-${escapeHtml(sName)}-${escapeHtml(sev)}`;
      const arrowId = `arrow-${escapeHtml(sName)}-${escapeHtml(sev)}`;
      const row = document.getElementById(accId);
      const arrow = document.getElementById(arrowId);
      if (!row) return;

      if (row.style.display === 'none' || !row.style.display) {
        row.style.display = 'table-row';
        if (arrow) {
          arrow.textContent = '▼';
          arrow.style.color = '#3b82f6';
        }
      } else {
        row.style.display = 'none';
        if (arrow) {
          arrow.textContent = '▶';
          arrow.style.color = 'var(--text-muted)';
        }
      }
    }

    // What `signature_source` actually promises about a cluster's members.
    // Clusters are grouped on service + log ID + severity + the first 120
    // characters of ONE payload field, and which field that is decides whether
    // the example on the card is representative or merely arbitrary. That
    // varies from "the opening line is identical" to "these entries have
    // nothing in common but their type", so it is stated on every card rather
    // than left for the reader to infer from the payload.
    const SIGNATURE_MATCH = {
      text_payload: {
        label: 'Same message template',
        tone: '#34d399',
        field: 'text_payload',
        detail: 'These entries share one message template. Variable tokens — timestamps, ids, addresses, numbers — were normalised before grouping, so they differ between entries wherever a <PLACEHOLDER> appears.'
      },
      json_message: {
        label: 'Same message template',
        tone: '#34d399',
        field: 'jsonPayload.message',
        detail: 'These entries share one jsonPayload.message template. Variable tokens were normalised before grouping, so they differ wherever a <PLACEHOLDER> appears. Other payload fields are not compared.'
      },
      json_MESSAGE: {
        label: 'Same message template',
        tone: '#34d399',
        field: 'jsonPayload.MESSAGE',
        detail: 'These entries share one jsonPayload.MESSAGE template (the systemd journal field). Variable tokens were normalised before grouping. Other payload fields are not compared.'
      },
      json_msg: {
        label: 'Same message template',
        tone: '#34d399',
        field: 'jsonPayload.msg',
        detail: 'These entries share one jsonPayload.msg template. Variable tokens were normalised before grouping. Other payload fields are not compared.'
      },
      json_log: {
        label: 'Same message template',
        tone: '#34d399',
        field: 'jsonPayload.log',
        detail: 'These entries share one jsonPayload.log template. Variable tokens were normalised before grouping. Other payload fields are not compared.'
      },
      audit_method: {
        label: 'Same API method',
        tone: '#fbbf24',
        field: 'protoPayload.methodName',
        detail: 'Every entry records the same API method. Callers, target resources, parameters and outcomes vary freely.'
      },
      json_shape: {
        label: 'Same record structure',
        tone: '#fbbf24',
        field: null,
        detail: 'These entries carry no message field, so they are grouped by the set of keys their payload contains. Every member has this same structure; every value inside it may differ. Two records with identical keys but opposite meanings — an allowed and a denied connection, say — sit in this same group.'
      },
      proto_type: {
        label: 'Payload type only — contents vary',
        tone: '#f87171',
        field: 'protoPayload.@type',
        detail: 'Grouped only by payload type. No message text was extractable, so the entries share a schema and nothing else. The example is one arbitrary member.'
      },
      none: {
        label: 'Payload type only — contents vary',
        tone: '#f87171',
        field: null,
        detail: 'No message field could be extracted from these entries, so they are grouped by service, log ID and severity alone. The example is one arbitrary member and may look nothing like the rest.'
      }
    };

    function signatureMatchInfo(src) {
      return SIGNATURE_MATCH[src] || SIGNATURE_MATCH.none;
    }

    function renderSampleCard(sm, sName, sev, sIdx, coverage) {
      const log = sm.sample_log || {};
      const payloadText = log.payload || sm.preview || '';
      const cardId = `log-${escapeHtml(sName)}-${escapeHtml(sev)}-${sIdx}`.replace(/[^a-zA-Z0-9_-]/g, '_');
      const isLong = payloadText.length > 300;
      const initialText = isLong ? payloadText.slice(0, 300) + '...' : payloadText;

      // A census card is two things: the log, and how much of this stream that
      // kind of line accounts for. It deliberately carries no exclusion rule --
      // a rule is an irreversible action on log routing and belongs to the cost
      // optimizer, which measures what the rule itself would drop. Here the
      // volume describes the pattern, which is a different number.
      const gib = sm.total_gib || 0;
      const entries = sm.entry_count || 0;
      // Never substitute a placeholder count: a pattern with no measurement
      // says so rather than implying it carries a single log.
      const measured = (sm.volume_measured !== undefined)
        ? !!sm.volume_measured
        : (gib > 0 || entries > 0);

      const streamBytes = coverage ? (coverage.stream_bytes || 0) : 0;
      const sharePct = (streamBytes > 0 && sm.total_bytes > 0)
        ? (sm.total_bytes / streamBytes) * 100
        : null;

      let metaText;
      if (!measured) {
        metaText = 'Volume not measured for this stream';
      } else {
        const parts = [];
        if (entries > 0) parts.push(`${Number(entries).toLocaleString()} entries`);
        if (gib > 0) parts.push(`${gib.toFixed(2)} GiB`);
        if (sharePct !== null) parts.push(`${sharePct.toFixed(1)}% of ${escapeHtml(sev)} in ${escapeHtml(sName)}`);
        metaText = parts.join(' · ');
      }

      const match = signatureMatchInfo(sm.signature_source);
      // A pattern that covers its whole stream has not identified a pattern at
      // all -- it is the stream, relabelled. Saying so is the difference
      // between "these 135M entries are alike" and "we could not tell these
      // 135M entries apart".
      const isWholeStream = sharePct !== null && sharePct >= 99.5;
      const detailsId = `sig-${cardId}`;

      const isShape = sm.signature_source === 'json_shape';
      const criteriaRows = [
        ['resource.type', sName],
        ['log ID', sm.log_id || '—'],
        ['severity', sev]
      ];
      if (isShape) {
        criteriaRows.push([
          'payload key set',
          sm.preview ? String(sm.preview).slice(0, 120) : '(none)'
        ]);
      } else if (match.field) {
        criteriaRows.push([
          `${match.field} template`,
          sm.preview ? `"${String(sm.preview).slice(0, 120)}"` : '(empty)'
        ]);
      } else {
        criteriaRows.push([
          'message text',
          'not extractable — not used for grouping'
        ]);
      }

      return `
        <div class="sample-card">
          <div style="display: flex; justify-content: space-between; align-items: center; gap: 8px; padding-bottom: 6px;">
            <div style="font-size: 11px; color: var(--text-muted); font-family: var(--font-mono);">
              ${escapeHtml(metaText)}
            </div>
            <span style="font-size: 10px; font-weight: 700; color: ${match.tone}; border: 1px solid ${match.tone}44; background: ${match.tone}1a; border-radius: 10px; padding: 2px 8px; white-space: nowrap;">
              ${escapeHtml(match.label)}
            </span>
          </div>

          ${isWholeStream ? `
            <div style="font-size: 11px; color: #f87171; padding-bottom: 6px;">
              This pattern covers the entire ${escapeHtml(sev)} stream — it describes the stream, not a distinguishing pattern within it.
            </div>
          ` : ''}

          <div style="display: flex; flex-direction: column; gap: 6px;">
            <div class="payload-box" id="box-${cardId}">${escapeHtml(initialText)}</div>
            ${isLong ? `
              <div style="display: flex; justify-content: flex-end;">
                <button onclick="togglePayloadExpand('${cardId}', this)" class="copy-btn" style="padding: 2px 8px; font-size: 10px;">Show full (${payloadText.length.toLocaleString()} chars)</button>
              </div>
            ` : ''}
            <textarea id="full-${cardId}" style="display: none;">${escapeHtml(payloadText)}</textarea>
            <textarea id="trunc-${cardId}" style="display: none;">${escapeHtml(initialText)}</textarea>
          </div>

          <details id="${detailsId}" style="margin-top: 8px;">
            <summary style="font-size: 11px; color: var(--text-muted); cursor: pointer; user-select: none;">
              What makes a log part of this group?
            </summary>
            <div style="margin-top: 6px; font-size: 11px; color: var(--text-muted); line-height: 1.5;">
              <div style="margin-bottom: 6px;">${escapeHtml(match.detail)}</div>
              <table style="width: 100%; border-collapse: collapse; font-family: var(--font-mono); font-size: 10px;">
                <tr><td colspan="2" style="padding: 3px 0; font-weight: 700; color: var(--text-muted);">COMPARED</td></tr>
                ${criteriaRows.map(([k, v]) => `
                  <tr>
                    <td style="padding: 2px 8px 2px 0; vertical-align: top; white-space: nowrap;">${escapeHtml(k)}</td>
                    <td style="padding: 2px 0; word-break: break-all;">${escapeHtml(String(v))}</td>
                  </tr>
                `).join('')}
                <tr><td colspan="2" style="padding: 8px 0 3px 0; font-weight: 700; color: var(--text-muted);">NOT COMPARED</td></tr>
                <tr><td colspan="2" style="padding: 2px 0;">resource labels — instance, subnetwork, cluster and zone all vary within this group</td></tr>
                ${isShape
                  ? '<tr><td colspan="2" style="padding: 2px 0;">every value inside the payload — only the key names were compared</td></tr>'
                  : '<tr><td colspan="2" style="padding: 2px 0;">any token shown as &lt;TS&gt;, &lt;IP&gt;, &lt;UUID&gt;, &lt;HEX&gt;, &lt;PATH&gt; or &lt;N&gt; — these vary between members by design</td></tr>'}
                <tr><td colspan="2" style="padding: 2px 0;">anything past character 200</td></tr>
                <tr><td colspan="2" style="padding: 2px 0;">all other payload fields, labels, timestamps and insertId</td></tr>
              </table>
              <div style="margin-top: 6px; font-style: italic;">
                The log shown above is one member chosen arbitrarily, not the most common or most recent.
              </div>
            </div>
          </details>
        </div>
      `;
    }


    function togglePayloadExpand(cardId, btn) {
      const box = document.getElementById(`box-${cardId}`);
      const full = document.getElementById(`full-${cardId}`);
      const trunc = document.getElementById(`trunc-${cardId}`);
      if (!box || !full || !trunc) return;

      if (box.classList.contains('expanded')) {
        box.classList.remove('expanded');
        box.textContent = trunc.value;
        btn.textContent = `Show full (${full.value.length.toLocaleString()} chars)`;
      } else {
        box.classList.add('expanded');
        box.textContent = full.value;
        btn.textContent = 'Show less';
      }
    }

    // ---- Extraneous Log Spend (measured waste floor) ----

    // Inline show/hide for the detail panel.
    function toggleExtraneousDetails(btn) {
      const el = document.getElementById('extraneous-details');
      if (!el) return;
      if (el.style.display === 'none' || !el.style.display) {
        el.style.display = 'flex';
        btn.textContent = 'Hide details';
      } else {
        el.style.display = 'none';
        btn.textContent = 'See details';
      }
    }

    // `null` means "not measured" and must not render as 0.
    function measuredNumber(v) {
      return (v === null || v === undefined) ? NaN : Number(v);
    }

    // One row per action, from the same objects the Cost Optimizer renders;
    // the filter and how to apply it live on the action's card there.
    function extraneousRows(actions) {
      return actions.map(a => {
        const gib = measuredNumber(a.monthly_gib);
        const usd = measuredNumber(a.monthly_usd);
        const pct = measuredNumber(a.pct_of_billable);
        const details = [];
        if (a.flag) {
          details.push(`<div style="color: var(--warning); font-size: 11px;">⚠ ${escapeHtml(a.flag)}</div>`);
        }
        if (a.evidence) {
          details.push(`<p class="kpi-subtext">${escapeHtml(a.evidence)}</p>`);
        }
        return `
          <tr>
            <td style="font-weight: 600;">${escapeHtml(a.title)}</td>
            <td>${isFinite(gib) ? formatGiBCompact(gib) + '/mo' : '—'}</td>
            <td style="color: #34d399; font-weight: 600;">${isFinite(usd) ? formatDollars(usd) + '/mo' : '—'}</td>
            <td>${isFinite(pct) ? pct.toFixed(2) + '%' : '—'}</td>
            <td style="color: var(--text-muted);">${escapeHtml(a.assurance.label)}</td>
          </tr>
          ${details.length > 0 ? `
            <tr>
              <td colspan="5" style="padding-top: 0;">
                <div style="display: flex; flex-direction: column; gap: 8px; padding-bottom: 6px;">${details.join('')}</div>
              </td>
            </tr>` : ''}`;
      }).join('');
    }

    function buildExtraneousPanel(ext, counted, uncounted, withheld) {
      const basis = ext.basis || {};
      const head = `
        <thead>
          <tr>
            <th>Action</th><th>Volume</th><th>Savings</th><th>% of billable</th><th>Assurance</th>
          </tr>
        </thead>`;

      let html = `
        <div class="chart-title-bar">
          <h2 class="section-title">Extraneous Log Spend — counted actions</h2>
        </div>`;

      if (counted.length > 0) {
        html += `<div class="table-scroll"><table class="data-table">${head}<tbody>${extraneousRows(counted)}</tbody></table></div>`;
        html += `<p class="kpi-subtext">Filters and how to apply each one are in the Cost Optimizer.</p>`;
      } else {
        html += `<p class="kpi-subtext">No individually measured actions were counted in this window.</p>`;
      }

      if (uncounted.length > 0 || withheld.length > 0) {
        const morePct = measuredNumber(ext.uncounted_total_pct);
        const heading = isFinite(morePct) && morePct > 0
          ? `Additional — requires owner review (${Number(morePct.toFixed(2))}% more, not counted)`
          : 'Additional — requires owner review (not counted)';
        html += `
          <div style="border-top: 1px dashed rgba(255,255,255,0.12); padding-top: 14px;">
            <h3 class="section-title" style="font-size: 14px; margin-bottom: 10px;">${escapeHtml(heading)}</h3>
            ${uncounted.length > 0 ? `<div class="table-scroll"><table class="data-table">${head}<tbody>${extraneousRows(uncounted)}</tbody></table></div>` : ''}
            ${withheld.map(w => `<p class="kpi-subtext">• <strong>${escapeHtml(w.title)}:</strong> ${escapeHtml(w.reason)}</p>`).join('')}
          </div>`;
      }

      const basisBits = [];
      if (basis.source) basisBits.push(escapeHtml(basis.source));
      if (basis.window_days) basisBits.push(`${escapeHtml(basis.window_days)}-day window`);
      if (basis.byte_count_to_billed_calibration !== undefined && basis.byte_count_to_billed_calibration !== null) {
        basisBits.push(`stream volumes calibrated to billed bytes (×${escapeHtml(basis.byte_count_to_billed_calibration)})`);
      }
      if (basisBits.length > 0) {
        html += `<p class="kpi-subtext" style="border-top: 1px solid var(--border); padding-top: 10px;">Basis: ${basisBits.join(' · ')}</p>`;
      }
      return html;
    }

    function renderExtraneousSpend() {
      const valEl = document.getElementById('kpi-waste-val');
      const subEl = document.getElementById('kpi-waste-subtext');
      if (!valEl || !subEl) return;
      const badgeEl = document.getElementById('kpi-waste-badge');
      const btnEl = document.getElementById('kpi-waste-details-btn');
      const panelEl = document.getElementById('extraneous-details');

      const ext = reportData.extraneous_spend;
      // Both are absent when the floor could not be measured.
      const headline = ext.headline;
      const basis = ext.basis || {};

      // Reset the details affordance; it is only offered when there is something to list.
      if (btnEl) { btnEl.style.display = 'none'; btnEl.textContent = 'See details'; }
      if (panelEl) { panelEl.style.display = 'none'; panelEl.innerHTML = ''; }

      // No measured data: show an em-dash and the upstream reason. Never fabricate a number.
      const pct = headline ? Number(headline.pct_of_billable_spend) : NaN;
      if (ext.status !== 'ok' || !isFinite(pct)) {
        valEl.textContent = '—';
        subEl.textContent = ext.reason;
        if (badgeEl) badgeEl.textContent = 'No data';
        return;
      }

      const needsReview = headline.exceeds_sanity_ceiling === true;
      if (badgeEl) badgeEl.textContent = basis.window_days ? `Floor · ${basis.window_days}d` : 'Floor';

      // The headline is a floor (only measured actions are counted), hence the ≥.
      valEl.textContent = `≥ ${Number(pct.toFixed(2))}%` + (needsReview ? ' ⚠' : '');

      const reduction = reportData.reduction_actions;
      const levers = reduction.actions.filter(a => a.source === 'measured_lever');
      const counted = levers.filter(a => a.counted);
      const uncounted = levers.filter(a => !a.counted);
      const withheld = reduction.withheld;
      let subtext = `~${formatDollars(headline.monthly_savings_usd)}/mo of ${formatDollars(basis.billable_monthly_cost_usd)}/mo billable · ${counted.length} actions counted`;
      if (needsReview) subtext += ' · ⚠ exceeds sanity ceiling, needs manual review';
      subEl.textContent = subtext;

      if (panelEl && (levers.length > 0 || withheld.length > 0)) {
        panelEl.innerHTML = buildExtraneousPanel(ext, counted, uncounted, withheld);
        if (btnEl) btnEl.style.display = 'inline-block';
      }
    }

    function copyToClipboard(text, btn) {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(() => {
          const original = btn.textContent;
          btn.textContent = 'Copied!';
          setTimeout(() => { btn.textContent = original; }, 1500);
        }).catch(() => {
          fallbackCopyText(text, btn);
        });
      } else {
        fallbackCopyText(text, btn);
      }
    }

    function fallbackCopyText(text, btn) {
      const ta = document.createElement('textarea');
      ta.value = text;
      ta.style.position = 'fixed';
      ta.style.opacity = '0';
      document.body.appendChild(ta);
      ta.select();
      try {
        if (!document.execCommand('copy')) throw new Error('copy refused');
        const original = btn.textContent;
        btn.textContent = 'Copied!';
        setTimeout(() => { btn.textContent = original; }, 1500);
      } catch (err) {
        btn.textContent = 'Failed';
      }
      document.body.removeChild(ta);
    }

    // ---------------------------------------------------------------------
    // Prove It: renders `provenance.claims[<id>]` (provenance.py) from the
    // embedded JSON. It never talks to an agent, since an HTML file cannot know
    // which host embeds it; the footer names verify_claim.py instead.
    // ---------------------------------------------------------------------
    function provenanceClaim(claimId) {
      const claims = reportData.provenance.claims;
      return claims[claimId] || null;
    }

    function revealProveButtons() {
      document.querySelectorAll('.prove-btn[data-claim]').forEach(btn => {
        btn.style.display = provenanceClaim(btn.dataset.claim) ? '' : 'none';
      });
    }

    function renderProveSource(src, idx) {
      const link = (src.console && src.console.url)
        ? `<a class="prove-link" href="${escapeHtml(src.console.url)}" target="_blank" rel="noopener">${escapeHtml(src.console.label || 'Open in Console')} ↗</a>`
        : '';
      const code = src.query
        ? `<div>
             <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
               <span class="prove-kind">${escapeHtml(src.language || 'query')}</span>
               <button class="prove-link" style="background:none; cursor:pointer;" onclick="copyProveQuery(${idx}, this)">Copy</button>
             </div>
             <pre class="prove-code">${escapeHtml(src.query)}</pre>
           </div>`
        : '';
      const steps = (src.steps && src.steps.length)
        ? `<ol class="prove-steps">${src.steps.map(s => `<li>${escapeHtml(s)}</li>`).join('')}</ol>`
        : '';
      return `
        <div class="prove-source">
          <div class="prove-source-head">
            <div>
              <div class="prove-kind">${escapeHtml(src.kind || '')}</div>
              <div class="prove-source-name">${escapeHtml(src.name || 'Source')}</div>
              ${src.role ? `<div class="prove-source-role">${escapeHtml(src.role)}</div>` : ''}
            </div>
            ${link}
          </div>
          ${code}
          ${steps}
        </div>`;
    }

    let activeProveClaim = null;

    function copyProveQuery(idx, btn) {
      const src = ((activeProveClaim || {}).sources || [])[idx];
      if (src && src.query) copyToClipboard(src.query, btn);
    }

    function proveIt(claimId) {
      const claim = provenanceClaim(claimId);
      if (!claim) return;
      activeProveClaim = claim;
      const formula = claim.formula.join('\n');
      const sources = claim.sources.map(renderProveSource).join('');
      const diffs = claim.differences.length
        ? `<div><div class="prove-section-title">Why the console may differ slightly</div>
             <ul class="prove-diffs">${claim.differences.map(d => `<li>${escapeHtml(d)}</li>`).join('')}</ul></div>`
        : '';
      const related = claim.see_also.filter(provenanceClaim);
      const seeAlso = related.length
        ? `<div><div class="prove-section-title">Built from these claims, each with its own proof</div>
             <ul class="prove-diffs">${related.map(id => `<li><a class="prove-link" href="#" data-claim="${escapeHtml(id)}" onclick="proveIt(this.dataset.claim); return false;">${escapeHtml(provenanceClaim(id).title)}</a></li>`).join('')}</ul></div>`
        : '';
      const ctx = reportData.report_context || {};
      const verifyCmd = `${ctx.python || 'python3'} ${ctx.verify_script || 'scripts/verify_claim.py'} --summary ${ctx.summary_path || 'logging_usage_summary.json'} --claim "${claim.id}"`;
      const foot = `To re-check every input above against the live sources: <code>${escapeHtml(verifyCmd)}</code><br>Or ask your agent: <code>prove ${escapeHtml(claim.id)}</code>`;

      const drawer = document.getElementById('prove-drawer');
      drawer.innerHTML = `
        <div class="prove-head">
          <div>
            <div class="prove-kicker">✓ Prove It</div>
            <div class="prove-title">${escapeHtml(claim.title || '')}</div>
            <div class="prove-value">${escapeHtml(claim.value || '')}</div>
          </div>
          <button class="prove-close" onclick="closeProveIt()" aria-label="Close">✕</button>
        </div>
        ${claim.summary ? `<div style="font-size:13px; line-height:1.55; color:var(--text);">${escapeHtml(claim.summary)}</div>` : ''}
        ${formula ? `<div><div class="prove-section-title">How it's calculated</div><div class="prove-formula">${escapeHtml(formula)}</div></div>` : ''}
        ${sources ? `<div style="display:flex; flex-direction:column; gap:10px;"><div class="prove-section-title">Check each input yourself</div>${sources}</div>` : ''}
        ${seeAlso}
        ${diffs}
        <div class="prove-foot">${foot}</div>`;
      document.getElementById('prove-overlay').classList.add('open');
      drawer.classList.add('open');
      drawer.scrollTop = 0;
    }

    function closeProveIt() {
      document.getElementById('prove-overlay').classList.remove('open');
      document.getElementById('prove-drawer').classList.remove('open');
      activeProveClaim = null;
    }

    document.addEventListener('keydown', e => {
      if (e.key === 'Escape') closeProveIt();
    });

    function escapeHtml(str) {
      if (str === undefined || str === null) return '';
      return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
    }

    function escapeJs(str) {
      if (str === undefined || str === null) return '';
      return String(str)
        .replace(/\\/g, '\\\\')
        .replace(/'/g, "\\'")
        .replace(/"/g, '\\"')
        .replace(/\n/g, '\\n')
        .replace(/\r/g, '\\r');
    }

    function filterServices(q) {
      const term = q.toLowerCase().trim();
      document.querySelectorAll('.service-row').forEach(row => {
        const name = row.dataset.service.toLowerCase();
        row.style.display = name.includes(term) ? 'flex' : 'none';
      });
    }

    // One card per action, full width, ranked by saving. Each card answers, in
    // order: what it is and what it saves, why (evidence and what to weigh),
    // and how to apply it. Nothing here is selectable or summed: overlapping
    // actions can cover the same stream, so a running total would promise the
    // same bytes twice.
    function renderOptimizationActions() {
      const container = document.getElementById('optimization-actions');
      if (!container) return;

      const reductionData = reportData.reduction_actions;
      const actions = reductionData.actions;
      const withheld = reductionData.withheld;

      if (actions.length === 0 && withheld.length === 0) {
        container.innerHTML = '<div class="card"><p class="kpi-subtext">No actions could be measured for this window.</p></div>';
        return;
      }

      // Bars are scaled to the largest action so the list reads as a ranking.
      const maxGib = Math.max(0, ...actions.map(a => a.monthly_gib || 0));

      const cards = actions.map(item => {
        const id = escapeHtml(escapeJs(item.id));
        const a = item.assurance;
        const level = a.level || 'judgement';
        const hasFigure = item.monthly_usd !== null && item.monthly_usd !== undefined;
        const hasVolume = item.monthly_gib !== null && item.monthly_gib !== undefined;

        // Dollars lead and volume sits under them: one fact, measured two ways.
        const saving = hasFigure
          ? `<div class="action-saving-usd">${formatDollars(item.monthly_usd)}/mo</div>`
            + (hasVolume ? `<div class="action-saving-gib">${formatGiBCompact(item.monthly_gib)}/mo</div>` : '')
          : '<div class="action-saving-usd action-saving-none">—</div>';
        const barPct = (maxGib > 0 && hasVolume) ? Math.max(2, item.monthly_gib / maxGib * 100) : 0;

        // The caveat says what the stream is FOR. It is the line that can stop
        // someone deleting their firewall logs, so it is set apart.
        const why = [item.evidence, a.measurement, a.judgement]
          .filter(Boolean)
          .map(s => `<div class="action-text">${escapeHtml(s)}</div>`)
          .join('')
          + (a.caveat ? `<div class="action-caveat">${escapeHtml(a.caveat)}</div>` : '');

        let how = '';
        if (item.filter) {
          how += `
            <div class="action-text action-muted">Add as an exclusion filter on the <code>_Default</code> sink (Logging → Log Router → <code>_Default</code> → Edit sink).</div>
            <code class="action-filter">${escapeHtml(item.filter)}</code>
            <div><button class="copy-btn action-copy" onclick="copyActionFilter('${id}', this)">Copy filter</button></div>`;
        }
        if (item.manual_step) {
          how += `<div class="action-text">${escapeHtml(item.manual_step)}</div>`;
        }
        if (item.scope_note) {
          how += `<div class="action-text action-muted">${escapeHtml(item.scope_note)}</div>`;
        }
        // Without this the saving looks arbitrarily smaller than the volume the
        // evidence quotes, with nothing to explain the gap.
        const refused = item.refused_claims.filter(r => r.monthly_gib > 0);
        if (refused.length > 0) {
          how += `<div class="action-text action-muted"><strong>Not covered by this filter:</strong>`
            + refused.map(r => `<div>• ${escapeHtml(r.log_id)} (${formatGiBCompact(r.monthly_gib)}/mo) — ${escapeHtml(r.reason)}</div>`).join('')
            + '</div>';
        }

        const sample = item.sample_log && (item.sample_log.payload || item.sample_log.preview);
        const sampleName = (item.sample_log && item.sample_log.log_name) ? ` (${escapeHtml(item.sample_log.log_name)})` : '';
        const sampleHtml = sample
          ? `<details class="action-details"><summary>Example log${sampleName}</summary><div class="payload-box">${escapeHtml(sample)}</div></details>`
          : '';

        return `
          <div class="action-card level-${escapeHtml(level)}">
            <div class="action-head">
              <div style="min-width: 0;">
                <div class="action-label">${escapeHtml(a.label || 'Your call')}</div>
                <div class="action-title">${escapeHtml(item.title)}</div>
              </div>
              <div class="action-saving">${saving}${hasFigure ? `
                <div style="margin-top: 6px;"><button class="prove-btn" style="display:none;" data-claim="action::${escapeHtml(item.id)}"
                        onclick="proveIt(this.dataset.claim)"
                        title="How this saving is calculated, and how to check it yourself"><span class="check">✓</span> Prove It</button></div>` : ''}</div>
            </div>
            ${barPct > 0 ? `<div class="action-bar"><span style="width: ${barPct.toFixed(1)}%;"></span></div>` : ''}
            <div class="action-body${how ? '' : ' action-body-single'}">
              <div>
                <div class="action-section-title">Why</div>
                ${why}
              </div>
              ${how ? `<div><div class="action-section-title">How to apply</div>${how}</div>` : ''}
            </div>
            ${sampleHtml ? `<div class="action-foot">${sampleHtml}</div>` : ''}
          </div>`;
      });

      if (withheld.length > 0) {
        cards.push(`
          <div class="card action-withheld">
            <div class="action-section-title">Not offered as an action</div>
            ${withheld.map(w => `<div class="action-text action-muted">• <strong>${escapeHtml(w.title)}:</strong> ${escapeHtml(w.reason)}</div>`).join('')}
          </div>`);
      }

      container.innerHTML = cards.join('');
    }

    // Looked up by id rather than passed through the onclick attribute: filters
    // contain quotes and newlines, which break attribute escaping.
    function copyActionFilter(actionId, btn) {
      const actions = reportData.reduction_actions.actions;
      const item = actions.find(x => x.id === actionId);
      if (item && item.filter) copyToClipboard(item.filter, btn);
    }
  </script>
</body>
</html>
references/
attribution.md 1.9 KB
# Usage Attribution

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

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

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-logging-finops)" \
    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-logging-finops)` 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:

    ```text
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:cloud-logging-finops)
    ```

-   **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.
executive_summary_authoring.md 3.8 KB
# Authoring `insights/executive_summary.html`

Optional. `build_report.py` synthesizes a data-driven Executive Summary when
this file is absent or empty. Write it only to add analysis the default lacks
(for example, what the Step 2.5 interview asked for).

Keep text brief and anchored on specific numbers from
`logging_usage_summary.json`. Follow SKILL.md Step 3: say what the cost figures
rest on, and state recoverable spend as a floor (`at least X%`), never "up to".
Quote unit prices and the free tier from `pricing.skus`, never from memory.

## Styling

The template uses its own CSS classes and variables (not Tailwind):

*   **Card Container**: `<div class="card" style="gap: 16px;">`
*   **Card Header**: `<div style="display: flex; justify-content: space-between;
    align-items: center; border-bottom: 1px solid var(--border); padding-bottom:
    12px;"><h2 class="section-title">Title</h2><span class="badge
    badge-primary">Label</span></div>`
*   **Structured Item Rows**: `<div style="display: flex; gap: 14px;
    align-items: flex-start; background: var(--bg); border: 1px solid
    var(--border); border-radius: 8px; padding: 14px;">`
*   **Badges**: `<span class="badge badge-warning">SPEND TREND</span>`, `<span
    class="badge badge-primary">PRIMARY DRIVERS</span>`, `<span class="badge
    badge-success">OPPORTUNITY</span>`
*   **Inline Code / Resource Names**: `<code
    class="code-pill">k8s_cluster</code>`
*   **Typography & Colors**:
    *   Primary text: `color: var(--text)`
    *   Muted notes: `<div style="font-size: 12px; color: var(--text-muted);
        margin-top: 4px;">`
    *   Accents: `#60a5fa` (blue), `#34d399` (emerald), `#fbbf24` (amber),
        `#ef4444` (red)

## Example

```html
<div class="card" style="gap: 16px;">
  <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border); padding-bottom: 12px;">
    <h2 class="section-title">Executive Summary & Key Findings</h2>
    <span class="badge badge-primary">FinOps Assessment</span>
  </div>

  <div style="display: flex; flex-direction: column; gap: 12px;">
    <div style="display: flex; gap: 14px; align-items: flex-start; background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 14px;">
      <span class="badge badge-warning" style="flex-shrink: 0; margin-top: 1px;">SPEND TREND</span>
      <div style="font-size: 13px; line-height: 1.5; color: var(--text);">
        Project spend expanded from <strong style="color: var(--text);">$X.XX (Y GB)</strong> to peak at <strong style="color: #fbbf24;">$A.AA (B GB)</strong>, stabilizing at <strong>~$C/mo</strong>.
        <div style="font-size: 12px; color: var(--text-muted); margin-top: 4px;">Note: Estimated at list prices (Log Storage $P/GiB after F GiB/month free; Vended Logs Storage $V/GiB).</div>
      </div>
    </div>

    <div style="display: flex; gap: 14px; align-items: flex-start; background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 14px;">
      <span class="badge badge-primary" style="flex-shrink: 0; margin-top: 1px;">PRIMARY DRIVERS</span>
      <div style="font-size: 13px; line-height: 1.5; color: var(--text);">
        <code class="code-pill">k8s_cluster</code> accounts for <strong style="color: #60a5fa;">50.3% ($X MTD)</strong> of ingestion.
      </div>
    </div>

    <div style="display: flex; gap: 14px; align-items: flex-start; background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 14px;">
      <span class="badge badge-success" style="flex-shrink: 0; margin-top: 1px;">OPPORTUNITY</span>
      <div style="font-size: 13px; line-height: 1.5; color: var(--text);">
        At least <strong style="color: #34d399;">X% (~$Y/mo)</strong> of spend is recoverable without losing signal; see the Cost Optimizer tab for each action and its filter.
      </div>
    </div>
  </div>
</div>
```
scripts/
actions.py 12.4 KB
"""One typed representation of a cost reduction action, and the ranked list.

`waste` builds lever actions (measured against billing metrics) and
`merge_actions` adds the sampled exclusion rules from `exclusion_rules`. Every
action carries what the report and Prove It need (`gib_by_sku`,
`stream_fraction`, `counted`, `flag`), so no consumer joins actions back to
anything by id or filter.
"""

import dataclasses
import hashlib
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple

from constants import BYTES_PER_GIB
from constants import HOST_AUDIT_CAVEAT
from constants import HOST_AUDIT_PAYLOAD_MARKERS
from constants import SECURITY_TELEMETRY_LOG_IDS
from exclusion_rules import decode_log_id
from exclusion_rules import log_name_predicate
from exclusion_rules import rule_eligibility
from exclusion_rules import severity_predicate
import messages
from pricing import PriceBook

SOURCE_LEVER = "measured_lever"
SOURCE_RULE = "exclusion_rule"
ALL_SEVERITIES = "*"

# Cloud Logging rejects exclusion filters longer than this.
MAX_FILTER_CHARS = 20000
# Whole-stream filters stop below the first severity `rule_eligibility` refuses
# (`NEVER_EXCLUDE_SEVERITIES`), so they never drop a paging signal.
_WHOLE_STREAM_GUARD = "severity < CRITICAL"


@dataclasses.dataclass(frozen=True)
class Claim:
  """A stream (at one severity, or every severity) an action's volume covers."""

  log_id: str
  severity: str
  monthly_gib: float

  def to_dict(self) -> Dict[str, Any]:
    return {
        "log_id": self.log_id,
        "severity": self.severity,
        "monthly_gib": round(self.monthly_gib, 3),
    }

  def covers(self, other: "Claim") -> bool:
    """True when every byte of `other` falls in this stream and severity."""
    return decode_log_id(self.log_id) == decode_log_id(other.log_id) and (
        self.severity in (ALL_SEVERITIES, other.severity)
    )


@dataclasses.dataclass
class Action:
  """One saving the reader can act on, or a reason it is withheld."""

  id: str
  title: str
  source: str
  evidence: str
  # In the recoverable-spend floor; the headline is the sum of these.
  counted: bool = False
  # None when the volume behind the action is not measurable.
  monthly_gib: Optional[float] = None
  monthly_usd: Optional[float] = None
  pct_of_billable: Optional[float] = None
  gib_by_sku: Dict[str, float] = dataclasses.field(default_factory=dict)
  # Share of the claimed streams' bytes the action removes, for re-measuring.
  stream_fraction: float = 1.0
  claims: List[Claim] = dataclasses.field(default_factory=list)
  refused_claims: List[Dict[str, Any]] = dataclasses.field(default_factory=list)
  filter: str = ""
  manual_step: str = ""
  scope_note: str = ""
  sample_log: Optional[Dict[str, Any]] = None
  # Reader-facing sentence; what the reader must decide before acting.
  flag: str = ""
  confidence: str = "high"
  # Rules only: share of the sampled volume the filter matches.
  projected_savings_pct: Optional[float] = None
  rule_scope: str = ""
  # Set when the action is reported but never offered.
  withheld: str = ""

  def covers(self, claim: Claim) -> bool:
    return any(c.covers(claim) for c in self.claims)

  def assurance(self) -> Dict[str, str]:
    """The plain-language verdict on how far to trust this action."""
    sample = _sample_text(self.sample_log)
    if self.source == SOURCE_RULE:
      return _verdict(
          "estimated",
          measurement=[messages.HOW_MEASURED_RULE],
          judgement=[
              messages.SCOPE_JUDGEMENT.get(
                  self.rule_scope, messages.SCOPE_JUDGEMENT["signature"]
              )
              + (messages.READ_SAMPLE if sample else "")
          ],
          caveat=_security_caveat(
              (c.log_id for c in self.claims), sample, drops_stream=True
          ),
      )
    quantified = self.monthly_gib is not None
    if not quantified:
      level = "unmeasured"
    elif not self.counted:
      level = "judgement"
    elif self.flag or self.confidence != "high":
      level = "confirm"
    else:
      level = "ready"
    return _verdict(
        level,
        measurement=[messages.HOW_MEASURED_LEVER if quantified else ""],
        judgement=[
            self.flag,
            messages.CONFIDENCE_MEANINGS.get(self.confidence, ""),
        ],
        # Includes refused claims: they still signal security telemetry.
        caveat=_security_caveat(
            [c.log_id for c in self.claims]
            + [r["log_id"] for r in self.refused_claims],
            sample,
            drops_stream=bool(self.filter),
        ),
    )

  def to_dict(self) -> Dict[str, Any]:
    return {
        "id": self.id,
        "title": self.title,
        "source": self.source,
        "counted": self.counted,
        "flag": self.flag,
        "monthly_gib": self.monthly_gib,
        "monthly_usd": self.monthly_usd,
        "pct_of_billable": self.pct_of_billable,
        "gib_by_sku": self.gib_by_sku,
        "stream_fraction": self.stream_fraction,
        "projected_savings_pct": self.projected_savings_pct,
        "claims": [c.to_dict() for c in self.claims],
        "refused_claims": self.refused_claims,
        "evidence": self.evidence,
        "filter": self.filter,
        "manual_step": self.manual_step,
        "scope_note": self.scope_note,
        "sample_log": self.sample_log,
        "assurance": self.assurance(),
    }


# --- Assurance ---------------------------------------------------------------


def _sample_text(sample: Optional[Mapping[str, Any]]) -> str:
  """The example log text the report would render, or ""."""
  sample = sample or {}
  return str(sample.get("payload") or sample.get("preview") or "")


def _join_prose(items: Sequence[str]) -> str:
  if len(items) <= 1:
    return "".join(items)
  return f"{', '.join(items[:-1])} and {items[-1]}"


def _security_caveat(
    log_ids: Iterable[str], sample_text: str, drops_stream: bool
) -> str:
  """Returns a caveat if the streams are security telemetry, else ""."""
  # GCP security streams are matched by log ID; host audit streams by sample
  # text. `drops_stream` is False when the action only reduces a stream (e.g.
  # sampling).
  described = sorted({
      SECURITY_TELEMETRY_LOG_IDS[decoded]
      for decoded in map(decode_log_id, log_ids)
      if decoded in SECURITY_TELEMETRY_LOG_IDS
  })
  if not described and any(
      m in sample_text for m in HOST_AUDIT_PAYLOAD_MARKERS
  ):
    described = [HOST_AUDIT_CAVEAT]
  if not described:
    return ""
  template = (
      messages.SECURITY_CAVEAT_DROPS
      if drops_stream
      else messages.SECURITY_CAVEAT_REDUCES
  )
  return template.format(what=_join_prose(described))


def _verdict(
    level: str,
    measurement: Sequence[str],
    judgement: Sequence[str],
    caveat: str,
) -> Dict[str, str]:
  # "Ready to apply" is never the word for deleting security telemetry.
  if caveat and level == "ready":
    level = "confirm"
  return {
      "level": level,
      "label": messages.LEVEL_LABELS[level],
      "measurement": " ".join(s for s in measurement if s),
      "judgement": " ".join(s for s in judgement if s),
      "caveat": caveat,
  }


# --- Filters -----------------------------------------------------------------


def _render_filter(claims: Sequence[Claim], project_id: str) -> str:
  """Renders claims as one filter, one OR-group per severity."""
  by_severity: Dict[str, List[str]] = {}
  for claim in claims:
    by_severity.setdefault(claim.severity, []).append(
        log_name_predicate(project_id, claim.log_id)
    )

  groups = []
  for severity, log_preds in by_severity.items():
    if severity == ALL_SEVERITIES:
      severity_pred = _WHOLE_STREAM_GUARD
    else:
      severity_pred = severity_predicate(severity)
    logs = (
        log_preds[0] if len(log_preds) == 1 else f"({' OR '.join(log_preds)})"
    )
    groups.append(f"{severity_pred} AND {logs}")
  if len(groups) == 1:
    return groups[0]
  return " OR ".join(f"({g})" for g in groups)


def _refusal_reason(claim: Claim) -> Optional[str]:
  if not claim.log_id or claim.log_id == "unknown":
    return messages.REFUSED_NO_LOG_ID
  ok, reason = rule_eligibility(
      severity="" if claim.severity == ALL_SEVERITIES else claim.severity,
      log_id=claim.log_id,
      rule_bytes=int(claim.monthly_gib * BYTES_PER_GIB),
  )
  return None if ok else reason


def filter_from_claims(
    claims: Sequence[Claim], project_id: str
) -> Tuple[str, List[Claim], List[Dict[str, Any]]]:
  """Builds a copy-paste filter covering the claims it can safely exclude.

  Args:
    claims: candidate claims to exclude.
    project_id: project the filter targets.

  Returns:
    `(filter, kept, refused)`; `refused` entries carry a reason and the
    filter is "" when nothing is kept.
  """
  kept: List[Claim] = []
  refused: List[Dict[str, Any]] = []
  for claim in sorted(claims, key=lambda c: c.monthly_gib, reverse=True):
    reason = _refusal_reason(claim)
    if reason is None and (
        len(_render_filter([*kept, claim], project_id)) > MAX_FILTER_CHARS
    ):
      reason = messages.REFUSED_FILTER_TOO_LONG.format(limit=MAX_FILTER_CHARS)
    if reason is not None:
      refused.append({**claim.to_dict(), "reason": reason})
    else:
      kept.append(claim)
  return (_render_filter(kept, project_id) if kept else ""), kept, refused


# --- Exclusion rules ---------------------------------------------------------


def _rule_action(raw: Mapping[str, Any], price_book: PriceBook) -> Action:
  """Converts one `exclusion_rules` candidate into an action."""
  log_id = raw["log_id"]
  severity = raw["severity"]
  gib = raw["projected_savings_gib"]
  scope = raw["rule_scope"]
  # Several rules can share a stream and severity (two signatures, or two
  # resource types), so the filter is part of the identity.
  digest = hashlib.sha1(raw["filter"].encode("utf-8")).hexdigest()[:8]
  return Action(
      id=f"exclusion::{log_id}::{severity}::{digest}",
      title=raw["title"],
      source=SOURCE_RULE,
      evidence=raw["rationale"],
      monthly_gib=gib,
      monthly_usd=raw["projected_monthly_savings_usd"],
      gib_by_sku={price_book.sku_for_log(log_id): gib},
      claims=[Claim(log_id, severity, gib)],
      filter=raw["filter"],
      # A stream-scoped rule's reach is already stated in its judgement.
      scope_note=raw["rule_scope_note"] if scope == "signature" else "",
      sample_log=raw["sample_log"] or None,
      projected_savings_pct=raw["projected_savings_pct"],
      rule_scope=scope,
  )


def merge_actions(
    lever_actions: Sequence[Action],
    exclusion_candidates: Sequence[Mapping[str, Any]],
    price_book: PriceBook,
) -> Dict[str, Any]:
  """Builds the `reduction_actions` contract: ranked actions and withheld.

  A rule whose stream a lever's filter already covers folds into that lever
  (lending it its example log); a rule beside a manual-step lever on the same
  stream stays, marked as an alternative; exact duplicate filters are dropped.

  Args:
    lever_actions: actions from `waste.compute_extraneous_spend`.
    exclusion_candidates: raw candidates from `exclusion_rules`.
    price_book: prices the candidates.

  Returns:
    The `reduction_actions` dict.
  """
  actions: List[Action] = []
  withheld: List[Dict[str, str]] = []
  for action in lever_actions:
    if action.withheld:
      withheld.append({"title": action.title, "reason": action.withheld})
    else:
      actions.append(action)
  levers = list(actions)
  filters = {a.filter for a in levers if a.filter}

  for raw in exclusion_candidates:
    rule = _rule_action(raw, price_book)
    if rule.monthly_gib <= 0:
      withheld.append(
          {"title": rule.title, "reason": messages.WITHHELD_NO_VOLUME}
      )
      continue
    if rule.filter in filters:
      continue
    claim = rule.claims[0]
    covering = next((a for a in levers if a.filter and a.covers(claim)), None)
    if covering is not None:
      covering.sample_log = covering.sample_log or rule.sample_log
      continue
    beside = next(
        (a for a in levers if a.manual_step and a.covers(claim)), None
    )
    if beside is not None:
      rule.scope_note = " ".join(
          filter(
              None,
              [
                  rule.scope_note,
                  messages.ALTERNATIVE_TO.format(title=beside.title),
              ],
          )
      )
    filters.add(rule.filter)
    actions.append(rule)

  # Dollars first: SKU rates differ, so largest volume != largest saving.
  actions.sort(
      key=lambda a: (a.monthly_usd or 0.0, a.monthly_gib or 0.0), reverse=True
  )
  return {"actions": [a.to_dict() for a in actions], "withheld": withheld}
aggregations.py 25.4 KB
"""Cost apportionment and volume/cost aggregations over the collected series."""

import calendar
import collections
import datetime
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple

from constants import BYTES_PER_GIB
from constants import DAYS_PER_MONTH
from constants import DEFAULT_SAMPLE_DAYS
from constants import DEFAULT_TELEMETRY_LOOKBACK_DAYS
from constants import ESTIMATED_SKU_NAME
from pricing import complete_days
from pricing import PriceBook
from pricing import sku_of_resource


def window_start(now: datetime.datetime, days: float) -> str:
  """First date (`YYYY-MM-DD`) of the `days`-day window ending at `now`."""
  return (now - datetime.timedelta(days=days)).strftime("%Y-%m-%d")


def window_sums(
    parsed: Mapping[Any, Sequence[Sequence[Any]]],
    now: datetime.datetime,
    days: float,
) -> Dict[Any, float]:
  """Totals each `[[date, value], ...]` series from `window_start(now, days)`.

  Series are whole UTC days ending before today, so this covers exactly `days`
  days. A series with nothing in the window is omitted rather than reported as
  zero, which would read as a stream that stopped.

  Args:
    parsed: `[[date, value], ...]` series by key.
    now: end of the window.
    days: window length in days.

  Returns:
    The window total per key.
  """
  start = window_start(now, days)
  sums: Dict[Any, float] = {}
  for key, points in parsed.items():
    total = sum(value for day, value in points if day >= start)
    if total:
      sums[key] = total
  return sums


def apportion_cents_exactly(
    weights: Dict[str, int], total_cents: int
) -> Dict[str, float]:
  """Splits integer cents by weight (largest remainder); sum is exact."""
  total_weight = sum(weights.values())
  if total_weight <= 0 or total_cents <= 0:
    return {k: 0.0 for k in weights}

  exact_cents = {
      k: (w * total_cents) / total_weight for k, w in weights.items()
  }
  floor_cents = {k: int(cents) for k, cents in exact_cents.items()}

  remainder_cents = total_cents - sum(floor_cents.values())
  remainders = {k: exact_cents[k] - floor_cents[k] for k in weights}

  for key, _ in sorted(remainders.items(), key=lambda x: x[1], reverse=True)[
      :remainder_cents
  ]:
    floor_cents[key] += 1

  return {k: round(cents / 100.0, 2) for k, cents in floor_cents.items()}


def _apportion_by_sku(
    services_bytes: Dict[str, int],
    total_cents: int,
    ingestion_by_sku: Optional[Dict[str, Dict[str, float]]],
) -> Tuple[Dict[str, float], bool]:
  """Apportions a month's ingestion cost to services, one SKU pool at a time."""
  # Falls back to one pool when fewer than two SKUs carry cost or a priced SKU
  # has no mapped service. Returns (dollars per service summing exactly to
  # `total_cents / 100`, whether the split was per SKU).
  pools: Dict[str, Dict[str, int]] = collections.defaultdict(dict)
  for name, num_bytes in services_bytes.items():
    pools[sku_of_resource(name)][name] = num_bytes
  sku_costs = {
      k: v["net_cost_usd"] for k, v in (ingestion_by_sku or {}).items()
  }
  priced = {k: c for k, c in sku_costs.items() if c > 0}
  if len(priced) < 2 or any(not pools.get(k) for k in priced):
    return apportion_cents_exactly(services_bytes, total_cents), False

  # Whole cents per SKU, closing on the month total by largest remainder.
  sku_cents = {
      k: int(round(v * 100))
      for k, v in apportion_cents_exactly(
          {k: int(round(c * 100)) for k, c in priced.items()}, total_cents
      ).items()
  }
  result: Dict[str, float] = {name: 0.0 for name in services_bytes}
  for sku, cents in sku_cents.items():
    result.update(apportion_cents_exactly(pools[sku], cents))
  return result, True


# ==============================================================================
# Data Merging & Transformation Engine
# ==============================================================================


def merge_data(
    billing_data: Dict[str, List[List[Any]]],
    severity_data: Dict[str, Dict[str, List[List[Any]]]],
) -> Dict[str, Dict[str, Dict[str, Any]]]:
  """Merges billing and severity daily history per service and date."""
  merged: Dict[str, Dict[str, Dict[str, Any]]] = collections.defaultdict(
      lambda: collections.defaultdict(
          lambda: {"billing_total": 0, "severity": {}}
      )
  )

  for service, points in billing_data.items():
    for date_str, val in points:
      merged[service][date_str]["billing_total"] = val

  for service, sevs in severity_data.items():
    for severity, points in sevs.items():
      for date_str, val in points:
        merged[service][date_str]["severity"][severity] = val

  return {
      service: {d: data for d, data in dates.items()}
      for service, dates in merged.items()
  }


def _month_span(month: str) -> int:
  """Returns the number of days in `month` ('YYYY-MM')."""
  return calendar.monthrange(int(month[:4]), int(month[5:7]))[1]


def get_monthly_aggregations(
    billing_data: Dict[str, List[List[Any]]],
    price_book: PriceBook,
    billing_costs: Optional[Dict[str, Any]] = None,
    now: Optional[datetime.datetime] = None,
) -> Dict[str, Dict[str, Any]]:
  """Calculates monthly usage and cost summaries reconciled to the penny.

  Months are the union of telemetry months (42-day Cloud Monitoring retention)
  and invoiced months.

  Args:
    billing_data: Daily `[date, bytes]` points keyed by service.
    price_book: Prices the months the invoice does not cover.
    billing_costs: Optional output of `billing.query_logging_billing_costs`.
    now: Reference instant used to identify the in-progress month.

  Returns:
    A dict keyed by `YYYY-MM` with volume, cost, per-service breakdown and
    partial-month flags.
  """
  telemetry: Dict[str, Dict[str, Any]] = {}
  for service, points in billing_data.items():
    for date_str, val in points:
      month_str = date_str[:7]
      entry = telemetry.setdefault(
          month_str,
          {
              "bytes": 0,
              "services": collections.defaultdict(int),
              "dates": set(),
          },
      )
      entry["services"][service] += val
      entry["bytes"] += val
      entry["dates"].add(date_str)

  b_costs = billing_costs.get("monthly_costs", {}) if billing_costs else {}
  current_month = now.strftime("%Y-%m") if now else None
  monthly: Dict[str, Dict[str, Any]] = {}

  for month in sorted(set(telemetry) | set(b_costs)):
    tele = telemetry.get(month, {})
    services_bytes = dict(
        sorted(
            tele.get("services", {}).items(),
            key=lambda item: item[1],
            reverse=True,
        )
    )
    telemetry_bytes = tele.get("bytes", 0)
    coverage_days = len(tele.get("dates", set()))
    days_in_month = _month_span(month)
    billed = b_costs.get(month)

    if billed:
      raw_cost = billed["raw_cost_usd"]
      credits_amount = billed["credits_usd"]
      net_cost = billed["net_cost_usd"]
      sku_breakdown = billed["sku_breakdown"]
      data_source = "actual_bq_billing"
      total_gib = billed["ingestion_gib"]
      ingestion_cost = billed["ingestion_net_cost_usd"]
      observed_days = billed["billed_days"]
    else:
      total_gib = round(telemetry_bytes / BYTES_PER_GIB, 2)
      gib_by_sku: Dict[str, float] = collections.defaultdict(float)
      for name, num_bytes in services_bytes.items():
        gib_by_sku[price_book.sku_for_resource(name)] += (
            num_bytes / BYTES_PER_GIB
        )
      ingestion_cost = price_book.month_cost(gib_by_sku)
      raw_cost = ingestion_cost
      credits_amount = 0.0
      net_cost = ingestion_cost
      sku_breakdown = {ESTIMATED_SKU_NAME: ingestion_cost}
      data_source = "usage_estimated"
      observed_days = coverage_days

    # A month is partial until it has both ended and been fully observed.
    if month == current_month:
      is_partial, partial_reason = True, "month still in progress"
    elif observed_days < days_in_month:
      is_partial = True
      partial_reason = (
          f"{observed_days} of {days_in_month} days observed"
          f" ({'billing export' if billed else 'Cloud Monitoring retention'})"
      )
    else:
      is_partial, partial_reason = False, None

    # Shares are against the telemetry total, which may cover fewer days than
    # the invoiced total.
    services_basis_bytes = telemetry_bytes
    total_ingest_cents = int(round(ingestion_cost * 100))
    apportioned, services_per_sku = _apportion_by_sku(
        services_bytes,
        total_ingest_cents,
        billed["ingestion_by_sku"] if billed else None,
    )

    services_details: Dict[str, Dict[str, Any]] = {}
    for s_name, s_bytes in services_bytes.items():
      s_cost = apportioned.get(s_name, 0.0)
      share = (
          s_bytes / services_basis_bytes if services_basis_bytes > 0 else 0.0
      )
      services_details[s_name] = {
          "bytes": s_bytes,
          "gib": round(s_bytes / BYTES_PER_GIB, 2),
          "cost_usd": s_cost,
          "pct_of_volume": round(share * 100.0, 1),
      }
      # Telemetry keeps only 42 days; `billed_gib` restates the share on the
      # invoiced month's basis, matching `cost_usd`.
      if billed:
        services_details[s_name]["billed_gib"] = round(share * total_gib, 2)

    monthly[month] = {
        "total_gib": total_gib,
        "raw_cost_usd": raw_cost,
        "credits_usd": credits_amount,
        "net_cost_usd": net_cost,
        "ingestion_cost_usd": ingestion_cost,
        "data_source": data_source,
        "coverage_days": observed_days,
        "is_partial": is_partial,
        "partial_reason": partial_reason,
        "cost_by_sku": sku_breakdown,
        # Ingestion GiB and cost per billing SKU (log_storage / vended), the
        # pools the per-service dollars below are apportioned from.
        "ingestion_by_sku": billed["ingestion_by_sku"] if billed else {},
        "services_cost_basis": "per_sku" if services_per_sku else "blended",
        "services": services_bytes,
        "services_details": services_details,
        "top_service": top_driver(
            [{"service": k, **v} for k, v in services_details.items()]
        ),
        # Days the per-service split was measured over (vs invoiced days).
        "services_telemetry_days": coverage_days,
    }

  return monthly


def get_severity_summary(
    severity_data: Dict[str, Dict[str, List[List[Any]]]],
    now: datetime.datetime,
    days: int = DEFAULT_SAMPLE_DAYS,
    samples_by_service: Optional[
        Dict[str, Dict[str, List[Dict[str, Any]]]]
    ] = None,
    severity_source: str = "cloud_monitoring",
) -> Dict[str, Any]:
  """Summarises severity volume for the last N days.

  Args:
    severity_data: Daily `[date, bytes]` points keyed by service then severity.
    now: Reference instant; the window is the `days` before it.
    days: Length of the summarised window, in days.
    samples_by_service: Optional sampled log patterns keyed by service then
      severity, passed through to the result.
    severity_source: Which measurement the volumes came from, either
      "cloud_monitoring" or "log_analytics".

  Returns:
    A dict with the per-severity totals, the window description, per-service
    and per-day severity breakdowns, and the samples with their coverage.
  """
  start_date_str = window_start(now, days)

  severity_totals: Dict[str, int] = collections.defaultdict(int)
  severity_by_service: Dict[str, Dict[str, int]] = collections.defaultdict(
      lambda: collections.defaultdict(int)
  )
  daily_severity: Dict[str, Dict[str, int]] = collections.defaultdict(
      lambda: collections.defaultdict(int)
  )

  for service, sevs in severity_data.items():
    for sev, points in sevs.items():
      for date_str, val in points:
        if date_str >= start_date_str:
          severity_totals[sev] += val
          severity_by_service[service][sev] += val
          daily_severity[date_str][sev] += val

  def by_value(mapping: Dict[str, int]) -> Dict[str, int]:
    return dict(sorted(mapping.items(), key=lambda x: x[1], reverse=True))

  sorted_totals = by_value(severity_totals)
  sorted_services = sorted(
      severity_by_service,
      key=lambda s: sum(severity_by_service[s].values()),
      reverse=True,
  )

  return {
      "severity_totals": sorted_totals,
      "severity_source": severity_source,
      "window_days": days,
      "severity_by_service": {
          s: by_value(severity_by_service[s]) for s in sorted_services
      },
      "daily_severity": {
          d: by_value(daily_severity[d]) for d in sorted(daily_severity)
      },
      "samples_by_service": samples_by_service or {},
      "sample_coverage": _compute_sample_coverage(
          samples_by_service, severity_by_service, severity_source
      ),
  }


def _compute_sample_coverage(
    samples_by_service: Optional[Dict[str, Dict[str, List[Dict[str, Any]]]]],
    severity_by_service: Dict[str, Dict[str, int]],
    severity_source: str = "cloud_monitoring",
) -> Dict[str, Dict[str, Dict[str, Any]]]:
  """Reports what share of each stream the displayed patterns account for."""
  # The share is withheld unless both sides come from Log Analytics; otherwise
  # stream totals are Cloud Monitoring `byte_count` over a different window.
  coverage: Dict[str, Dict[str, Dict[str, Any]]] = {}
  if not samples_by_service:
    return coverage

  comparable = severity_source == "log_analytics"

  for service, sevs in samples_by_service.items():
    for severity, cards in (sevs or {}).items():
      measured = [c for c in cards if c["volume_measured"]]
      shown_bytes = sum(c["total_bytes"] for c in measured)
      stream_bytes = severity_by_service.get(service, {}).get(severity, 0)

      # Shown and stream totals come from different queries; withhold the share
      # (with a reason) rather than report coverage above 100%.
      if not comparable:
        reason = "bases_differ"
      elif stream_bytes <= 0:
        reason = "stream_volume_not_measured"
      elif shown_bytes > stream_bytes:
        reason = "shown_exceeds_stream"
      else:
        reason = None

      coverage.setdefault(service, {})[severity] = {
          "patterns_shown": len(measured),
          "shown_bytes": shown_bytes,
          "stream_bytes": stream_bytes,
          "shown_pct": (
              None if reason else round(shown_bytes / stream_bytes * 100.0, 1)
          ),
          "remainder_bytes": None if reason else stream_bytes - shown_bytes,
          "shown_pct_withheld": reason,
      }

  return coverage


def invoiced_window_gib(
    invoiced_daily_gib: Optional[Dict[str, float]],
    now: datetime.datetime,
    window_days: float,
) -> Optional[float]:
  """Returns the mean complete invoiced day scaled onto `window_days`."""
  # Metric buckets anchor to `now` and invoice buckets to Pacific days, so only
  # the span is matched. None means no invoiced anchor, not zero volume.
  if window_days <= 0:
    return None
  complete = complete_days(
      invoiced_daily_gib, window_start(now, window_days), now
  )
  if not complete:
    return None
  return (sum(complete.values()) / len(complete)) * window_days


def get_trailing_30d_summary(
    parsed_billing: Dict[str, List[List[Any]]],
    now: datetime.datetime,
    invoiced_daily_gib: Optional[Dict[str, float]] = None,
) -> Dict[str, Any]:
  """Calculates trailing 30-day volume, daily average and monthly run rate."""
  # Volume only; the caller prices it from the price book. Volume comes from
  # the invoice when `invoiced_daily_gib` is supplied, since
  # `billing/bytes_ingested` can silently under-report; the metric is then used
  # only for the per-service split.
  days = DEFAULT_TELEMETRY_LOOKBACK_DAYS
  cutoff_str = window_start(now, days)
  service_bytes = window_sums(parsed_billing, now, days)
  total_bytes = sum(service_bytes.values())
  invoiced = complete_days(invoiced_daily_gib, cutoff_str, now)

  if invoiced:
    total_gib = sum(invoiced.values())
    valid_days = len(invoiced)
    basis = "invoiced_daily_usage"
  else:
    total_gib = total_bytes / BYTES_PER_GIB
    observed_days = set()
    for points in parsed_billing.values():
      for day, _ in points:
        if day >= cutoff_str:
          observed_days.add(day)
    valid_days = max(1, len(observed_days))
    basis = "cloud_monitoring_metric"

  daily_avg_gib = total_gib / valid_days
  monthly_run_rate_gib = daily_avg_gib * DAYS_PER_MONTH

  ranked = sorted(service_bytes.items(), key=lambda kv: kv[1], reverse=True)

  def as_entry(name: str, num_bytes: int) -> Dict[str, Any]:
    # Share from the metric, magnitude from `total_gib`, so services sum to the
    # headline total.
    share = (num_bytes / total_bytes) if total_bytes else 0.0
    return {
        "service": name,
        "gib": round(share * total_gib, 2),
        "pct_of_total": round(share * 100.0, 1),
    }

  top_services = [as_entry(s, b) for s, b in ranked[:5]]
  # Remainder row so the listed shares sum to 100%.
  remainder = sum(b for _, b in ranked[5:])
  if remainder > 0:
    other = as_entry(f"Other ({len(ranked) - 5} services)", remainder)
    # Flagged so consumers need not match on the display name. It mixes
    # services on both SKUs, so it is never priced or ranked as one service.
    other["is_remainder"] = True
    top_services.append(other)

  return {
      "window_start": cutoff_str,
      "days_observed": valid_days,
      "total_gib": round(total_gib, 2),
      "daily_avg_gib": round(daily_avg_gib, 2),
      "monthly_run_rate_gib": round(monthly_run_rate_gib, 2),
      "volume_basis": basis,
      "top_services": top_services,
  }


def top_driver(top_services: Sequence[Dict[str, Any]]) -> Optional[str]:
  """The named service with the most estimated dollars, volume breaking ties."""
  # Vended GiB are cheaper, so the largest service by volume need not cost the
  # most. The remainder row is never a candidate.
  named = [s for s in top_services if not s.get("is_remainder")]
  if not named:
    return None
  return max(named, key=lambda s: (s["cost_usd"], s["gib"]))["service"]


def latest_complete_month(
    monthly: Mapping[str, Mapping[str, Any]],
) -> Optional[str]:
  """The newest month that has both ended and been fully observed."""
  return max(
      (m for m, e in monthly.items() if not e["is_partial"]), default=None
  )


def get_weekly_aggregations(
    parsed_billing: Dict[str, List[List[Any]]],
    now: datetime.datetime,
    price_book: PriceBook,
) -> Dict[str, Dict[str, Any]]:
  """Calculates 4 rolling 7-day weeks (W-1 to W-4) for WoW trend analysis.

  Args:
    parsed_billing: Daily `[date, bytes]` points keyed by service.
    now: Reference instant; W-1 is the seven days ending on its date.
    price_book: Prices each week at its average rate, so four weeks sum to about
      one monthly bill.

  Returns:
    A dict keyed `W-1` to `W-4` with dates, volume, cost, partial flag and
    per-service bytes.
  """
  rate = price_book.average_rate
  weeks: Dict[str, Dict[str, Any]] = {}
  for w_idx in range(1, 5):
    end_d = now - datetime.timedelta(days=(w_idx - 1) * 7)
    start_d = now - datetime.timedelta(days=w_idx * 7 - 1)
    start_str = start_d.strftime("%Y-%m-%d")
    end_str = end_d.strftime("%Y-%m-%d")

    w_bytes = 0
    w_services: Dict[str, int] = collections.defaultdict(int)
    for service, points in parsed_billing.items():
      for date_str, val in points:
        if start_str <= date_str <= end_str:
          w_bytes += val
          w_services[service] += val

    w_gib = w_bytes / BYTES_PER_GIB
    weeks[f"W-{w_idx}"] = {
        "start_date": start_str,
        "end_date": end_str,
        "total_bytes": w_bytes,
        "total_gib": round(w_gib, 2),
        "cost_usd": round(w_gib * rate, 2),
        # W-1 ends today, so it covers a partial final day and will always
        # look slightly lower than its neighbours.
        "is_partial": w_idx == 1,
        "services": dict(
            sorted(w_services.items(), key=lambda x: x[1], reverse=True)
        ),
    }

  return weeks


def get_daily_services(
    billing_data: Dict[str, List[List[Any]]],
    now: datetime.datetime,
    days: int = DEFAULT_SAMPLE_DAYS,
) -> Dict[str, Dict[str, int]]:
  """Extracts daily volume per service for the last N days."""
  start_date_str = window_start(now, days)
  daily_services: Dict[str, Dict[str, int]] = collections.defaultdict(
      lambda: collections.defaultdict(int)
  )
  for service, points in billing_data.items():
    for date_str, val in points:
      if date_str >= start_date_str:
        daily_services[date_str][service] += val

  return {
      d: dict(
          sorted(
              daily_services[d].items(),
              key=lambda x: x[1],
              reverse=True,
          )
      )
      for d in sorted(daily_services.keys())
  }


def get_mom_patterns(
    monthly_aggregations: Dict[str, Dict[str, Any]],
) -> Dict[str, Dict[str, Any]]:
  """Pre-computes Month-over-Month volume and cost growth patterns."""
  trends: Dict[str, Dict[str, Any]] = collections.defaultdict(dict)
  months = list(monthly_aggregations.keys())

  for i in range(1, len(months)):
    prev_month, curr_month = months[i - 1], months[i]
    period_key = f"{prev_month}_to_{curr_month}"

    prev_data = monthly_aggregations[prev_month]
    curr_data = monthly_aggregations[curr_month]

    prev_services = prev_data["services"]
    curr_services = curr_data["services"]
    all_services = set(prev_services.keys()) | set(curr_services.keys())

    prev_cost = prev_data["net_cost_usd"]
    curr_cost = curr_data["net_cost_usd"]
    cost_delta = round(curr_cost - prev_cost, 2)
    cost_pct_change = (
        "NEW"
        if prev_cost == 0
        else round(((curr_cost - prev_cost) / prev_cost) * 100, 1)
    )

    partial_sides = [
        f"{label} ({data['partial_reason']})"
        for label, data in ((prev_month, prev_data), (curr_month, curr_data))
        if data["is_partial"]
    ]

    total_entry: Dict[str, Any] = {
        "cost_change_usd": cost_delta,
        "cost_pct_change": cost_pct_change,
        # A comparison involving a partial month is not a trend; the UI
        # suppresses the percentage.
        "comparable": not partial_sides,
    }
    if partial_sides:
      total_entry["partial_warning"] = "Not directly comparable: " + "; ".join(
          partial_sides
      )

    trends["_monthly_total"][period_key] = total_entry

    for service in all_services:
      prev_val = prev_services.get(service, 0)
      curr_val = curr_services.get(service, 0)
      if prev_val == 0 and curr_val == 0:
        continue

      bytes_change = curr_val - prev_val
      pct_change = (
          "NEW" if prev_val == 0 else round((bytes_change / prev_val) * 100, 1)
      )
      trends[service][period_key] = {
          "bytes_change": bytes_change,
          "pct_change": pct_change,
      }

  return dict(trends)


def project_month(
    now: datetime.datetime,
    price_book: PriceBook,
    parsed_billing: Dict[str, List[List[Any]]],
    invoiced_daily_gib_by_sku: Optional[Dict[str, Dict[str, float]]] = None,
) -> Dict[str, Any]:
  """Projects this month's ingestion bill to month end, priced by the book.

  Each SKU's month-end GiB is its mean GiB/day over the month's complete days
  times the month's length, never less than month-to-date. Both figures are
  priced as whole months, so the free tier comes off once and only where it
  exists.

  Args:
    now: Reference instant; its calendar month is the one projected.
    price_book: Maps services to SKUs and prices both figures.
    parsed_billing: `billing/bytes_ingested` daily points per resource type;
      used when the invoice has no rows for this month yet.
    invoiced_daily_gib_by_sku: Invoiced ingestion GiB per SKU per Pacific day.

  Returns:
    The projected month, the month-to-date and end-of-month volume (total and
    per SKU) and cost, a `volume_basis`, and a human-readable note.
  """
  month = now.strftime("%Y-%m")
  invoiced = {
      sku: {d: g for d, g in days.items() if d.startswith(month)}
      for sku, days in (invoiced_daily_gib_by_sku or {}).items()
  }
  invoiced = {sku: days for sku, days in invoiced.items() if days}
  if invoiced:
    daily_by_sku = invoiced
    volume_basis = "invoiced_daily_usage"
  else:
    daily_by_sku = collections.defaultdict(
        lambda: collections.defaultdict(float)
    )
    for service, points in parsed_billing.items():
      sku = price_book.sku_for_resource(service)
      for day, num_bytes in points:
        if day.startswith(month):
          daily_by_sku[sku][day] += num_bytes / BYTES_PER_GIB
    volume_basis = "cloud_monitoring_metric"

  so_far_by_sku: Dict[str, float] = {}
  eom_by_sku: Dict[str, float] = {}
  for sku, days in daily_by_sku.items():
    # Cloud Monitoring returns only whole UTC days; the invoice's latest day
    # can still be filling in, so it must not drag the mean down.
    complete = complete_days(days, month, now) if invoiced else days
    so_far_by_sku[sku] = sum(days.values())
    per_day = sum(complete.values()) / len(complete) if complete else 0.0
    eom_by_sku[sku] = max(so_far_by_sku[sku], per_day * _month_span(month))
  so_far_by_sku = price_book.collapse(so_far_by_sku)
  eom_by_sku = price_book.collapse(eom_by_sku)

  return {
      "month": month,
      "projection_method": "linear_monthly_run_rate",
      "volume_basis": volume_basis,
      "so_far_gib": round(sum(so_far_by_sku.values()), 2),
      "projected_eom_gib": round(sum(eom_by_sku.values()), 2),
      "so_far_gib_by_sku": {k: round(v, 2) for k, v in so_far_by_sku.items()},
      "projected_eom_gib_by_sku": {
          k: round(v, 2) for k, v in eom_by_sku.items()
      },
      "so_far_cost_usd": price_book.month_cost(so_far_by_sku),
      "projected_eom_cost_usd": price_book.month_cost(eom_by_sku),
      "confidence_note": (
          f"Cost projected per SKU ({price_book.formula_terms()}), before"
          " credits."
      ),
  }
analytics.py 25.6 KB
"""Log Analytics bucket detection, probe, breakdown queries and census samples."""

import collections
import concurrent.futures
import datetime
import json
import re
from typing import Any, Dict, List, Optional, Tuple

from constants import BYTES_PER_GIB
from constants import DEFAULT_BUCKET_ID
from constants import DEFAULT_LOCATION
from constants import DEFAULT_SAMPLE_DAYS
from constants import mask_sql
from constants import MAX_SAMPLES_PER_SEVERITY
from constants import PAYLOAD_BYTES_SQL
from constants import quote_table_ref
from constants import SIGNATURE_TEMPLATE_CHARS
from google.api_core import exceptions as api_exceptions
from google.cloud import bigquery
from google.cloud.logging_v2.services import config_service_v2

ConfigServiceV2Client = config_service_v2.ConfigServiceV2Client


def _parse_bucket_info(
    b: Any, loc: str, config_client: ConfigServiceV2Client
) -> Dict[str, Any]:
  """Extracts retention, analytics status and linked dataset from a bucket."""
  linked_dataset = None
  if b.analytics_enabled:
    try:
      for link in config_client.list_links(request={"parent": b.name}):
        if link.bigquery_dataset.dataset_id:
          linked_dataset = link.bigquery_dataset.dataset_id.rsplit("/", 1)[-1]
          break
    except api_exceptions.GoogleAPICallError as e:
      # The bucket's own name still resolves its view without the link.
      print(f"Notice: unable to list links for {b.name}: {e}")

  return {
      "name": b.name,
      "bucket_id": b.name.rsplit("/", 1)[-1],
      "location": loc,
      "analytics_enabled": bool(b.analytics_enabled),
      # Unset (0) means the default retention.
      "retention_days": int(b.retention_days or 30),
      "linked_dataset": linked_dataset,
  }


def detect_log_analytics_buckets(
    config_client: ConfigServiceV2Client,
    project_id: str,
    location: str = DEFAULT_LOCATION,
) -> List[Dict[str, Any]]:
  """Detects log buckets, their Log Analytics status and linked datasets."""
  detected_buckets = []
  locations_to_try = (
      [location] if location == "global" else [location, "global"]
  )

  for loc in locations_to_try:
    parent = f"projects/{project_id}/locations/{loc}"
    try:
      buckets = config_client.list_buckets(request={"parent": parent})
      for b in buckets:
        detected_buckets.append(_parse_bucket_info(b, loc, config_client))
    except api_exceptions.GoogleAPICallError as e:
      print(f"Notice: Unable to list buckets in location '{loc}': {e}")

  if not detected_buckets:
    for loc in locations_to_try:
      bucket_path = (
          f"projects/{project_id}/locations/{loc}/buckets/{DEFAULT_BUCKET_ID}"
      )
      try:
        b = config_client.get_bucket(request={"name": bucket_path})
      except api_exceptions.GoogleAPICallError:
        continue
      detected_buckets.append(_parse_bucket_info(b, loc, config_client))
      break

  detected_buckets.sort(
      key=lambda b: (
          b["bucket_id"] != DEFAULT_BUCKET_ID,
          not b["linked_dataset"],
          not b["analytics_enabled"],
      )
  )
  return detected_buckets


# The probe only sees the last `sample_days`, and the oldest entry inside that
# window lands a little after its start, so a full window reads slightly short.
MATURITY_TOLERANCE_DAYS = 0.5

_NO_DATA = {
    "status": "too_fresh",
    "days_available": 0.0,
    "earliest_log": None,
    "latest_log": None,
    "total_entries": 0,
}


def probe_log_analytics_data(
    bq_client: bigquery.Client,
    project_id: str,
    location: str = DEFAULT_LOCATION,
    bucket_id: str = DEFAULT_BUCKET_ID,
    sample_days: int = DEFAULT_SAMPLE_DAYS,
    now: Optional[datetime.datetime] = None,
    linked_dataset: Optional[str] = None,
) -> Dict[str, Any]:
  """Probes the Log Analytics view for data volume, age and maturity tier.

  Args:
    bq_client: BigQuery client.
    project_id: project owning the bucket.
    location: bucket location.
    bucket_id: Log Analytics bucket.
    sample_days: lookback window in days.
    now: current time; defaults to now (UTC).
    linked_dataset: linked BigQuery dataset, tried first.

  Returns:
    The probe result. Its `table_name` is the view that answered (unquoted),
    or None if none did; the breakdown and Prove It query that same view.
  """
  if now is None:
    now = datetime.datetime.now(datetime.timezone.utc)

  dataset = "default_logs" if bucket_id == "_Default" else f"{bucket_id}_logs"
  candidate_tables = [
      f"{project_id}.{linked_dataset}._AllLogs" if linked_dataset else None,
      f"{project_id}.{bucket_id}._AllLogs",
      f"{project_id}.{location}.{bucket_id}._AllLogs",
      f"{project_id}.{dataset}._AllLogs",
  ]
  job_config = bigquery.QueryJobConfig(
      query_parameters=[bigquery.ScalarQueryParameter("now", "TIMESTAMP", now)]
  )
  bq_loc = None if location == "global" else location

  last_error = None
  for table_name in dict.fromkeys(filter(None, candidate_tables)):
    # Timestamps and a row count only: maturity depends on nothing else, and
    # summing payload bytes here would scan every payload column.
    query = f"""
    SELECT
      MIN(timestamp) AS earliest_log,
      MAX(timestamp) AS latest_log,
      COUNT(1) AS total_entries,
      TIMESTAMP_DIFF(@now, MIN(timestamp), HOUR) AS hours_available
    FROM {quote_table_ref(table_name)}
    WHERE timestamp >= TIMESTAMP_SUB(@now, INTERVAL {sample_days} DAY)
    """
    try:
      rows = list(
          bq_client.query(
              query, location=bq_loc, job_config=job_config
          ).result()
      )
    except api_exceptions.GoogleAPICallError as e:
      # The view may live under any of the candidate names.
      last_error = e
      continue
    if not rows or not rows[0]["total_entries"]:
      return {**_NO_DATA, "table_name": table_name}

    row = rows[0]
    hours = float(row["hours_available"])
    days = round(hours / 24.0, 1)
    if hours < 24:
      status = "too_fresh"
    elif days < sample_days - MATURITY_TOLERANCE_DAYS:
      status = "partial_window"
    else:
      status = "mature"
    return {
        "status": status,
        "days_available": days,
        "earliest_log": row["earliest_log"].isoformat(),
        "latest_log": row["latest_log"].isoformat(),
        "total_entries": int(row["total_entries"]),
        "table_name": table_name,
    }

  print(f"Notice: Log Analytics probe query encountered: {last_error}")
  return {**_NO_DATA, "table_name": None}


def _strip_nulls(value: Any) -> Any:
  """Recursively drops null, empty-object and empty-array fields."""
  if isinstance(value, dict):
    cleaned = {k: _strip_nulls(v) for k, v in value.items()}
    return {k: v for k, v in cleaned.items() if v not in (None, {}, [])}
  if isinstance(value, list):
    cleaned = [_strip_nulls(v) for v in value]
    return [v for v in cleaned if v not in (None, {}, [])]
  return value


def _clean_payload(value: Optional[str]) -> Any:
  """Returns a payload column's real content, or None if it has none."""
  # `TO_JSON_STRING(NULL)` yields "null", and the `_AllLogs` proto_payload
  # struct serialises as a skeleton of null fields even when the entry has no
  # proto content. Both are treated as absent.
  if not value or not value.strip():
    return None
  try:
    parsed = json.loads(value)
  except ValueError:
    return value
  return _strip_nulls(parsed) or None


def _format_payload(value: Any) -> str:
  if isinstance(value, (dict, list)):
    return json.dumps(value, indent=2)
  return str(value)


def _truncate(text: str) -> str:
  return text if len(text) <= 2000 else text[:2000] + "... [truncated]"


def _parse_sample_log_from_bq_row(r: Any) -> Dict[str, Any]:
  """Parses the sample entry carried by one signature row."""
  ts = r["sample_timestamp"]
  labels = r["sample_resource_labels"]  # TO_JSON_STRING, so valid JSON.
  text_payload = r["sample_text_payload"]
  json_payload = _clean_payload(r["sample_json_payload"])
  proto_payload = _clean_payload(r["sample_proto_payload"])

  if text_payload:
    payload_str, payload_type = text_payload, "text"
  elif json_payload is not None:
    payload_str, payload_type = _format_payload(json_payload), "json"
  elif proto_payload is not None:
    payload_str, payload_type = _format_payload(proto_payload), "proto"
  else:
    payload_str, payload_type = r["signature_preview"], "text"

  return {
      "timestamp": ts.isoformat() if ts else None,
      "log_name": r["sample_log_name"].rsplit("/", 1)[-1],
      "resource_type": r["service"],
      "resource_labels": json.loads(labels) if labels else {},
      "payload": _truncate(payload_str),
      "payload_type": payload_type,
  }


_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]")

# Artifacts of the SQL COALESCE falling through, not real messages.
_EMPTY_PREVIEWS = ("structured_payload", "null", "\\r\\n", "...")

_SYSLOG_PREFIX = re.compile(
    r"^[A-Z][a-z]{2}\s+\d+\s+\d+:\d+:\d+\s+[\w\-\.]+\s+([^:]+:\s*.+)$"
)

_TITLE_CHARS = 80


def _shape_title(preview: str) -> Tuple[str, str]:
  """Renders a JSON key skeleton as a de-duplicated field list."""
  keys = list(dict.fromkeys(k.strip() for k in preview.split(",") if k.strip()))
  if not keys:
    return "Structured record", preview
  shown = ", ".join(keys[:6])
  suffix = f" +{len(keys) - 6} more" if len(keys) > 6 else ""
  return f"Structured record ({len(keys)} fields): {shown}{suffix}", preview


def derive_display_text(sig: Dict[str, Any]) -> Tuple[str, str]:
  """Derives a display-only `(title, preview)` for a signature."""
  # Never build a filter from the result: it is cleaned and may not match the
  # rows the volume was measured over.
  raw = sig["preview"].strip()
  # A shape cluster's preview is a key skeleton, not prose.
  if sig["signature_source"] == "json_shape":
    return _shape_title(raw)

  clean = _CONTROL_CHARS.sub("", raw).strip()
  # A syslog timestamp and hostname are identical across every line in the
  # cluster, so they push the informative part out of the title.
  syslog_match = _SYSLOG_PREFIX.match(clean)
  if syslog_match:
    clean = syslog_match.group(1).strip()

  if not clean or clean in _EMPTY_PREVIEWS:
    log_id = sig["log_id"]
    label = log_id if log_id != "unknown" else sig["service"]
    return f"{sig['severity']} log in {label}", (clean or raw)

  title = clean[:_TITLE_CHARS].rstrip()
  if len(clean) > _TITLE_CHARS:
    title += "..."
  return title, clean


def build_samples_from_signatures(
    sigs: List[Dict[str, Any]],
) -> Dict[str, Dict[str, List[Dict[str, Any]]]]:
  """Selects representative log patterns per service and severity."""
  # Display-only census: cards carry no exclusion filter.
  by_service: Dict[str, Dict[str, List[Dict[str, Any]]]] = (
      collections.defaultdict(lambda: collections.defaultdict(list))
  )

  for s in sigs:
    title, preview = derive_display_text(s)
    by_service[s["service"]][s["severity"]].append({
        "title": title,
        "log_id": s["log_id"],
        "entry_count": s["count"],
        "total_bytes": s["total_bytes"],
        "total_gib": round(s["total_bytes"] / BYTES_PER_GIB, 2),
        # Not rendered as a filter; tells the reader what the pattern matched.
        "signature_source": s["signature_source"],
        "volume_measured": s["total_bytes"] > 0 or s["count"] > 0,
        "sample_log": s["sample_log"],
        "preview": preview,
    })

  out: Dict[str, Dict[str, List[Dict[str, Any]]]] = {}
  for srv, sevs in by_service.items():
    out[srv] = {}
    for sev, cards in sevs.items():
      cards.sort(
          key=lambda c: (c["total_bytes"], c["entry_count"]), reverse=True
      )
      out[srv][sev] = cards[:MAX_SAMPLES_PER_SEVERITY]
  return out


def format_logging_entry(
    entry: Any,
    service: str,
    severity: str,
) -> Dict[str, Any]:
  """Formats a `google.cloud.logging_v2` entry into a census sample item."""
  log_id = (entry.log_name or "unknown").rsplit("/", 1)[-1]
  res = entry.resource
  payload_val = entry.payload
  if isinstance(payload_val, dict):  # StructEntry
    payload_str, payload_type = json.dumps(payload_val, indent=2), "json"
  elif payload_val is not None:
    payload_str, payload_type = str(payload_val), "text"
  else:
    payload_str, payload_type = "", "empty"
  payload_str = _truncate(payload_str)

  return {
      "title": f"Recent {severity} log in {service} ({log_id})",
      "log_id": log_id,
      # API fallback samples carry no measured volume.
      "total_bytes": 0,
      "total_gib": 0.0,
      "entry_count": 0,
      "signature_source": "none",
      "volume_measured": False,
      "sample_log": {
          "timestamp": entry.timestamp.isoformat() if entry.timestamp else None,
          "log_name": log_id,
          "resource_type": res.type if res else service,
          "resource_labels": dict(res.labels or {}) if res else {},
          "payload": payload_str,
          "payload_type": payload_type,
      },
      "preview": payload_str[:120],
  }


_SAMPLE_FETCH_WORKERS = 8
_MAX_SAMPLE_PAIRS = 24


def _list_recent_entries(
    logging_client: Any,
    resource_names: List[str],
    filter_str: str,
    max_results: int,
) -> List[Any]:
  """Returns the newest `max_results` entries matching a filter."""
  return list(
      logging_client.list_entries(
          resource_names=resource_names,
          filter_=filter_str,
          order_by="timestamp desc",
          page_size=max_results,
          max_results=max_results,
      )
  )


def fetch_logging_api_samples(
    logging_client: Any,
    project_id: str,
    top_services: List[str],
    parsed_severity: Dict[str, Dict[str, Any]],
    samples_by_service: Dict[str, Dict[str, List[Dict[str, Any]]]],
    now: Optional[datetime.datetime] = None,
    lookback_days: int = DEFAULT_SAMPLE_DAYS,
    read_scope: Optional[Dict[str, Any]] = None,
) -> Dict[str, Dict[str, str]]:
  """Fetches recent log entries via the Logging API for streams with no census.

  Measured census cards are never replaced. Pairs are read concurrently and
  capped at `_MAX_SAMPLE_PAIRS`.

  Args:
    logging_client: A `google.cloud.logging_v2.Client`.
    project_id: Project whose entries are read.
    top_services: Resource types to sample, in rank order.
    parsed_severity: Severities observed per service; picks which to sample.
    samples_by_service: Filled in place with formatted samples.
    now: Reference instant for the read window. Defaults to the current time.
    lookback_days: Length of the read window; matches the severity breakdown.
    read_scope: From `inventory.resolve_log_read_scope`. Defaults to the
      project's own buckets.

  Returns:
    `{service: {severity: message}}` explaining each pair that yielded no
    samples (API error or empty window).
  """
  sample_errors: Dict[str, Dict[str, str]] = collections.defaultdict(dict)
  if not top_services:
    return {}

  pairs = []
  for srv in top_services:
    if srv not in samples_by_service:
      samples_by_service[srv] = {}

    sevs = list(parsed_severity.get(srv, {}).keys())
    if not sevs:
      sevs = ["INFO", "ERROR", "WARNING", "DEBUG", "DEFAULT"]

    for sev in sevs:
      if samples_by_service[srv].get(sev):
        continue
      pairs.append((srv, sev))

  if not pairs:
    return {}
  # Ordered by service rank already, so the truncation drops the least
  # significant streams rather than an arbitrary slice.
  pairs = pairs[:_MAX_SAMPLE_PAIRS]

  log_scope = (read_scope or {}).get("log_scope")
  resource_names = list(
      (read_scope or {}).get("resource_names") or [f"projects/{project_id}"]
  )
  scoped = (read_scope or {}).get("source") == "default_scope"

  # `list_entries` silently narrows any filter without a `timestamp` clause to
  # the last 24 hours; state the breakdown's window instead.
  now = now or datetime.datetime.now(datetime.timezone.utc)
  start = now - datetime.timedelta(days=lookback_days)
  window_filter = f'timestamp >= "{start.strftime("%Y-%m-%dT%H:%M:%SZ")}"'
  empty_message = f"No log entries in the last {lookback_days} days."
  where = f"projects/{project_id}"
  required_roles = "roles/logging.viewer"
  if scoped:
    # A log scope can span other projects' views. Only this project's entries
    # describe the volume being audited, so samples are limited to them.
    window_filter = (
        f'logName:"projects/{project_id}/logs/" AND {window_filter}'
    )
    empty_message = (
        f"No log entries from {project_id} in the last {lookback_days} days"
        f" in log scope {log_scope}."
    )
    where = f"log scope {log_scope}"
    required_roles += " (and roles/logging.viewAccessor on its log views)"

  # One cheap read first. If the project cannot be read at all, every stream
  # would fail the same way, so there is no point issuing the rest.
  try:
    probe = _list_recent_entries(
        logging_client, resource_names, window_filter, max_results=1
    )
  except Exception as e:  # pylint: disable=broad-except
    print(
        "[FINOPS ADVISORY] Representative logs unavailable: could not read"
        f" log entries in {where} ({e}). Reading entries requires"
        f" {required_roles}. Service Details will show this error instead"
        " of samples."
    )
    probe, empty_message = [], str(e)
  if not probe:
    for srv, sev in pairs:
      sample_errors[srv][sev] = empty_message
    return dict(sample_errors)

  def fetch_pair(srv: str, sev: str) -> None:
    # DEFAULT is a real severity value, not a wildcard.
    filter_str = (
        f'resource.type = "{srv}" AND severity = "{sev}" AND {window_filter}'
    )
    try:
      entries = _list_recent_entries(
          logging_client, resource_names, filter_str, MAX_SAMPLES_PER_SEVERITY
      )
    except Exception as e:  # pylint: disable=broad-except
      # One unreadable stream must not cost the others their samples.
      print(
          "Notice: Could not fetch sample logs via Logging API for"
          f" {srv}/{sev}: {e}"
      )
      sample_errors[srv][sev] = str(e)
      return
    if entries:
      samples_by_service[srv][sev] = [
          format_logging_entry(entry, srv, sev) for entry in entries
      ]
    else:
      sample_errors[srv][sev] = empty_message

  with concurrent.futures.ThreadPoolExecutor(
      max_workers=min(_SAMPLE_FETCH_WORKERS, len(pairs))
  ) as executor:
    list(executor.map(lambda pair: fetch_pair(*pair), pairs))
  return dict(sample_errors)


def query_log_analytics_breakdown(
    bq_client: bigquery.Client,
    table_name: str,
    sample_days: int = DEFAULT_SAMPLE_DAYS,
    location: str = DEFAULT_LOCATION,
) -> Dict[str, Any]:
  """Runs the Log Analytics severity, log name and signature queries."""
  table = quote_table_ref(table_name)
  window = (
      f"timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL {sample_days}"
      " DAY)"
  )
  log_id_sql = (
      "COALESCE(log_id, REGEXP_EXTRACT(log_name, r'logs/([^/]+)$'), 'unknown')"
  )
  severity_sql = f"""
          SELECT
            COALESCE(resource.type, 'unknown') AS service,
            COALESCE(severity, 'DEFAULT') AS severity,
            FORMAT_DATE('%Y-%m-%d', DATE(timestamp)) AS log_date,
            COUNT(1) AS entry_count,
            SUM({PAYLOAD_BYTES_SQL}) AS total_bytes
          FROM {table}
          WHERE {window}
          GROUP BY service, severity, log_date
          ORDER BY service, log_date
      """
  log_names_sql = f"""
          SELECT
            COALESCE(resource.type, 'unknown') AS service,
            {log_id_sql} AS log_id,
            COALESCE(severity, 'DEFAULT') AS severity,
            COUNT(1) AS entry_count
          FROM {table}
          WHERE {window}
          GROUP BY service, log_id, severity
          ORDER BY entry_count DESC
          LIMIT 100
      """
  signatures_sql = f"""
          WITH extracted AS (
            SELECT
              COALESCE(resource.type, 'unknown') AS service,
              {log_id_sql} AS log_id,
              COALESCE(severity, 'DEFAULT') AS severity,
              -- JSON_VALUE is case-sensitive, and systemd writes MESSAGE.
              COALESCE(
                text_payload,
                JSON_VALUE(json_payload.message),
                JSON_VALUE(json_payload.MESSAGE),
                JSON_VALUE(json_payload.msg),
                JSON_VALUE(json_payload.log),
                proto_payload.audit_log.method_name
              ) AS raw_message,
              -- Mirrors the COALESCE above so filters target the right field.
              CASE
                WHEN text_payload IS NOT NULL THEN 'text_payload'
                WHEN JSON_VALUE(json_payload.message) IS NOT NULL THEN 'json_message'
                WHEN JSON_VALUE(json_payload.MESSAGE) IS NOT NULL THEN 'json_MESSAGE'
                WHEN JSON_VALUE(json_payload.msg) IS NOT NULL THEN 'json_msg'
                WHEN JSON_VALUE(json_payload.log) IS NOT NULL THEN 'json_log'
                WHEN proto_payload.audit_log.method_name IS NOT NULL THEN 'audit_method'
                WHEN json_payload IS NOT NULL THEN 'json_shape'
                WHEN proto_payload.type IS NOT NULL THEN 'proto_type'
                ELSE 'none'
              END AS signature_source,
              -- Key skeleton for message-less JSON. DISTINCT + ORDER BY
              -- canonicalise it so key order/repetition don't split groups.
              ARRAY_TO_STRING(
                ARRAY(
                  SELECT DISTINCT k
                  FROM UNNEST(
                    REGEXP_EXTRACT_ALL(
                      TO_JSON_STRING(json_payload), r'"([^"]+)":'
                    )
                  ) AS k
                  ORDER BY k
                ),
                ','
              ) AS json_shape,
              proto_payload.type AS proto_type,
              timestamp, text_payload, json_payload, proto_payload,
              log_name, resource
            FROM {table}
            WHERE {window}
          ),
          templated AS (
            SELECT
              *,
              SUBSTR(
                COALESCE(
                  -- Audit method names are already canonical; masking them
                  -- would fold v1/v2/v3 of an API onto one template.
                  IF(signature_source = 'audit_method',
                     raw_message,
                     {mask_sql('raw_message')}),
                  NULLIF(json_shape, ''),
                  proto_type,
                  'structured_payload'
                ),
                1, {SIGNATURE_TEMPLATE_CHARS}
              ) AS signature_preview
            FROM extracted
          ),
          grouped_signatures AS (
            SELECT
              service,
              log_id,
              severity,
              signature_preview,
              signature_source,
              COUNT(1) AS entry_count,
              SUM({PAYLOAD_BYTES_SQL}) AS total_bytes,
              -- One ANY_VALUE(STRUCT) so all sample fields come from one row.
              ANY_VALUE(STRUCT(
                timestamp AS sample_timestamp,
                text_payload AS sample_text_payload,
                TO_JSON_STRING(json_payload) AS sample_json_payload,
                TO_JSON_STRING(proto_payload) AS sample_proto_payload,
                TO_JSON_STRING(resource.labels) AS sample_resource_labels,
                log_name AS sample_log_name
              )) AS sample_entry
            FROM templated
            GROUP BY service, log_id, severity, signature_preview, signature_source
          ),
          ranked_signatures AS (
            SELECT *,
              SUM(total_bytes) OVER (PARTITION BY service, severity, log_id) AS stream_total_bytes,
              SUM(entry_count) OVER (PARTITION BY service, severity, log_id) AS stream_entry_count,
              ROW_NUMBER() OVER (PARTITION BY service, severity ORDER BY total_bytes DESC) AS rank_in_sev,
              ROW_NUMBER() OVER (ORDER BY total_bytes DESC) AS global_rank
            FROM grouped_signatures
          )
          SELECT
            * EXCEPT (sample_entry, rank_in_sev, global_rank),
            sample_entry.*
          FROM ranked_signatures
          -- Wider than rendered: the optimizer dedupes clusters per rule.
          WHERE rank_in_sev <= 15 OR global_rank <= 30
          ORDER BY total_bytes DESC
      """

  bq_loc = None if location == "global" else location
  with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
    severity_rows, log_name_rows, signature_rows = pool.map(
        lambda sql: list(bq_client.query(sql, location=bq_loc).result()),
        (severity_sql, log_names_sql, signatures_sql),
    )

  # One unit for the whole result set, so bytes and entries never mix.
  by_bytes = any(r["total_bytes"] > 0 for r in severity_rows)
  volume_column = "total_bytes" if by_bytes else "entry_count"

  parsed_sev: Dict[str, Dict[str, List[List[Any]]]] = collections.defaultdict(
      lambda: collections.defaultdict(list)
  )
  for r in severity_rows:
    parsed_sev[r["service"]][r["severity"]].append(
        [r["log_date"], int(r[volume_column])]
    )

  top_logs: Dict[str, List[Dict[str, Any]]] = collections.defaultdict(list)
  for r in log_name_rows:
    top_logs[r["service"]].append({
        "log_id": r["log_id"],
        "severity": r["severity"],
        "count": int(r["entry_count"]),
    })

  sigs = [
      {
          "service": r["service"],
          "log_id": r["log_id"],
          "severity": r["severity"],
          "preview": r["signature_preview"],
          "count": int(r["entry_count"]),
          "total_bytes": int(r["total_bytes"]),
          "stream_total_bytes": int(r["stream_total_bytes"]),
          "stream_entry_count": int(r["stream_entry_count"]),
          "signature_source": r["signature_source"],
          "sample_log": _parse_sample_log_from_bq_row(r),
      }
      for r in signature_rows
  ]

  return {
      "severity_history": {srv: dict(sevs) for srv, sevs in parsed_sev.items()},
      # The coverage denominator; never an entry count posing as bytes.
      "total_payload_bytes": (
          sum(int(r["total_bytes"]) for r in severity_rows) if by_bytes else 0
      ),
      "top_log_names": dict(top_logs),
      "top_signatures": sigs,
      "samples_by_service": build_samples_from_signatures(sigs),
  }
attribution.py 2.3 KB
"""Usage attribution for the Google Cloud API requests this skill sends.

Prefixes `google-skills/1.0 (skill:cloud-logging-finops; script:<script>)` to
the `User-Agent` (HTTP/JSON) or `x-goog-api-client` (gRPC) header. The token
carries no project, user, or request data.
"""

from typing import Any

SKILL_NAME = "cloud-logging-finops"

# Version of the token format the usage analytics parse, not of this skill.
_TOKEN_FORMAT_VERSION = "1.0"

# Script names as they appear in the token. Library modules (billing,
# inventory, analytics, ...) only run inside `collect_logging_data.py`, so they
# attribute their requests to it.
COLLECT_LOGGING_DATA = "collect-logging-data"
VERIFY_CLAIM = "verify-claim"


def user_agent(script: str) -> str:
  """Returns the attribution token for requests sent by `script`."""
  return (
      f"google-skills/{_TOKEN_FORMAT_VERSION}"
      f" (skill:{SKILL_NAME}; script:{script})"
  )


def _prefixed(token: str, existing: Any) -> str:
  return f"{token} {existing}" if existing else token


def client_info(script: str) -> Any:
  """Returns a ClientInfo that tags every request a client sends."""
  # Works for both GAPIC and HTTP/JSON clients (it subclasses the base one).
  from google.api_core.gapic_v1 import client_info as gapic_client_info  # pylint: disable=g-import-not-at-top

  return gapic_client_info.ClientInfo(user_agent=user_agent(script))


def tag_session(session: Any, script: str) -> Any:
  """Prefixes the token to a `requests.Session`'s User-Agent; returns it."""
  session.headers["User-Agent"] = _prefixed(
      user_agent(script), session.headers.get("User-Agent")
  )
  return session


def discovery_request_builder(script: str) -> Any:
  """Returns a `requestBuilder` for `googleapiclient.discovery.build`."""
  # Discovery clients take no user-agent option; `requestBuilder` builds every
  # request, including `list_next` pages.
  from googleapiclient import http as googleapiclient_http  # pylint: disable=g-import-not-at-top

  token = user_agent(script)

  class _AttributedHttpRequest(googleapiclient_http.HttpRequest):

    def __init__(self, *args: Any, **kwargs: Any) -> None:
      headers = dict(kwargs.get("headers") or {})
      headers["user-agent"] = _prefixed(token, headers.get("user-agent"))
      kwargs["headers"] = headers
      super().__init__(*args, **kwargs)

  return _AttributedHttpRequest
billing.py 22.6 KB
"""Finds the Cloud Billing BigQuery export and reads Cloud Logging costs."""

import collections
import concurrent.futures
import dataclasses
import datetime
import functools
import re
import time
from typing import Any, Dict, Iterator, List, Optional, Tuple

import attribution
from constants import DEFAULT_ANALYSIS_MONTHS
from constants import INGESTION_PRICING_UNIT
from constants import INGESTION_SKU_NAME
from constants import INVOICE_TIMEZONE
from constants import LOGGING_SCOPE_SQL
from constants import LOGGING_SERVICE_ID
from constants import LOGGING_SERVICE_NAME
from constants import quote_table_ref
import google.auth
from google.cloud import bigquery
import googleapiclient.discovery
from pricing import sku_of_description

# Billing modes, keyed on what the caller knows about the export's location:
#   `explicit` probe the named table/scope only.
#   `none`     no export; skip discovery and use list pricing.
#   `search`   this project, then the whole billing account.
MODE_NONE = "none"
MODE_EXPLICIT = "explicit"
MODE_SEARCH = "search"
BILLING_MODES = (MODE_NONE, MODE_EXPLICIT, MODE_SEARCH)

# Outcomes recorded per tier in `fallback_chain`. `inconclusive` means
# something could not be read, so an export may still exist (SKILL.md 3A).
FOUND = "found"
NO_PROJECT_RECORDS = "no_project_records"
NOT_FOUND = "not_found"
INCONCLUSIVE = "inconclusive"
SKIPPED = "skipped"

BILLING_EXPORT_PREFIXES = (
    "gcp_billing_export_v1_",
    "gcp_billing_export_resource_v1_",
)
_CAI_TABLE_RE = re.compile(
    r"//bigquery\.googleapis\.com/projects/([^/]+)/datasets/([^/]+)/tables/(.+)"
)

# `list_tables` defaults to 50 rows per request and pages within a dataset are
# sequential, so page size bounds the scan of a date-sharded dataset.
TABLE_LIST_PAGE_SIZE = 1000
DATASET_SCAN_WORKERS = 16
PROJECT_SCAN_WORKERS = 12
SCAN_PROGRESS_INTERVAL_SECONDS = 30.0
LARGE_PROJECT_DATASET_COUNT = 25
SLOW_SCAN_ADVISORY_SECONDS = 20.0

_SCOPE_SQL = (
    LOGGING_SCOPE_SQL.format(
        service_name="@service_name",
        service_id="@service_id",
        project_id="@project_id",
    )
    + f"\n  AND DATE(usage_start_time, '{INVOICE_TIMEZONE}') >= @window_start"
)

_NO_EXPORT_METADATA = {
    "status": "disabled",
    "table_name": None,
    "days_available": 0.0,
    "earliest_date": None,
    "latest_date": None,
    "currency": "USD",
    "distinct_months": 0,
}


@dataclasses.dataclass
class BillingResult:
  """Where costs came from. `costs` is None under list pricing."""

  costs: Optional[Dict[str, Any]]
  metadata: Dict[str, Any]
  chain: List[Dict[str, str]]

  @property
  def invoiced(self) -> bool:
    return self.costs is not None

  def summary(self) -> Dict[str, Any]:
    """The summary's `billing_metadata` block."""
    return {
        "invoiced": self.invoiced,
        **self.metadata,
        "fallback_chain": self.chain,
    }


@dataclasses.dataclass
class Scan:
  """Candidate tables from one search tier.

  `complete` is False when something could not be read, so an empty result
  does not prove there is no export.
  """

  tables: List[str]
  complete: bool = True
  detail: str = ""


def _export_rank(table: str) -> int:
  # The standard export is preferred over the resource-level one.
  return 0 if "gcp_billing_export_v1_" in table else 1


def _export_tables_in_dataset(
    bq_client: bigquery.Client,
    project: str,
    dataset_id: str,
    account_filter: Optional[str] = None,
) -> Optional[List[str]]:
  """Returns quoted export tables in one dataset, or None if unreadable."""
  try:
    return [
        f"`{project}.{dataset_id}.{t.table_id}`"
        for t in bq_client.list_tables(
            f"{project}.{dataset_id}", page_size=TABLE_LIST_PAGE_SIZE
        )
        if t.table_id.startswith(BILLING_EXPORT_PREFIXES)
        and (not account_filter or account_filter in t.table_id)
    ]
  except Exception:  # pylint: disable=broad-except
    return None


def scan_project_for_export_tables(
    bq_client: bigquery.Client,
    project: str,
    account_filter: Optional[str] = None,
    announce: bool = False,
) -> Scan:
  """Lists every dataset of `project` in parallel for export tables.

  BigQuery has no server-side table name filter, so the whole project is
  enumerated.

  Args:
    bq_client: BigQuery client.
    project: project to scan.
    account_filter: billing account ID export table names must contain.
    announce: print the cost of a slow scan (for the audited project).

  Returns:
    The export tables found, standard export first.
  """
  try:
    dataset_ids = [
        ds.dataset_id for ds in bq_client.list_datasets(project=project)
    ]
  except Exception as e:  # pylint: disable=broad-except
    return Scan([], False, f"Could not list the datasets of '{project}': {e}")
  if not dataset_ids:
    return Scan([], True, f"Project '{project}' has no datasets.")
  if announce and len(dataset_ids) >= LARGE_PROJECT_DATASET_COUNT:
    print(
        f"[BILLING DISCOVERY] Listing {len(dataset_ids)} datasets in"
        f" '{project}' to find the billing export. Passing --billing-table"
        " skips this search (~2s); --billing-mode=none skips it too."
    )

  started = time.monotonic()
  found: List[str] = []
  complete = True
  with concurrent.futures.ThreadPoolExecutor(
      max_workers=min(DATASET_SCAN_WORKERS, len(dataset_ids))
  ) as executor:
    for tables in executor.map(
        lambda ds: _export_tables_in_dataset(
            bq_client, project, ds, account_filter
        ),
        dataset_ids,
    ):
      if tables is None:
        complete = False
      else:
        found.extend(tables)
  elapsed = time.monotonic() - started
  if announce and elapsed >= SLOW_SCAN_ADVISORY_SECONDS:
    print(
        "[FINOPS ADVISORY - BILLING SYNC] Searching"
        f" {len(dataset_ids)} datasets in '{project}' took {elapsed:.0f}s"
        " because the export's location is unknown. Pass --billing-table next"
        " time, or --billing-mode=none if there is no export."
    )

  found.sort(key=_export_rank)
  if complete:
    return Scan(found, True, f"No billing export table in '{project}'.")
  return Scan(found, False, f"Some datasets of '{project}' could not be read.")


def _scan_projects_for_export(
    bq_client: bigquery.Client, projects: List[str], account_filter: str
) -> Tuple[Optional[str], int]:
  """Returns `(first export table found, unreadable count)` over `projects`."""
  # A None table proves no export only if `unreadable` is 0.
  started = last_progress = time.monotonic()
  unreadable = 0
  executor = concurrent.futures.ThreadPoolExecutor(
      max_workers=PROJECT_SCAN_WORKERS
  )
  try:
    futures = [
        executor.submit(
            scan_project_for_export_tables, bq_client, p, account_filter
        )
        for p in projects
    ]
    for done, future in enumerate(concurrent.futures.as_completed(futures), 1):
      scan = future.result()
      if scan.tables:
        return scan.tables[0], unreadable
      if not scan.complete:
        unreadable += 1
      now = time.monotonic()
      if now - last_progress >= SCAN_PROGRESS_INTERVAL_SECONDS:
        last_progress = now
        print(
            f"[BILLING DISCOVERY] Searched {done}/{len(futures)} projects on"
            f" the billing account ({now - started:.0f}s), no export yet."
        )
  finally:
    # A `with` block would wait for every running scan on an early return.
    executor.shutdown(wait=False, cancel_futures=True)
  return None, unreadable


def _discovery_credentials(bq_client: bigquery.Client) -> Any:
  # Without the ADC quota project, so these APIs need not be enabled on it
  # (SERVICE_DISABLED otherwise).
  creds = getattr(bq_client, "_credentials", None)
  if creds is None:
    creds, _ = google.auth.default()
  if hasattr(creds, "with_quota_project"):
    creds = creds.with_quota_project(None)
  return creds


def _org_scope(crm: Any, project_id: str) -> str:
  """Returns the project's organization, or the highest readable ancestor."""
  scope = f"projects/{project_id}"
  try:
    scope = crm.projects().get(name=scope).execute().get("parent") or scope
    while scope.startswith("folders/"):
      parent = crm.folders().get(name=scope).execute().get("parent")
      if not parent or parent == scope:
        break
      scope = parent
  except Exception as e:  # pylint: disable=broad-except
    print(f"Notice: Resource Manager scope resolution encountered: {e}")
  return scope


def _search_asset_inventory(
    build: Any, project_id: str, account_id: str
) -> Optional[str]:
  """One Cloud Asset Inventory search; often denied, hence only a fast path."""
  try:
    scope = _org_scope(build("cloudresourcemanager", "v3"), project_id)
    response = (
        build("cloudasset", "v1")
        .resources()
        .searchAll(
            scope=scope,
            query=" OR ".join(
                f"name:{prefix}{account_id}"
                for prefix in BILLING_EXPORT_PREFIXES
            ),
            assetTypes=["bigquery.googleapis.com/Table"],
        )
        .execute()
    )
  except Exception as e:  # pylint: disable=broad-except
    print(f"Notice: Cloud Asset Inventory search encountered: {e}")
    return None
  tables = []
  for item in response.get("results", []):
    match = _CAI_TABLE_RE.match(item.get("name", ""))
    if match and match.group(3).startswith(BILLING_EXPORT_PREFIXES):
      tables.append("`{}.{}.{}`".format(*match.groups()))
  return min(tables, key=_export_rank) if tables else None


def discover_account_export(
    bq_client: bigquery.Client, project_id: str
) -> Scan:
  """Finds the export anywhere on the billing account of `project_id`."""
  # Cloud Asset Inventory first, then every other project on the account.
  try:
    build = functools.partial(
        googleapiclient.discovery.build,
        credentials=_discovery_credentials(bq_client),
        cache_discovery=False,
        requestBuilder=attribution.discovery_request_builder(
            attribution.COLLECT_LOGGING_DATA
        ),
    )
    billing_svc = build("cloudbilling", "v1")
    info = (
        billing_svc.projects()
        .getBillingInfo(name=f"projects/{project_id}")
        .execute()
    )
  except Exception as e:  # pylint: disable=broad-except
    return Scan([], False, f"Could not read the project's billing account: {e}")
  account = info.get("billingAccountName")
  if not account or not info.get("billingEnabled", True):
    return Scan([], True, f"Billing is not enabled for '{project_id}'.")
  account_id = account.split("/")[-1].replace("-", "_")

  table = _search_asset_inventory(build, project_id, account_id)
  if table:
    return Scan([table])

  try:
    projects = []
    accounts = billing_svc.billingAccounts().projects()
    request = accounts.list(name=account, pageSize=100)
    while request is not None:
      response = request.execute()
      projects += [
          p["projectId"]
          for p in response.get("projectBillingInfo", [])
          if p.get("billingEnabled", True)
          and p.get("projectId") not in (None, project_id)
      ]
      request = accounts.list_next(request, response)
  except Exception as e:  # pylint: disable=broad-except
    return Scan([], False, f"Could not list the projects on '{account}': {e}")
  if not projects:
    return Scan([], True, "The billing account has no other projects.")

  print(
      f"[BILLING DISCOVERY] Searching all {len(projects)} projects on billing"
      f" account '{account}'. This runs until it finds an export or has"
      " checked every project, reporting progress every"
      f" {SCAN_PROGRESS_INTERVAL_SECONDS:.0f}s."
  )
  table, unreadable = _scan_projects_for_export(bq_client, projects, account_id)
  if table:
    return Scan([table])
  if unreadable:
    return Scan(
        [],
        False,
        f"Searched {len(projects)} projects on the billing account, but"
        f" {unreadable} could not be fully read, so an export these"
        " credentials cannot see may still exist.",
    )
  return Scan(
      [],
      True,
      f"Searched all {len(projects)} projects on the billing account without"
      " finding an export table.",
  )


def _candidates(
    bq_client: bigquery.Client,
    project_id: str,
    override_table: Optional[str],
    billing_project: Optional[str],
    billing_dataset: Optional[str],
) -> Iterator[Tuple[str, Scan]]:
  """Yields `(tier, scan)` in search order; later tiers run only if needed."""
  if override_table:
    yield "explicit_table", Scan([quote_table_ref(override_table)])
    return
  if billing_project or billing_dataset:
    target = billing_project or project_id
    if billing_dataset:
      tables = _export_tables_in_dataset(bq_client, target, billing_dataset)
      where = f"'{target}.{billing_dataset}'"
      yield "explicit_scope", Scan(
          tables or [],
          tables is not None,
          f"Could not list {where}."
          if tables is None
          else f"No billing export table in {where}.",
      )
    else:
      yield "explicit_scope", scan_project_for_export_tables(bq_client, target)
    return
  yield "local_project", scan_project_for_export_tables(
      bq_client, project_id, announce=True
  )
  yield "billing_account", discover_account_export(bq_client, project_id)


def _record(
    chain: List[Dict[str, str]],
    tier: str,
    status: str,
    detail: str,
    table: Optional[str] = None,
) -> None:
  step = {"tier": tier, "status": status, "detail": detail}
  if table:
    step["table"] = table
  chain.append(step)
  print(
      f"[BILLING DISCOVERY] {tier}: {status}"
      + (f" ({table})" if table else "")
      + f" - {detail}"
  )


def resolve_billing_source(
    bq_client: bigquery.Client,
    project_id: str,
    override_table: Optional[str] = None,
    billing_project: Optional[str] = None,
    billing_dataset: Optional[str] = None,
    analysis_months: int = DEFAULT_ANALYSIS_MONTHS,
    now: Optional[datetime.datetime] = None,
    billing_mode: str = MODE_SEARCH,
) -> BillingResult:
  """Reads costs from the first candidate table holding this project's rows.

  A named table or scope is the only candidate (whatever the mode); otherwise
  `search` tries this project, then the billing account.

  Args:
    bq_client: BigQuery client.
    project_id: audited project.
    override_table: export table named by the user.
    billing_project: project named by the user to search.
    billing_dataset: dataset named by the user to search.
    analysis_months: whole calendar months to read.
    now: current time; defaults to now (UTC).
    billing_mode: one of `BILLING_MODES`.

  Returns:
    The costs (None under list pricing), metadata and fallback chain.
  """
  now = now or datetime.datetime.now(datetime.timezone.utc)
  chain: List[Dict[str, str]] = []
  named = override_table or billing_project or billing_dataset
  if billing_mode == MODE_NONE and not override_table:
    _record(
        chain,
        "user_declared_no_export",
        SKIPPED,
        "Told there is no billing export, so nothing was searched.",
    )
    return BillingResult(None, dict(_NO_EXPORT_METADATA), chain)
  if billing_mode == MODE_EXPLICIT and not named:
    _record(
        chain,
        "explicit_scope",
        SKIPPED,
        "Explicit mode named no table, project or dataset to probe.",
    )
    return BillingResult(None, dict(_NO_EXPORT_METADATA), chain)

  for tier, scan in _candidates(
      bq_client, project_id, override_table, billing_project, billing_dataset
  ):
    for table in scan.tables:
      try:
        costs = query_logging_billing_costs(
            bq_client, table, project_id, analysis_months, now
        )
      except Exception as e:  # pylint: disable=broad-except
        _record(chain, tier, INCONCLUSIVE, f"Query failed: {e}", table)
        continue
      if costs["monthly_costs"]:
        _record(chain, tier, FOUND, "Reading costs from this table.", table)
        metadata = _metadata(costs, table, now, analysis_months)
        return BillingResult(costs, metadata, chain)
      _record(
          chain,
          tier,
          NO_PROJECT_RECORDS,
          f"Holds no Cloud Logging rows for '{project_id}'.",
          table,
      )
    if not scan.tables or not scan.complete:
      _record(
          chain,
          tier,
          NOT_FOUND if scan.complete else INCONCLUSIVE,
          scan.detail,
      )
  return BillingResult(None, dict(_NO_EXPORT_METADATA), chain)


def _window_start(
    now: datetime.datetime, analysis_months: int
) -> datetime.date:
  """First day of the oldest of `analysis_months` whole calendar months."""
  year, month = divmod(now.year * 12 + now.month - analysis_months, 12)
  return datetime.date(year, month + 1, 1)


def _metadata(
    costs: Dict[str, Any],
    table: str,
    now: datetime.datetime,
    analysis_months: int,
) -> Dict[str, Any]:
  """Describes the export's history from the rows the cost query returned."""
  dates = sorted(costs["daily_costs"])
  earliest = datetime.datetime.fromisoformat(dates[0]).replace(
      tzinfo=datetime.timezone.utc
  )
  # The query never reads before the window, so an export that reaches its
  # first day is as mature as this analysis can see.
  covers_window = dates[0] <= _window_start(now, analysis_months).isoformat()
  return {
      "status": "mature" if covers_window else "partial_window",
      "table_name": table,
      "days_available": round(
          max((now - earliest).total_seconds(), 0) / 86400, 1
      ),
      "earliest_date": dates[0],
      "latest_date": dates[-1],
      "currency": costs["currency"],
      "distinct_months": len(costs["monthly_costs"]),
  }


def query_logging_billing_costs(
    bq_client: bigquery.Client,
    table_name: str,
    project_id: str,
    analysis_months: int = DEFAULT_ANALYSIS_MONTHS,
    now: Optional[datetime.datetime] = None,
) -> Dict[str, Any]:
  """Returns monthly and daily Cloud Logging costs from the billing export.

  Dates are bucketed in Pacific time to match invoice months.

  Args:
    bq_client: BigQuery client.
    table_name: billing export table.
    project_id: project whose rows are read.
    analysis_months: whole calendar months to read.
    now: current time; defaults to now (UTC).

  Returns:
    Dict with `monthly_costs`, `daily_costs`, `daily_gib`, `daily_gib_by_sku`
    and `currency`. `monthly_costs` is empty when the table holds no rows for
    `project_id`.
  """
  now = now or datetime.datetime.now(datetime.timezone.utc)
  sql = f"""
  SELECT
    FORMAT_DATE('%Y-%m', DATE(usage_start_time, '{INVOICE_TIMEZONE}'))
      AS invoice_month,
    FORMAT_DATE('%Y-%m-%d', DATE(usage_start_time, '{INVOICE_TIMEZONE}'))
      AS usage_date,
    sku.description AS sku_description,
    currency,
    usage.pricing_unit AS pricing_unit,
    SUM(cost) AS raw_cost,
    SUM(IFNULL((SELECT SUM(c.amount) FROM UNNEST(credits) c), 0))
      AS total_credits,
    SUM(cost + IFNULL((SELECT SUM(c.amount) FROM UNNEST(credits) c), 0))
      AS net_cost,
    SUM(usage.amount_in_pricing_units) AS usage_amount
  FROM {quote_table_ref(table_name)}
  WHERE {_SCOPE_SQL}
  GROUP BY invoice_month, usage_date, sku_description, currency, pricing_unit
  ORDER BY usage_date ASC
  """
  job_config = bigquery.QueryJobConfig(
      query_parameters=[
          bigquery.ScalarQueryParameter(
              "service_name", "STRING", LOGGING_SERVICE_NAME
          ),
          bigquery.ScalarQueryParameter(
              "service_id", "STRING", LOGGING_SERVICE_ID
          ),
          bigquery.ScalarQueryParameter("project_id", "STRING", project_id),
          bigquery.ScalarQueryParameter(
              "window_start", "DATE", _window_start(now, analysis_months)
          ),
      ]
  )
  rows = list(bq_client.query(sql, job_config=job_config).result())

  monthly = collections.defaultdict(
      lambda: {
          "raw_cost": 0.0,
          "credits": 0.0,
          "net_cost": 0.0,
          "ingestion_gib": 0.0,
          "ingestion_raw_cost": 0.0,
          "ingestion_net_cost": 0.0,
          "sku_breakdown": collections.defaultdict(float),
          "ingestion_by_sku": collections.defaultdict(
              lambda: {"gib": 0.0, "raw_cost": 0.0, "net_cost": 0.0}
          ),
          "dates": set(),
      }
  )
  daily_costs: Dict[str, float] = collections.defaultdict(float)
  # Invoiced daily volume; preferred over `billing/bytes_ingested`, which can
  # silently under-report.
  daily_gib: Dict[str, float] = collections.defaultdict(float)
  daily_gib_by_sku: Dict[str, Dict[str, float]] = collections.defaultdict(
      lambda: collections.defaultdict(float)
  )
  for r in rows:
    day = r["usage_date"]
    sku = r["sku_description"] or INGESTION_SKU_NAME
    net = float(r["net_cost"] or 0.0)
    raw = float(r["raw_cost"] or 0.0)
    usage = float(r["usage_amount"] or 0.0)
    entry = monthly[r["invoice_month"]]
    entry["raw_cost"] += raw
    entry["credits"] += float(r["total_credits"] or 0.0)
    entry["net_cost"] += net
    entry["sku_breakdown"][sku] += net
    entry["dates"].add(day)
    daily_costs[day] += net
    # Ingestion only: retention rows (`gibibyte month`) would double-count.
    if (r["pricing_unit"] or "").strip().lower() == INGESTION_PRICING_UNIT:
      entry["ingestion_gib"] += usage
      entry["ingestion_raw_cost"] += raw
      entry["ingestion_net_cost"] += net
      daily_gib[day] += usage
      # SKUs differ in unit price and free tier, so price per SKU.
      sku_key = sku_of_description(sku)
      by_sku = entry["ingestion_by_sku"][sku_key]
      by_sku["gib"] += usage
      by_sku["raw_cost"] += raw
      by_sku["net_cost"] += net
      daily_gib_by_sku[sku_key][day] += usage

  return {
      "monthly_costs": {
          m: {
              "raw_cost_usd": round(v["raw_cost"], 2),
              "credits_usd": round(v["credits"], 2),
              "net_cost_usd": round(v["net_cost"], 2),
              "ingestion_gib": round(v["ingestion_gib"], 2),
              "ingestion_raw_cost_usd": round(v["ingestion_raw_cost"], 2),
              "ingestion_net_cost_usd": round(v["ingestion_net_cost"], 2),
              "billed_days": len(v["dates"]),
              "sku_breakdown": {
                  k: round(c, 2) for k, c in v["sku_breakdown"].items()
              },
              "ingestion_by_sku": {
                  k: {
                      "gib": round(s["gib"], 2),
                      "raw_cost_usd": round(s["raw_cost"], 2),
                      "net_cost_usd": round(s["net_cost"], 2),
                  }
                  for k, s in v["ingestion_by_sku"].items()
              },
          }
          for m, v in monthly.items()
      },
      "daily_costs": {d: round(v, 2) for d, v in daily_costs.items()},
      # 4dp so a tiny billed day doesn't round to zero.
      "daily_gib": {d: round(v, 4) for d, v in daily_gib.items()},
      "daily_gib_by_sku": {
          sku: {d: round(v, 4) for d, v in days.items()}
          for sku, days in daily_gib_by_sku.items()
      },
      "currency": (rows[0]["currency"] if rows else None) or "USD",
  }
build_report.py 14.8 KB
#!/usr/bin/env python3
"""Builds a deterministic, interactive Cloud Logging FinOps HTML report.

Fills `assets/report_template.html` with `logging_usage_summary.json` and an
optional agent-authored `insights/executive_summary.html`. Standard library
only.
"""

import argparse
import datetime
import html
import json
import os
import pathlib
import sys
from typing import Any, Dict, List, Optional, Tuple


def load_summary_data(summary_path: str) -> Dict[str, Any]:
  """Loads the logging usage summary JSON file."""
  with open(summary_path, "r", encoding="utf-8") as f:
    return json.load(f)


def load_template(template_path: Optional[str] = None) -> str:
  """Loads the HTML template from `template_path` or the skill's assets."""
  if template_path:
    candidate_paths = [pathlib.Path(template_path)]
  else:
    # Unresolved __file__ first: runfiles symlinks point at dirs without assets.
    candidate_paths = [
        pathlib.Path(__file__).parent.parent
        / "assets"
        / "report_template.html",
        pathlib.Path(__file__).resolve().parent.parent
        / "assets"
        / "report_template.html",
    ]
  for p in candidate_paths:
    if p.is_file():
      return p.read_text(encoding="utf-8")
  raise FileNotFoundError(
      "report_template.html not found at "
      + ", ".join(str(p) for p in candidate_paths)
  )


def load_executive_summary(insights_dir: Optional[str]) -> Optional[str]:
  """Returns the agent-authored `executive_summary.html`, if present."""
  if not insights_dir:
    return None
  path = os.path.join(insights_dir, "executive_summary.html")
  if not os.path.isfile(path):
    return None
  with open(path, "r", encoding="utf-8") as f:
    return f.read().strip() or None


def _money(value: Optional[float]) -> str:
  """Formats a dollar figure, distinguishing an unmeasured value from zero."""
  return "—" if value is None else f"${value:,.2f}"


def _volume(value: Optional[float]) -> str:
  """Formats a GiB figure, distinguishing an unmeasured value from zero."""
  return "—" if value is None else f"{value:,.1f} GiB"


def _finding(badge: str, badge_class: str, body: str) -> str:
  """Renders one executive-summary finding row."""
  return f"""    <div style="display: flex; gap: 14px; align-items: flex-start; background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 14px;">
      <span class="badge {badge_class}" style="flex-shrink: 0; margin-top: 1px;">{badge}</span>
      <div style="font-size: 13px; line-height: 1.5; color: var(--text);">
        {body}
      </div>
    </div>"""


def _recoverable_spend_finding(summary_data: Dict[str, Any]) -> str:
  """Renders the measured recoverable-spend floor from `extraneous_spend`."""
  waste = summary_data["extraneous_spend"]

  # Never substitute another savings figure for an unmeasured floor.
  if waste["status"] != "ok":
    return _finding(
        "RECOVERABLE SPEND",
        "badge-warning",
        "No recoverable-spend floor could be measured &mdash;"
        f" {html.escape(waste['reason'])} No savings figure is shown in place"
        " of one.",
    )

  headline = waste["headline"]
  counted = sum(
      1 for a in summary_data["reduction_actions"]["actions"] if a["counted"]
  )
  # Without the inventory, "no lever found" could just mean "not checked".
  unchecked = ""
  if waste["inventory_unavailable"]:
    unchecked = (
        " Sink, exclusion and flow-log levers could not be checked (Log Router"
        " or VPC inventory unreadable)."
    )
  usd = headline["monthly_savings_usd"]
  gib = headline["monthly_savings_gib"]
  pct = headline["pct_of_billable_spend"]
  uncounted_pct = waste["uncounted_total_pct"]

  if not counted or not usd:
    body = (
        "No cleanup lever cleared the evidence bar for counted savings, so the"
        " recoverable floor for this project is not quantified."
    )
    if uncounted_pct > 0:
      body += (
          ' Levers worth <strong style="color: #c084fc;">'
          f"{uncounted_pct:.1f}%</strong> of billable spend were found but"
          " require owner or compliance judgement, so they are surfaced in the"
          " <em>Extraneous Log Spend</em> card above rather than counted."
      )
    return _finding("RECOVERABLE SPEND", "badge-primary", body + unchecked)

  body = (
      'At least <strong style="color: #34d399;">'
      f"{pct:.1f}% of billable spend</strong> is recoverable &mdash;"
      f' <strong style="color: #34d399;">{_money(usd)}/mo</strong>'
      f" ({_volume(gib)}/mo) across {counted} measured"
      f" lever{'s' if counted != 1 else ''}. This is a floor, not an estimate:"
      " it counts only levers measured against billing metrics whose cleanup"
      " preserves a signal this project has shown it wants. Per-lever evidence"
      " is in the <em>Extraneous Log Spend</em> card above."
  )
  if uncounted_pct > 0:
    body += (
        f' A further <strong style="color: #c084fc;">{uncounted_pct:.1f}%'
        "</strong> sits in levers that need owner or compliance judgement"
        " and is deliberately excluded from this figure."
    )
  if headline["exceeds_sanity_ceiling"]:
    body += (
        ' <strong style="color: #fbbf24;">Flagged for manual review:</strong>'
        " this share is high enough that the underlying measurement should be"
        " confirmed before it is acted on."
    )
  return _finding("RECOVERABLE SPEND", "badge-success", body + unchecked)


def _generate_default_executive_summary(summary_data: Dict[str, Any]) -> str:
  """Generates a default FinOps executive summary card from summary data."""
  is_invoiced = summary_data["billing_metadata"]["invoiced"]

  # Only whole months are comparable.
  monthly_aggs = summary_data["monthly_aggregations"]
  complete = sorted(m for m, d in monthly_aggs.items() if not d["is_partial"])
  if len(complete) >= 2:
    first, last = monthly_aggs[complete[0]], monthly_aggs[complete[-1]]
    span_html = (
        f"Complete billing months {complete[0]} through {complete[-1]} moved"
        f' from <strong style="color: var(--text);">'
        f'{_money(first["net_cost_usd"])}'
        f' ({_volume(first["total_gib"])})</strong> to'
        f' <strong style="color: #fbbf24;">{_money(last["net_cost_usd"])}'
        f' ({_volume(last["total_gib"])})</strong>.'
    )
  elif complete:
    only = monthly_aggs[complete[0]]
    span_html = (
        f"One complete billing month is available ({complete[0]}):"
        f' <strong style="color: var(--text);">'
        f'{_money(only["net_cost_usd"])}'
        f' ({_volume(only["total_gib"])})</strong>.'
    )
  else:
    span_html = (
        "No complete billing month has been observed yet, so no"
        " month-over-month comparison is shown."
    )

  trailing_30d = summary_data["trailing_30d_summary"]
  # Label by days actually observed (may be < 30) and by their source.
  days_observed = trailing_30d["days_observed"]
  invoiced = trailing_30d["volume_basis"] == "invoiced_daily_usage"
  day_word = "invoiced day" if invoiced else "measured day"
  window_label = (
      f"the last {days_observed} {day_word}{'s' if days_observed != 1 else ''}"
      if days_observed
      else "the trailing window"
  )
  span_html += (
      f" Ingestion over {window_label} is"
      ' <strong style="color: var(--text);">'
      f'{_volume(trailing_30d["total_gib"])}</strong>, a projected run rate'
      ' of <strong style="color: #fbbf24;">'
      f'{_money(trailing_30d["projected_monthly_cost_usd"])}/mo'
      f' ({_volume(trailing_30d["monthly_run_rate_gib"])}/mo)</strong>.'
  )

  if is_invoiced:
    months = sum(
        1
        for d in monthly_aggs.values()
        if d["data_source"] == "actual_bq_billing"
    )
    pricing_note = (
        "Actual invoiced BigQuery billing export data, reconciled across"
        f" {months} billing month{'s' if months != 1 else ''}."
    )
  else:
    pricing_note = (
        "Estimated from per-SKU list prices; no billing export was read."
    )
  span_html += (
      '<div style="font-size: 12px; color: var(--text-muted); margin-top:'
      f' 4px;">Note: {html.escape(pricing_note)}</div>'
  )

  findings = [_finding("SPEND &amp; INGESTION", "badge-warning", span_html)]

  # State the measured combined share rather than a qualitative claim.
  named = [
      s for s in trailing_30d["top_services"][:3] if not s.get("is_remainder")
  ]
  if named:
    listed = ", ".join(
        f'<code class="code-pill">{html.escape(s["service"])}</code>'
        f' (<strong style="color: #60a5fa;">{s["pct_of_total"]:.1f}%'
        "</strong>)"
        for s in named
    )
    combined = sum(s["pct_of_total"] for s in named)
    findings.append(
        _finding(
            "PRIMARY DRIVERS",
            "badge-primary",
            f"Ingestion is led by {listed} &mdash;"
            f' <strong style="color: #60a5fa;">{combined:.1f}%</strong> of'
            f" volume over {window_label} between them.",
        )
    )

  # Only the measured floor is stated; action savings overlap and don't sum.
  findings.append(_recoverable_spend_finding(summary_data))

  findings_html = "\n\n".join(findings)
  return f"""<div class="card" style="gap: 16px;">
  <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border); padding-bottom: 12px;">
    <h2 class="section-title">Executive Summary &amp; Key Findings</h2>
    <span class="badge badge-primary">FinOps Assessment</span>
  </div>

  <div style="display: flex; flex-direction: column; gap: 12px;">
{findings_html}
  </div>
</div>"""


# The summary fields report_template.html reads: a top-level key maps to None
# (embed the whole block) or to the only sub-keys the page reads. Everything
# else stays on disk for the agent, so new fields never leak into the page.
PAGE_FIELDS: Dict[str, Optional[Tuple[str, ...]]] = {
    "analytics_metadata": ("status",),
    "billing_metadata": None,
    "cost_projection": None,
    "daily_services": None,
    "extraneous_spend": None,
    "latest_complete_month": None,
    "monthly_aggregations": None,
    "pricing": None,
    "provenance": None,
    "reduction_actions": None,
    "severity_summary": None,
    "telemetry_integrity": None,
    "trailing_30d_summary": None,
    "weekly_aggregations": None,
}


def _browser_payload(summary_data: Dict[str, Any]) -> Dict[str, Any]:
  """Returns the `PAGE_FIELDS` subset of the summary, without claim ledgers."""
  payload: Dict[str, Any] = {}
  for key, sub_keys in PAGE_FIELDS.items():
    value = summary_data[key]
    payload[key] = (
        value if sub_keys is None else {k: value[k] for k in sub_keys}
    )
  # Per-stream claim ledgers are for Prove It and the agent, not the page.
  payload["reduction_actions"] = {
      **payload["reduction_actions"],
      "actions": [
          {k: v for k, v in a.items() if k != "claims"}
          for a in payload["reduction_actions"]["actions"]
      ],
  }
  return payload


def populate_template(
    template_content: str,
    summary_data: Dict[str, Any],
    executive_summary: Optional[str] = None,
    report_context: Optional[Dict[str, str]] = None,
) -> str:
  """Renders the HTML report.

  Args:
    template_content: The report_template.html text.
    summary_data: Parsed logging_usage_summary.json.
    executive_summary: Agent-authored executive summary HTML; a default one is
      generated from the summary when absent.
    report_context: Where the summary, `verify_claim.py` and the Python that can
      run it live on disk, so the Prove It drawer can print a ready-to-run
      re-check command.

  Returns:
    The rendered HTML.
  """
  snapshot_time = datetime.datetime.fromisoformat(
      summary_data["last_updated"]
  ).strftime("%Y-%m-%d %H:%M:%S UTC")

  payload = _browser_payload(summary_data)
  if report_context:
    payload["report_context"] = dict(report_context)
  # Escaped so a string in the data cannot close the <script> element.
  json_data_str = json.dumps(payload, separators=(",", ":")).replace(
      "</", "<\\/"
  )

  rendered = template_content
  rendered = rendered.replace(
      "{{PROJECT_ID}}", html.escape(summary_data["project_id"])
  )
  rendered = rendered.replace("{{SNAPSHOT_TIME}}", snapshot_time)
  rendered = rendered.replace("{{FINOPS_JSON_DATA}}", json_data_str)
  return rendered.replace(
      "<!-- SLOT:EXECUTIVE_SUMMARY -->",
      executive_summary or _generate_default_executive_summary(summary_data),
  )


def compose_report(
    summary_path: str,
    output_path: str,
    insights_dir: Optional[str] = None,
    template_path: Optional[str] = None,
) -> str:
  """Loads the summary and template, renders the report and writes it."""
  summary_data = load_summary_data(summary_path)
  template_content = load_template(template_path)
  html_output = populate_template(
      template_content,
      summary_data,
      load_executive_summary(insights_dir),
      report_context={
          "summary_path": os.path.abspath(summary_path),
          "verify_script": os.path.join(
              os.path.dirname(os.path.abspath(__file__)), "verify_claim.py"
          ),
          # This interpreter has the google-cloud-* deps verify_claim needs.
          "python": sys.executable,
      },
  )

  out_dir = os.path.dirname(output_path)
  if out_dir:
    os.makedirs(out_dir, exist_ok=True)

  with open(output_path, "w", encoding="utf-8") as f:
    f.write(html_output)

  return output_path


def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
  """Parses command-line arguments."""
  parser = argparse.ArgumentParser(
      description=(
          "Deterministically build a Cloud Logging FinOps HTML report from"
          " the collector's summary JSON."
      )
  )
  parser.add_argument(
      "--summary",
      "-s",
      default="logging_usage_summary.json",
      help=(
          "Path to logging_usage_summary.json (default:"
          " logging_usage_summary.json)"
      ),
  )
  parser.add_argument(
      "--insights-dir",
      "-i",
      default="insights",
      help=(
          "Directory holding an agent-authored executive_summary.html"
          " (default: insights)"
      ),
  )
  parser.add_argument(
      "--output",
      "-o",
      default="log_usage_report.html",
      help=(
          "Output path for compiled HTML report (default:"
          " log_usage_report.html)"
      ),
  )
  parser.add_argument(
      "--template",
      "-t",
      default=None,
      help="Path to custom report_template.html (optional)",
  )
  return parser.parse_args(argv)


def main(argv: Optional[List[str]] = None) -> None:
  args = parse_args(argv)
  try:
    out_file = compose_report(
        summary_path=args.summary,
        output_path=args.output,
        insights_dir=args.insights_dir,
        template_path=args.template,
    )
    print(f"Successfully generated FinOps report: {out_file}")
  except (OSError, ValueError, KeyError) as e:
    print(f"Error generating FinOps report: {e}", file=sys.stderr)
    sys.exit(1)


if __name__ == "__main__":
  main()
collect_logging_data.py 19.9 KB
"""Collects GCP logging volume and cost data.

Sources: Cloud Monitoring, Log Analytics, and the BigQuery billing export.
"""

import collections
from collections.abc import Sequence
import concurrent.futures
import datetime
import os
from typing import Any, Dict, List, Optional

from absl import app
from absl import flags
from actions import merge_actions
from aggregations import get_daily_services
from aggregations import get_mom_patterns
from aggregations import get_monthly_aggregations
from aggregations import get_severity_summary
from aggregations import get_trailing_30d_summary
from aggregations import get_weekly_aggregations
from aggregations import invoiced_window_gib
from aggregations import latest_complete_month
from aggregations import merge_data
from aggregations import project_month
from aggregations import top_driver
from aggregations import window_sums
from analytics import detect_log_analytics_buckets
from analytics import fetch_logging_api_samples
from analytics import probe_log_analytics_data
from analytics import query_log_analytics_breakdown
import attribution
import billing
from billing import resolve_billing_source
from constants import DEFAULT_ANALYSIS_MONTHS
from constants import DEFAULT_LOCATION
from constants import DEFAULT_SAMPLE_DAYS
from constants import DEFAULT_TELEMETRY_LOOKBACK_DAYS
from constants import MONITORING_RETENTION_DAYS
from constants import write_json
from exclusion_rules import generate_exclusion_candidates
from google.cloud import bigquery
from google.cloud import logging_v2
from google.cloud import monitoring_v3
from google.cloud.logging_v2.services import config_service_v2
from inventory import authed_session
from inventory import fetch_flow_log_configs
from inventory import fetch_log_router_inventory
from inventory import resolve_log_read_scope
from monitoring import get_query_interval
from monitoring import parse_billing_results
from monitoring import parse_severity_results
from monitoring import parse_stream_results
from monitoring import query_log_volume
from monitoring import query_severity_volume
from monitoring import query_stream_volume
from output import print_advisory
from output import write_monthly_details
from output import write_service_details
import perf
from pricing import build_price_book
from provenance import build_provenance
import telemetry_integrity
from waste import compute_extraneous_spend

ConfigServiceV2Client = config_service_v2.ConfigServiceV2Client

FLAGS = flags.FLAGS
if "project-id" not in FLAGS:
  flags.DEFINE_string("project-id", None, "GCP Project ID to query.")
if "output" not in FLAGS:
  flags.DEFINE_string(
      "output",
      "logging_usage_summary.json",
      "Output JSON file path for summary index.",
  )
if "billing-project" not in FLAGS:
  flags.DEFINE_string(
      "billing-project",
      None,
      "Optional GCP Project ID where BigQuery billing export resides.",
  )
if "billing-dataset" not in FLAGS:
  flags.DEFINE_string(
      "billing-dataset",
      None,
      "Optional BigQuery dataset containing billing export tables.",
  )
if "billing-table" not in FLAGS:
  flags.DEFINE_string(
      "billing-table",
      None,
      "Optional explicit BigQuery billing export table name (e.g."
      " `proj.ds.gcp_billing_export_v1_XXXX`).",
  )
if "billing-mode" not in FLAGS:
  flags.DEFINE_enum(
      "billing-mode",
      billing.MODE_SEARCH,
      list(billing.BILLING_MODES),
      "What is already known about where the Cloud Billing BigQuery export"
      " lives. 'explicit' probes only what --billing-table/-project/-dataset"
      " names (~2s, invoiced costs); 'none' skips discovery entirely because"
      " the caller has confirmed there is no export (instant, estimated"
      " costs); 'search' (default) looks for it -- this project first, then"
      " every project on the billing account.",
  )


def collect_data(
    monitoring_client: monitoring_v3.MetricServiceClient,
    project_id: str,
    output_path: str,
    now: datetime.datetime,
    config_client: Optional[ConfigServiceV2Client] = None,
    bq_client: Optional[bigquery.Client] = None,
    sample_days: int = DEFAULT_SAMPLE_DAYS,
    location: str = DEFAULT_LOCATION,
    billing_project: Optional[str] = None,
    billing_dataset: Optional[str] = None,
    billing_table: Optional[str] = None,
    analysis_months: int = DEFAULT_ANALYSIS_MONTHS,
    logging_client: Optional[Any] = None,
    billing_mode: str = billing.MODE_SEARCH,
    http_session: Optional[Any] = None,
) -> Dict[str, Any]:
  """Collects all sources, writes the summary JSON, and returns it."""
  timer = perf.StageTimer()
  client_info = attribution.client_info(attribution.COLLECT_LOGGING_DATA)
  if config_client is None:
    config_client = ConfigServiceV2Client(client_info=client_info)
  if bq_client is None:
    bq_client = bigquery.Client(project=project_id, client_info=client_info)
  if logging_client is None:
    logging_client = logging_v2.Client(
        project=project_id, client_info=client_info
    )
  # Inventory checks that could not run are disclosed, never read as "none".
  inventory_unavailable: List[str] = []
  if http_session is None:
    try:
      http_session = authed_session()
    except Exception as e:  # pylint: disable=broad-except
      print(f"Notice: unable to build an authorized session: {e}")
      inventory_unavailable.append(f"authorized session: {e}")

  def _run_pillar_analytics():
    with timer.stage("log_analytics_buckets"):
      detected_buckets = detect_log_analytics_buckets(
          config_client, project_id, location
      )
    analytics_enabled_buckets = [
        b for b in detected_buckets if b["analytics_enabled"]
    ]
    is_analytics_enabled = len(analytics_enabled_buckets) > 0

    probe_info = {
        "status": "disabled",
        "days_available": 0.0,
        "table_name": None,
    }
    granular_raw = None
    if is_analytics_enabled:
      active = analytics_enabled_buckets[0]
      active_loc = active["location"]
      with timer.stage("log_analytics_probe"):
        probe_info = probe_log_analytics_data(
            bq_client,
            project_id,
            location=active_loc,
            bucket_id=active["bucket_id"],
            sample_days=sample_days,
            now=now,
            linked_dataset=active["linked_dataset"],
        )
      if probe_info["status"] in ("partial_window", "mature"):
        with timer.stage("log_analytics_breakdown"):
          granular_raw = query_log_analytics_breakdown(
              bq_client,
              probe_info["table_name"],
              sample_days=sample_days,
              location=active_loc,
          )
    return detected_buckets, is_analytics_enabled, probe_info, granular_raw

  def _run_pillar_billing():
    return resolve_billing_source(
        bq_client=bq_client,
        project_id=project_id,
        override_table=billing_table,
        billing_project=billing_project,
        billing_dataset=billing_dataset,
        analysis_months=analysis_months,
        now=now,
        billing_mode=billing_mode,
    )

  def _run_billing_chain():
    """Resolves billing, then the billed-volume series whose window needs it."""
    with timer.stage("billing_discovery"):
      billing_result = _run_pillar_billing()
    lookback = (
        MONITORING_RETENTION_DAYS
        if billing_result.invoiced
        else DEFAULT_TELEMETRY_LOOKBACK_DAYS
    )
    with timer.stage("gcm_billed_bytes"):
      results = query_log_volume(
          monitoring_client, project_id, get_query_interval(now, lookback)
      )
    return billing_result, parse_billing_results(results)

  def _run_stream_volume():
    """Fetches `byte_count` once for all consumers."""
    with timer.stage("gcm_byte_count_streams"):
      return query_stream_volume(
          monitoring_client,
          project_id,
          now=now,
          days=int(max(sample_days, DEFAULT_TELEMETRY_LOOKBACK_DAYS)),
      )

  def _run_router_inventory():
    if http_session is None:
      return {"sinks": [], "exclusions": []}, []
    with timer.stage("log_router_inventory"):
      return fetch_log_router_inventory(http_session, project_id)

  def _run_flow_log_configs():
    if http_session is None:
      return [], []
    with timer.stage("flow_log_configs"):
      return fetch_flow_log_configs(http_session, project_id)

  def _run_log_read_scope():
    with timer.stage("log_read_scope"):
      return resolve_log_read_scope(http_session, project_id)

  # These groups are independent, so they run concurrently.
  with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:
    fut_analytics = executor.submit(_run_pillar_analytics)
    fut_billing = executor.submit(_run_billing_chain)
    fut_streams = executor.submit(_run_stream_volume)
    fut_router = executor.submit(_run_router_inventory)
    fut_flow_logs = executor.submit(_run_flow_log_configs)
    fut_read_scope = executor.submit(_run_log_read_scope)

    detected_buckets, is_analytics_enabled, probe_info, granular_raw = (
        fut_analytics.result()
    )
    billing_result, parsed_billing = fut_billing.result()
    stream_series = fut_streams.result()
    router_inventory, router_unavailable = fut_router.result()
    flow_log_configs, flow_unavailable = fut_flow_logs.result()
    read_scope = fut_read_scope.result()
  inventory_unavailable += router_unavailable + flow_unavailable

  parsed_streams = parse_stream_results(stream_series.series)
  if stream_series.missing_windows:
    print(
        "Notice: byte_count is incomplete for"
        f" {len(stream_series.missing_windows)} window(s):"
        f" {', '.join(stream_series.missing_windows)}"
    )

  # `billing/bytes_ingested` can silently under-report billed volume. Suspect
  # days are disclosed, never dropped (it is the only per-service split). The
  # invoice is the control when present; else `byte_count` (relative only).
  billed_daily = telemetry_integrity.daily_totals(parsed_billing)
  billing_costs = billing_result.costs or {}
  invoiced_daily_gib = billing_costs.get("daily_gib")
  if invoiced_daily_gib:
    telemetry_verdict = telemetry_integrity.assess_against_invoice(
        billed_daily=billed_daily,
        invoiced_daily_gib=invoiced_daily_gib,
        now=now,
    )
  else:
    # Summing the per-stream series equals the ungrouped daily total.
    telemetry_verdict = telemetry_integrity.assess(
        billed_daily=billed_daily,
        received_daily=telemetry_integrity.daily_totals(parsed_streams),
    )
  if telemetry_verdict["compromised_days"]:
    print(
        "[TELEMETRY INTEGRITY]"
        f" {len(telemetry_verdict['compromised_days'])} day(s) of"
        " billed-volume telemetry under-report the volume that was billed:"
        f" {', '.join(telemetry_verdict['compromised_days'])}"
    )

  billed_by_service = window_sums(parsed_billing, now, sample_days)
  top_services = sorted(
      billed_by_service, key=billed_by_service.get, reverse=True
  )[:5]
  analytics_status = probe_info["status"]
  granular_analytics: Optional[Dict[str, Any]] = None
  severity_missing: List[str] = []

  if analytics_status == "mature":
    parsed_severity = granular_raw["severity_history"]
  else:
    with timer.stage("gcm_severity_volume"):
      severity_series = query_severity_volume(
          monitoring_client, project_id, top_services, now, days=sample_days
      )
    severity_missing = severity_series.missing_windows
    parsed_severity = parse_severity_results(severity_series.series)

  # Extract SQL samples if available, then fetch missing via Logging API
  samples_by_service: Dict[str, Dict[str, List[Dict[str, Any]]]] = (
      collections.defaultdict(lambda: collections.defaultdict(list))
  )
  if granular_raw is not None:
    for srv_name, sevs in granular_raw["samples_by_service"].items():
      for sev_name, items in sevs.items():
        samples_by_service[srv_name][sev_name].extend(items)

  with timer.stage("logging_api_samples"):
    sample_errors = fetch_logging_api_samples(
        logging_client=logging_client,
        project_id=project_id,
        top_services=top_services,
        parsed_severity=parsed_severity,
        samples_by_service=samples_by_service,
        now=now,
        lookback_days=sample_days,
        read_scope=read_scope,
    )
  samples_dict = {srv: dict(sevs) for srv, sevs in samples_by_service.items()}

  merged_data = merge_data(parsed_billing, parsed_severity)
  base_dir = os.path.dirname(os.path.abspath(output_path))
  write_monthly_details(
      parsed_billing, os.path.join(base_dir, "monthly_details"), project_id
  )
  write_service_details(
      merged_data,
      os.path.join(base_dir, "service_details"),
      project_id,
      samples_by_service=samples_dict,
  )

  # The invoice sets the run rate; the metric supplies the service split.
  trailing_30d = get_trailing_30d_summary(
      parsed_billing=parsed_billing,
      now=now,
      invoiced_daily_gib=billing_costs.get("daily_gib"),
  )
  monthly_run_rate_gib = trailing_30d["monthly_run_rate_gib"]

  # Every dollar in the summary is priced from this book: per SKU, with the
  # 50 GiB free tier on Log Storage only.
  stream_sums = window_sums(parsed_streams, now, sample_days)
  price_book = build_price_book(
      baseline_gib=monthly_run_rate_gib,
      now=now,
      window_start=trailing_30d["window_start"],
      monthly_costs=billing_costs.get("monthly_costs"),
      daily_gib_by_sku=billing_costs.get("daily_gib_by_sku"),
      bytes_by_stream=stream_sums,
  )
  trailing_30d["projected_monthly_cost_usd"] = price_book.baseline_cost
  trailing_30d["projected_annual_cost_usd"] = round(
      price_book.baseline_cost * 12.0, 2
  )
  # Price each service on its window GiB scaled to the monthly run rate.
  window_gib = trailing_30d["total_gib"]
  to_monthly = monthly_run_rate_gib / window_gib if window_gib > 0 else 0.0
  for entry in trailing_30d["top_services"]:
    if not entry.get("is_remainder"):
      entry["cost_usd"] = price_book.service_cost(
          entry["service"], entry["gib"] * to_monthly
      )
  trailing_30d["top_driver"] = top_driver(trailing_30d["top_services"])

  monthly_aggs = get_monthly_aggregations(
      billing_data=parsed_billing,
      price_book=price_book,
      billing_costs=billing_costs,
      now=now,
  )
  invoiced_months = sorted(
      m
      for m, entry in monthly_aggs.items()
      if entry["data_source"] == "actual_bq_billing"
  )
  # Named from the months actually retrieved, not the months requested.
  reporting_mode = (
      f"billing_invoiced_{len(invoiced_months)}mo"
      if invoiced_months
      else "telemetry_trailing_30d"
  )

  weekly_aggs = get_weekly_aggregations(
      parsed_billing=parsed_billing, now=now, price_book=price_book
  )
  mom_trends = get_mom_patterns(monthly_aggs)
  cost_projection = project_month(
      now=now,
      price_book=price_book,
      parsed_billing=parsed_billing,
      invoiced_daily_gib_by_sku=billing_costs.get("daily_gib_by_sku"),
  )

  # Present only when the Log Analytics breakdown ran.
  if granular_raw is not None:
    granular_analytics = {
        "sample_period_days": probe_info["days_available"],
        "sample_start": probe_info["earliest_log"],
        "sample_end": probe_info["latest_log"],
        "top_log_names": granular_raw["top_log_names"],
        "top_signatures": granular_raw["top_signatures"],
        # Gross run rate: the book subtracts the free tier itself.
        "exclusion_candidates": generate_exclusion_candidates(
            granular_raw["top_signatures"],
            price_book,
            project_id=project_id,
            total_entries=probe_info["total_entries"],
            total_sample_bytes=granular_raw["total_payload_bytes"],
            monthly_run_rate_gib=monthly_run_rate_gib,
            sample_days=probe_info["days_available"],
        ),
    }

  severity_summary = get_severity_summary(
      parsed_severity,
      now,
      days=sample_days,
      samples_by_service=samples_dict,
      severity_source=(
          "log_analytics"
          if analytics_status == "mature"
          else "cloud_monitoring"
      ),
  )
  # Without this, a truncated fetch looks like a real drop in ERROR volume.
  severity_summary["missing_windows"] = severity_missing
  severity_summary["sample_errors"] = sample_errors

  daily_services = get_daily_services(parsed_billing, now, days=sample_days)

  # Uses Cloud Monitoring volume and router/flow-log inventory, never payload
  # byte sums (which overstate billed volume).
  extraneous_spend, lever_actions = compute_extraneous_spend(
      billed_by_service=billed_by_service,
      byte_count_by_stream=stream_sums,
      window_days=float(sample_days),
      monthly_gib=monthly_run_rate_gib,
      price_book=price_book,
      project_id=project_id,
      sinks=router_inventory["sinks"],
      exclusions=router_inventory["exclusions"],
      buckets=detected_buckets,
      flow_log_configs=flow_log_configs,
      # Invoiced basis, matching the run rate it is divided by.
      billed_window_gib=invoiced_window_gib(
          billing_costs.get("daily_gib"),
          now,
          float(sample_days),
      ),
  )
  extraneous_spend["inventory_unavailable"] = inventory_unavailable

  # Merges levers and exclusion rules on the same stream into one action.
  reduction_actions = merge_actions(
      lever_actions,
      granular_analytics["exclusion_candidates"] if granular_analytics else [],
      price_book,
  )

  index_content = {
      "project_id": project_id,
      "last_updated": now.isoformat(),
      "reporting_mode": reporting_mode,
      "trailing_30d_summary": trailing_30d,
      # How every dollar was priced; read by the report and Prove It.
      "pricing": price_book.to_dict(),
      "weekly_aggregations": weekly_aggs,
      "analytics_metadata": {
          "enabled": is_analytics_enabled,
          "status": analytics_status,
          "days_available": probe_info["days_available"],
          # The `_AllLogs` view the breakdown measured; Prove It queries it.
          "table_name": probe_info["table_name"],
          "buckets": detected_buckets,
          # Where Logging API samples were read; explains empty samples.
          "log_read_scope": read_scope,
      },
      "billing_metadata": billing_result.summary(),
      "monthly_aggregations": monthly_aggs,
      "latest_complete_month": latest_complete_month(monthly_aggs),
      "mom_patterns": mom_trends,
      "cost_projection": cost_projection,
      "severity_summary": severity_summary,
      "daily_services": daily_services,
      "extraneous_spend": extraneous_spend,
      "reduction_actions": reduction_actions,
      "telemetry_integrity": telemetry_verdict,
      # Per-stage timings.
      "collection_profile": timer.profile(),
  }

  if granular_analytics is not None:
    index_content["granular_analytics"] = granular_analytics

  # Built last from the finished summary; source of truth for "Prove It" and
  # `verify_claim.py`.
  index_content["provenance"] = build_provenance(index_content)

  write_json(output_path, index_content)
  print(timer.render())

  print_advisory(index_content, output_path)

  return index_content


def main(argv: Sequence[str]) -> None:
  if len(argv) > 1:
    raise app.UsageError("Too many command-line arguments.")
  project_id = FLAGS["project-id"].value
  if not project_id:
    raise app.UsageError("Flag --project-id is required.")
  if FLAGS["billing-mode"].value == billing.MODE_EXPLICIT and not (
      FLAGS["billing-table"].value
      or FLAGS["billing-project"].value
      or FLAGS["billing-dataset"].value
  ):
    raise app.UsageError(
        "--billing-mode=explicit needs --billing-table, --billing-project or"
        " --billing-dataset."
    )

  # Optional clients are built by `collect_data`.
  collect_data(
      monitoring_client=monitoring_v3.MetricServiceClient(
          client_info=attribution.client_info(attribution.COLLECT_LOGGING_DATA)
      ),
      project_id=project_id,
      output_path=FLAGS["output"].value,
      now=datetime.datetime.now(datetime.timezone.utc),
      billing_project=FLAGS["billing-project"].value,
      billing_dataset=FLAGS["billing-dataset"].value,
      billing_table=FLAGS["billing-table"].value,
      billing_mode=FLAGS["billing-mode"].value,
  )


if __name__ == "__main__":
  app.run(main)
constants.py 9.1 KB
"""Domain constants and shared utility helpers for Cloud Logging FinOps."""

import json
import os
from typing import Any

# ==============================================================================
# Domain Constants
# ==============================================================================

# Cloud Logging is priced in gibibytes, not gigabytes (a 7.4% difference).
BYTES_PER_GIB = 1024.0**3
LIST_PRICE_PER_GIB = 0.50
FREE_TIER_GIB_PER_MONTH = 50.0

DEFAULT_SAMPLE_DAYS = 14
DEFAULT_ANALYSIS_MONTHS = 6
DEFAULT_TELEMETRY_LOOKBACK_DAYS = 30
DEFAULT_BUCKET_ID = "_Default"
DEFAULT_LOCATION = "global"

# Cloud Monitoring keeps `logging.googleapis.com/*` for 42 days and silently
# returns less when asked for more, so windows must be clamped.
MONITORING_RETENTION_DAYS = 42

DAYS_PER_MONTH = 30.0

LOGGING_SERVICE_NAME = "Cloud Logging"
LOGGING_SERVICE_ID = "5490-F7B7-8DF6"
INGESTION_SKU_NAME = "Cloud Logging - Log Volume"
ESTIMATED_SKU_NAME = f"{INGESTION_SKU_NAME} (Estimated)"

# Ingestion is billed per `gibibyte`, retention per `gibibyte month`, under the
# same service id; only the former is ingestion volume.
INGESTION_PRICING_UNIT = "gibibyte"

# Cloud Billing closes days and months on US/Pacific time, not UTC.
INVOICE_TIMEZONE = "America/Los_Angeles"

# One project's Cloud Logging rows in a billing export. The collector binds the
# placeholders as query parameters; Prove It inlines literals so the SQL it
# shows can be pasted as is.
LOGGING_SCOPE_SQL = (
    "(service.description = {service_name} OR service.id = {service_id})\n"
    "  AND project.id = {project_id}"
)


def bare_table_ref(table_ref: str) -> str:
  """Returns `project.dataset.table` without surrounding backticks."""
  return table_ref.strip().strip("`")


def quote_table_ref(table_ref: str) -> str:
  """Returns `table_ref` wrapped in exactly one pair of backticks."""
  # Hyphenated project ids can contain keywords (e.g. `a-with-b`), so every
  # table interpolated into SQL must be quoted.
  return f"`{bare_table_ref(table_ref)}`"


# ==============================================================================
# Byte Measurement
# ==============================================================================

# Authoritative volume metrics. Never use Log Analytics payload byte sums as a
# proxy for billed volume: they overstate it about 2x.
BILLED_BYTES_METRIC = "logging.googleapis.com/billing/bytes_ingested"
BYTE_COUNT_METRIC = "logging.googleapis.com/byte_count"

# Payload bytes for *content* analysis only (signature weighting, severity
# mix). `proto_payload` is a non-NULL STRUCT on every `_AllLogs` row, so the
# IF-guard skips its ~1 KB null skeleton when the row has no proto content.
# Not billed bytes: use BILLED_BYTES_METRIC for anything cost-facing.
PAYLOAD_BYTES_SQL = """
                COALESCE(BYTE_LENGTH(text_payload), 0) +
                COALESCE(BYTE_LENGTH(TO_JSON_STRING(json_payload)), 0) +
                IF(proto_payload.type IS NULL, 0,
                   COALESCE(BYTE_LENGTH(TO_JSON_STRING(proto_payload)), 0))
"""

# ==============================================================================
# Signature Templating
# ==============================================================================

# Masks variable tokens so lines group into templates. Order matters: each
# pattern runs on the previous one's output, so specific forms (dates, IPs)
# must match before the bare-integer rule.
SIGNATURE_MASK_PATTERNS = (
    (
        r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})?",
        "<TS>",
    ),
    (r"[A-Z][a-z]{2} +\d{1,2} \d{2}:\d{2}:\d{2}", "<TS>"),  # syslog
    (
        (
            r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}"
            r"-[0-9a-fA-F]{12}"
        ),
        "<UUID>",
    ),
    (r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", "<IP>"),
    (r"0x[0-9a-fA-F]+|\b[0-9a-fA-F]{8,}\b", "<HEX>"),
    (r"/[\w.\-]+/[\w./\-]*", "<PATH>"),
    # Blunt: also merges 'HTTP 500' with 'HTTP 200'.
    (r"\d+", "<N>"),
)

# A template containing a placeholder describes a family of lines, so it must
# never be interpolated into an exclusion filter as a literal.
MASK_PLACEHOLDERS = tuple(sorted({repl for _, repl in SIGNATURE_MASK_PATTERNS}))

# Templates are grouped and compared at this length.
SIGNATURE_TEMPLATE_CHARS = 200


def mask_sql(expr: str) -> str:
  """Wraps `expr` in the REGEXP_REPLACE chain that turns text into a template."""
  sql = expr
  for pattern, replacement in SIGNATURE_MASK_PATTERNS:
    sql = f"REGEXP_REPLACE({sql}, r'{pattern}', '{replacement}')"
  return sql


# ==============================================================================
# Extraneous Spend Model
# ==============================================================================

# GCP console default for VPC flow log sampling; lower targets would overstate
# recoverable spend.
FLOW_LOG_TARGET_SAMPLING = 0.5

# Free retention included with ingestion. Storage beyond this is billed extra.
INCLUDED_RETENTION_DAYS = 30

# If the computed floor exceeds this share of billable spend, still render it
# but flag it for manual review rather than presenting it as a safe number.
WASTE_SANITY_CEILING_PCT = 60.0

# Log IDs that are always free (stored in the _Required bucket). These must be
# excluded from both the numerator and denominator of any waste calculation.
FREE_REQUIRED_LOG_IDS = (
    "cloudaudit.googleapis.com/activity",
    "externalaudit.googleapis.com/activity",
    "cloudaudit.googleapis.com/system_event",
    "externalaudit.googleapis.com/system_event",
    "cloudaudit.googleapis.com/access_transparency",
    "externalaudit.googleapis.com/access_transparency",
)

# Buckets whose retention cannot be edited and is not billed (`_Required` is
# pinned at 400 days), so they are never reported as over-retained.
IMMUTABLE_RETENTION_BUCKETS = ("_Required",)

# Data Access audit logs are billed but often compliance-mandated, so they are
# surfaced to the owner and never counted as recoverable spend.
DATA_ACCESS_LOG_IDS = (
    "cloudaudit.googleapis.com/data_access",
    "externalaudit.googleapis.com/data_access",
)

# Streams still offered as actions, but read by security teams, so the reader
# is told what they are for. The value completes "Dropping this removes ...".
SECURITY_TELEMETRY_LOG_IDS = {
    "compute.googleapis.com/firewall": (
        "the record of which connections your firewall rules allowed and denied"
    ),
    "compute.googleapis.com/vpc_flows": (
        "the network flow record used for traffic forensics and incident"
        " reconstruction"
    ),
    "networkmanagement.googleapis.com/vpc_flows": (
        "the network flow record used for traffic forensics and incident"
        " reconstruction"
    ),
    "compute.googleapis.com/nat": (
        "the NAT translation record used to attribute outbound traffic to an"
        " instance"
    ),
    "dns.googleapis.com/dns_queries": (
        "the DNS query record used to detect exfiltration and command-and-"
        "control traffic"
    ),
    "cloudaudit.googleapis.com/policy": (
        "the record of requests your org policies denied"
    ),
}

# Payload markers of Linux audit subsystem records (often retained under
# PCI-DSS and FedRAMP), whose agent-chosen log ids cannot identify them.
HOST_AUDIT_PAYLOAD_MARKERS = (
    "type=PROCTITLE",
    "type=SYSCALL",
    "type=AVC",
    "audispd",
    "auditd.service",
)

HOST_AUDIT_CAVEAT = (
    "the Linux audit subsystem record of process and syscall activity on your"
    " instances"
)

# Display budget for patterns per (service, severity) in Service Details.
MAX_SAMPLES_PER_SEVERITY = 5

# Kept small: exclusions are irreversible and a long list invites bulk
# application without review.
MAX_EXCLUSION_CANDIDATES = 5


# ==============================================================================
# Pricing
# ==============================================================================

# A derived rate outside this band means volume and cost came from different
# bases, so it is rejected rather than published.
PLAUSIBLE_RATE_RANGE_PER_GIB = (0.05, 2.50)


def billable_gib(
    total_gib: float, free_tier_gib: float = FREE_TIER_GIB_PER_MONTH
) -> float:
  """Returns the portion of a month's ingestion that is actually charged."""
  return max(0.0, (total_gib or 0.0) - free_tier_gib)


def price_reduction(
    removed_gib: float,
    baseline_monthly_gib: float,
    rate_per_gib: float = LIST_PRICE_PER_GIB,
    free_tier_gib: float = FREE_TIER_GIB_PER_MONTH,
) -> float:
  """Returns the monthly saving from removing `removed_gib` of ingestion."""
  # The difference of two bills, so volume that falls back inside the free tier
  # saves nothing (100 GiB dropping 80 GiB saves $25, not $40).
  baseline = max(0.0, baseline_monthly_gib or 0.0)
  removed = max(0.0, min(removed_gib or 0.0, baseline))
  before = billable_gib(baseline, free_tier_gib)
  after = billable_gib(baseline - removed, free_tier_gib)
  return round((before - after) * rate_per_gib, 2)


def write_json(file_path: str, content: Any) -> None:
  """Helper to write content to a JSON file ensuring parent directories exist."""
  dir_name = os.path.dirname(file_path)
  if dir_name:
    os.makedirs(dir_name, exist_ok=True)
  with open(file_path, "w") as f:
    json.dump(content, f, indent=2)
enable_log_analytics.py 4.2 KB
"""Enables Log Analytics on a Google Cloud Logging bucket."""

from collections.abc import Sequence
import sys
from typing import Any, Dict

from absl import app
from absl import flags
from google.api_core import exceptions as api_exceptions
from google.api_core.gapic_v1 import client_info as gapic_client_info
from google.cloud.logging_v2 import types as logging_types
from google.cloud.logging_v2.services import config_service_v2

ConfigServiceV2Client = config_service_v2.ConfigServiceV2Client
LogBucket = logging_types.LogBucket
UpdateBucketRequest = logging_types.UpdateBucketRequest

# Attribution token (see `attribution.py`), duplicated because this strict-deps
# target cannot import that sibling module.
USER_AGENT = (
    "google-skills/1.0"
    " (skill:cloud-logging-finops; script:enable-log-analytics)"
)
# gcloud only takes a custom User-Agent through this variable, and needs the
# product name ahead of the token.
GCLOUD_METRICS_ENVIRONMENT = f"google-skills {USER_AGENT}"

FLAGS = flags.FLAGS
if "project-id" not in FLAGS:
  flags.DEFINE_string("project-id", None, "GCP Project ID.")
if "bucket-id" not in FLAGS:
  flags.DEFINE_string(
      "bucket-id", "_Default", "Bucket ID to enable Log Analytics on."
  )
if "location" not in FLAGS:
  flags.DEFINE_string("location", "global", "Bucket GCP location.")


def enable_log_analytics(
    config_client: ConfigServiceV2Client,
    project_id: str,
    bucket_id: str = "_Default",
    location: str = "global",
) -> Dict[str, Any]:
  """Enables Log Analytics on the specified bucket."""
  bucket_name = (
      f"projects/{project_id}/locations/{location}/buckets/{bucket_id}"
  )
  bucket = LogBucket(name=bucket_name, analytics_enabled=True)
  # proto-plus builds the FieldMask from a dict, so no protobuf import is
  # needed.
  mask = {"paths": ["analytics_enabled"]}
  request = UpdateBucketRequest(
      name=bucket_name, bucket=bucket, update_mask=mask
  )

  try:
    updated = config_client.update_bucket(request=request)
  except api_exceptions.GoogleAPICallError as e:
    if isinstance(e, api_exceptions.NotFound):
      diagnostic = (
          f"Bucket '{bucket_name}' was not found. Verify project ID, bucket"
          " ID, and location."
      )
    else:
      diagnostic = (
          "Ensure your identity has 'roles/logging.admin' or"
          " 'roles/logging.configWriter'."
      )
    return {
        "success": False,
        "bucket": bucket_name,
        "error": str(e),
        "message": (
            f"Failed to enable Log Analytics on '{bucket_name}': {e}.\n"
            f"  - Action: {diagnostic}\n"
            "  - Alternatively, run via gcloud CLI:\n"
            f'      CLOUDSDK_METRICS_ENVIRONMENT="{GCLOUD_METRICS_ENVIRONMENT}"'
            f" gcloud logging buckets update {bucket_id}"
            f" --location={location} --project={project_id} --enable-analytics"
        ),
    }
  if updated.analytics_enabled:
    message = (
        f"Successfully enabled Log Analytics on '{bucket_name}'.\n  - New"
        " logs will be queryable via SQL immediately.\n  - Historical logs"
        " prior to enablement are not retroactively indexed for SQL.\n  -"
        " Recommendation: Wait ~1 to 2 hours for a representative traffic"
        " sample before re-running audit."
    )
  else:
    message = (
        f"'{bucket_name}' was updated but still reports Log Analytics"
        " disabled."
    )
  return {
      "success": updated.analytics_enabled,
      "bucket": bucket_name,
      "analytics_enabled": updated.analytics_enabled,
      "message": message,
  }


def main(argv: Sequence[str]) -> None:
  if len(argv) > 1:
    raise app.UsageError("Too many command-line arguments.")
  project_id = FLAGS["project-id"].value
  if not project_id:
    raise app.UsageError("Flag --project-id is required.")

  client = ConfigServiceV2Client(
      client_info=gapic_client_info.ClientInfo(user_agent=USER_AGENT)
  )
  res = enable_log_analytics(
      client,
      project_id,
      FLAGS["bucket-id"].value or "_Default",
      FLAGS["location"].value or "global",
  )
  if res["success"]:
    print(res["message"])
  else:
    print(res["message"], file=sys.stderr)
    sys.exit(1)


if __name__ == "__main__":
  app.run(main)
exclusion_rules.py 12.6 KB
"""Builds precise, verifiable Cloud Logging exclusion filters.

Exclusions are irreversible, so these helpers guard against over-broad rules
(drop needed logs) first and no-op rules (match nothing) second.
"""

import re
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
import urllib.parse

from constants import BYTES_PER_GIB
from constants import DATA_ACCESS_LOG_IDS
from constants import FREE_REQUIRED_LOG_IDS
from constants import MASK_PLACEHOLDERS
from constants import MAX_EXCLUSION_CANDIDATES
from constants import SIGNATURE_TEMPLATE_CHARS
from pricing import PriceBook

# Maps the Log Analytics `signature_source` marker onto the Cloud Logging
# filter field holding the same value.
SIGNATURE_SOURCE_FIELDS = {
    "text_payload": "textPayload",
    "json_message": "jsonPayload.message",
    "json_MESSAGE": "jsonPayload.MESSAGE",
    "json_msg": "jsonPayload.msg",
    "json_log": "jsonPayload.log",
    "audit_method": "protoPayload.methodName",
}

# 'proto_type' (`@type`) is not reliably addressable in a filter, and
# 'json_shape' is a synthesised key skeleton no filter can select, so both
# stay stream-scoped.

# A signature must recur this many times in the sample window before it is
# treated as a durable pattern worth targeting.
MIN_SIGNATURE_ENTRIES = 10

# Shorter prefixes are not specific enough to bound the blast radius.
MIN_PREFIX_CHARS = 16

# Same length as the SQL grouping prefix, so an anchored prefix matches
# exactly the rows in the group.
MAX_PREFIX_CHARS = SIGNATURE_TEMPLATE_CHARS

# Severities that page a human; excluding them risks a missed incident.
NEVER_EXCLUDE_SEVERITIES = ("CRITICAL", "ALERT", "EMERGENCY")


def decode_log_id(log_id: str) -> str:
  """Returns `log_id` decoded; `logName` stores IDs percent-encoded."""
  return urllib.parse.unquote(log_id or "")


_FREE_REQUIRED = frozenset(
    decode_log_id(i).lower() for i in FREE_REQUIRED_LOG_IDS
)
_DATA_ACCESS = frozenset(decode_log_id(i).lower() for i in DATA_ACCESS_LOG_IDS)


def is_free_required(log_id: str) -> bool:
  """True for `_Required` streams, which are billed at $0."""
  return decode_log_id(log_id).lower() in _FREE_REQUIRED


def is_data_access(log_id: str) -> bool:
  """True for Data Access audit streams, which are never offered as savings."""
  return decode_log_id(log_id).lower() in _DATA_ACCESS


_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]")

# Built from the same tuple the SQL masks with, so the two stay in sync.
_MASK_PLACEHOLDER = re.compile(
    "|".join(re.escape(token) for token in MASK_PLACEHOLDERS)
)

# Tokens that rotate between otherwise identical lines; a prefix containing
# one stops matching once the value changes.
_VOLATILE_TOKEN = re.compile(
    r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"  # uuid
    r"|\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"  # ipv4
    r"|\b[0-9a-f]{16,}\b"  # trace / hash
    r"|\b\d{4,}\b"  # epoch, port, counter, numeric id
    r"|\d{2}:\d{2}:\d{2}",  # clock time
    re.IGNORECASE,
)

_RE2_METACHARS = re.compile(r"([\\.^$|()\[\]{}*+?])")


def escape_filter_string(value: str) -> str:
  """Escapes a value for embedding in a double-quoted filter string literal."""
  # Only `"` is escaped: the filter parser passes backslashes through verbatim,
  # so a regex escape needs a single backslash (`\.`, not `\\.`).
  return (value or "").replace('"', '\\"')


def escape_re2_literal(value: str) -> str:
  """Escapes RE2 metacharacters so `value` matches only itself."""
  # Narrower than `re.escape`, whose escapes of e.g. space are not portable RE2.
  return _RE2_METACHARS.sub(r"\\\1", value or "")


def encode_log_id(log_id: str) -> str:
  """Percent-encodes a log ID the way it appears inside `logName`."""
  # Unquotes first so already-encoded IDs are not double-encoded.
  if not log_id:
    return ""
  return urllib.parse.quote(decode_log_id(log_id), safe="")


def severity_predicate(severity: str) -> str:
  # DEFAULT included: omitting the predicate matches every severity.
  return f'severity = "{escape_filter_string(severity)}"'


def log_name_predicate(project_id: str, log_id: str) -> str:
  return (
      f'logName = "projects/{escape_filter_string(project_id)}/logs/'
      f'{escape_filter_string(encode_log_id(log_id))}"'
  )


def narrow_predicate(
    signature_source: Optional[str],
    signature_prefix: Optional[str],
    entry_count: int = 0,
) -> Tuple[Optional[str], Optional[str]]:
  """Returns `(predicate, None)` matching one signature, or `(None, reason)`."""
  field = SIGNATURE_SOURCE_FIELDS.get(signature_source or "")
  if not field:
    return None, "signature field is not addressable in a log filter"

  text = signature_prefix or ""
  if not text.strip():
    return None, "no signature text was captured"
  # A masked template ('<N>') would be matched literally by RE2 and find
  # nothing; only unmasked signatures can be narrowed.
  if _MASK_PLACEHOLDER.search(text):
    return None, (
        "signature is a normalised template; its variable tokens cannot be"
        " matched literally"
    )
  if _CONTROL_CHARS.search(text):
    return None, "signature contains control characters"
  if len(text) < MIN_PREFIX_CHARS:
    return None, "signature is too short to bound the match"
  if _VOLATILE_TOKEN.search(text):
    return None, "signature embeds a rotating id, address or timestamp"
  if (entry_count or 0) < MIN_SIGNATURE_ENTRIES:
    return None, (
        f"pattern recurred fewer than {MIN_SIGNATURE_ENTRIES} times in the"
        " sample window"
    )

  pattern = "^" + escape_re2_literal(text[:MAX_PREFIX_CHARS])
  return f'{field} =~ "{escape_filter_string(pattern)}"', None


def rule_eligibility(
    severity: str,
    log_id: str = "",
    rule_bytes: int = 0,
    rule_entries: int = 0,
) -> Tuple[bool, Optional[str]]:
  """Returns `(eligible, reason)`: is the rule safe and worth recommending?"""
  # Any failure disqualifies the rule outright.
  if (severity or "").upper() in NEVER_EXCLUDE_SEVERITIES:
    return False, (
        f"{severity} entries page an on-call; excluding them trades an"
        " incident signal for negligible savings"
    )

  if is_free_required(log_id):
    return False, (
        "_Required stream, already billed at $0; excluding it saves nothing"
        " and may breach audit retention obligations"
    )

  if is_data_access(log_id):
    return False, (
        "Data Access audit logs; these may be required by your organisation's"
        " audit obligations, so they are reported but never counted as"
        " recoverable spend"
    )

  if not (rule_bytes > 0 or rule_entries > 0):
    return False, "no volume measured in the sample window; savings unknown"

  return True, None


def build_sample_rule(
    sig: Mapping[str, Any], project_id: str
) -> Dict[str, Any]:
  """Builds an exclusion rule for one signature row, with the volume it drops.

  Narrowed to the signature when its text is safely matchable, else widened to
  the whole stream at that severity. Not priced here: sample bytes are Log
  Analytics payload bytes, so the caller anchors savings to the billed run
  rate.

  Args:
    sig: one row from `analytics` signature output.
    project_id: project the filter targets.

  Returns:
    The rule's filter, scope, measured volume and eligibility.
  """
  service, severity, log_id = sig["service"], sig["severity"], sig["log_id"]
  parts = [severity_predicate(severity)]
  if service != "unknown":
    parts.insert(0, f'resource.type = "{escape_filter_string(service)}"')
  if log_id != "unknown":
    parts.append(log_name_predicate(project_id, log_id))

  predicate, reason = narrow_predicate(
      sig["signature_source"], sig["preview"], sig["count"]
  )
  if predicate:
    parts.append(predicate)
    scope, note = "signature", "this pattern only"
    rule_bytes, rule_entries = sig["total_bytes"], sig["count"]
  else:
    scope, note = "stream", "entire stream at this severity"
    rule_bytes, rule_entries = (
        sig["stream_total_bytes"],
        sig["stream_entry_count"],
    )

  eligible, ineligible_reason = rule_eligibility(
      severity, log_id, rule_bytes, rule_entries
  )
  return {
      "filter": " AND ".join(parts),
      "rule_scope": scope,
      "rule_scope_note": note,
      "rule_scope_reason": reason,
      "rule_bytes": rule_bytes,
      "rule_entry_count": rule_entries,
      "eligible": eligible,
      "ineligible_reason": ineligible_reason,
  }


# A rule under both floors is not worth an owner's attention, and its estimate
# is dominated by sampling noise.
MIN_RULE_SHARE_PCT = 5.0
MIN_RULE_GIB = 50.0
MIN_RULE_ENTRIES = 50_000


def _title(rule: Mapping[str, Any], service: str, severity: str, log_id: str):
  where = f"{service} ({log_id})"
  if rule["rule_scope"] == "signature":
    return f"Exclude repetitive log pattern in {where}"
  if severity in ("DEBUG", "DEFAULT"):
    return f"Filter routine {severity} logs in {where}"
  if severity == "INFO":
    return f"Filter chatty INFO logs for {where}"
  return f"Filter {severity} logs in {where}"


def generate_exclusion_candidates(
    signatures: Sequence[Mapping[str, Any]],
    price_book: PriceBook,
    project_id: str,
    total_entries: int,
    total_sample_bytes: int,
    monthly_run_rate_gib: float,
    sample_days: float,
) -> List[Dict[str, Any]]:
  """Proposes Log Router exclusion rules, ranked by the volume each one drops.

  The only surface emitting copy-pasteable exclusions; every rule passes the
  `rule_eligibility` gates.

  Args:
    signatures: signature rows from the Log Analytics sample.
    price_book: prices each rule's savings.
    project_id: project the filters target.
    total_entries: entries in the sample.
    total_sample_bytes: bytes in the sample.
    monthly_run_rate_gib: billed monthly ingestion savings are anchored to.
    sample_days: length of the sample window.

  Returns:
    Candidate rules, largest first.
  """
  by_filter: Dict[str, Dict[str, Any]] = {}
  for sig in signatures:
    srv, sev, log_id = sig["service"], sig["severity"], sig["log_id"]
    rule = build_sample_rule(sig, project_id)
    if not rule["eligible"]:
      continue

    # Gate on what the rule drops, which for a widened rule is the whole
    # stream. The share basis is chosen per rule: a stream's byte column may
    # be NULL.
    rule_bytes, rule_entries = rule["rule_bytes"], rule["rule_entry_count"]
    if rule_bytes > 0 and total_sample_bytes > 0:
      pct = round(100.0 * rule_bytes / total_sample_bytes, 1)
      large = rule_bytes / BYTES_PER_GIB >= MIN_RULE_GIB
      magnitude = f"~{rule_bytes / BYTES_PER_GIB:,.1f} GiB"
    elif rule_entries > 0 and total_entries > 0:
      pct = round(100.0 * rule_entries / total_entries, 1)
      large = rule_entries >= MIN_RULE_ENTRIES
      magnitude = f"~{rule_entries:,} entries"
    else:
      continue
    if pct < MIN_RULE_SHARE_PCT and not large:
      continue

    filt = rule["filter"]
    prior = by_filter.get(filt)
    if prior is not None and rule_bytes <= prior["sample_bytes"]:
      continue

    scope_phrase = (
        rule["rule_scope_note"]
        if rule["rule_scope"] == "signature"
        else f"all {sev} logs in stream '{log_id}'"
    )
    rationale = (
        f"Drops {scope_phrase}: {magnitude} over the {sample_days:g}-day"
        f" sample ({pct}% of sampled volume)."
    )
    if rule["rule_scope_reason"]:
      rationale += f" Scoped to the stream because {rule['rule_scope_reason']}."

    # Apportion the billed run rate by the sampled share: payload bytes
    # overstate billed volume, so the sample is trusted only for the ratio.
    monthly_gib = pct / 100.0 * monthly_run_rate_gib
    by_filter[filt] = {
        "title": _title(rule, srv, sev, log_id),
        "service": srv,
        "severity": sev,
        "log_id": log_id,
        "filter": filt,
        "sample_bytes": rule_bytes,
        "rule_scope": rule["rule_scope"],
        "rule_scope_note": rule["rule_scope_note"],
        "projected_savings_pct": pct,
        "projected_savings_gib": round(monthly_gib, 2),
        # Difference of two bills, so the per-SKU free tier is respected.
        "projected_monthly_savings_usd": price_book.saving(
            {price_book.sku_for_log(log_id): monthly_gib}
        ),
        "rationale": rationale,
        "sample_log": sig["sample_log"],
    }

  ranked = sorted(
      by_filter.values(),
      key=lambda c: (c["sample_bytes"], c["projected_savings_pct"]),
      reverse=True,
  )
  # A stream rule subsumes signature rules on its stream; keeping both would
  # double count.
  streams = {
      (c["service"], c["severity"], c["log_id"])
      for c in ranked
      if c["rule_scope"] == "stream"
  }
  disjoint = [
      c
      for c in ranked
      if c["rule_scope"] == "stream"
      or (c["service"], c["severity"], c["log_id"]) not in streams
  ]
  return disjoint[:MAX_EXCLUSION_CANDIDATES]
inventory.py 7.1 KB
"""Log Router, flow log and log read scope inventory.

Every fetch reports what it could not read (an `unavailable` list, or the read
scope's `note`), so a project the skill lacked access to inspect is not
reported as one with nothing to clean up or no logs to sample.
"""

from typing import Any, Dict, Iterator, List, Optional, Tuple

import attribution

_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)


def authed_session() -> Any:
  """Returns an authorized, attributed requests session; raises without ADC."""
  import google.auth  # pylint: disable=g-import-not-at-top
  from google.auth.transport import requests as auth_requests  # pylint: disable=g-import-not-at-top

  credentials, _ = google.auth.default(scopes=list(_SCOPES))
  return attribution.tag_session(
      auth_requests.AuthorizedSession(credentials),
      attribution.COLLECT_LOGGING_DATA,
  )


def _pages(
    session: Any,
    url: str,
    params: Dict[str, Any],
    what: str,
    timeout: int,
    unavailable: List[str],
) -> Iterator[Dict[str, Any]]:
  """Yields each page of a Google REST list call, following `nextPageToken`."""
  # A failed page ends the listing and is recorded in `unavailable`; the pages
  # already yielded are kept.
  page_token = None
  while True:
    try:
      response = session.get(
          url, params={**params, "pageToken": page_token}, timeout=timeout
      )
      if not response.ok:
        raise RuntimeError(f"HTTP {response.status_code}")
      payload = response.json()
    except Exception as e:  # pylint: disable=broad-except
      print(f"Notice: unable to list {what}: {e}")
      unavailable.append(f"{what}: {e}")
      return
    yield payload
    page_token = payload.get("nextPageToken")
    if not page_token:
      return


def fetch_log_router_inventory(
    session: Any, project_id: str
) -> Tuple[Dict[str, List[Any]], List[str]]:
  """Fetches Log Router sinks and exclusions (project-level and sink-attached).

  Exclusions record operator intent that their volume should be dropped.

  Args:
    session: authorized `requests.Session`.
    project_id: project to read.

  Returns:
    `({"sinks": [...], "exclusions": [...]}, unavailable)`.
  """
  base = f"https://logging.googleapis.com/v2/projects/{project_id}"
  out: Dict[str, List[Any]] = {"sinks": [], "exclusions": []}
  unavailable: List[str] = []
  for key in out:
    for page in _pages(
        session, f"{base}/{key}", {}, f"Log Router {key}", 60, unavailable
    ):
      out[key].extend(page.get(key) or [])

  seen = {x.get("name") for x in out["exclusions"]}
  for sink in out["sinks"]:
    for exclusion in sink.get("exclusions") or []:
      if exclusion.get("name") not in seen:
        seen.add(exclusion.get("name"))
        out["exclusions"].append(exclusion)
  return out, unavailable


def fetch_flow_log_configs(
    session: Any, project_id: str
) -> Tuple[List[Dict[str, Any]], List[str]]:
  """Fetches VPC flow log configs from both managing APIs.

  Network Management and per-subnet Compute configs emit different log IDs, so
  both are needed.

  Args:
    session: authorized `requests.Session`.
    project_id: project to read.

  Returns:
    `([{"state", "flow_sampling"}, ...], unavailable)`.
  """
  configs: List[Dict[str, Any]] = []
  unavailable: List[str] = []

  for page in _pages(
      session,
      "https://networkmanagement.googleapis.com/v1/projects/"
      f"{project_id}/locations/global/vpcFlowLogsConfigs",
      {"pageSize": 500},
      "VPC flow log configs",
      60,
      unavailable,
  ):
    for cfg in page.get("vpcFlowLogsConfigs") or []:
      configs.append(
          {"state": cfg.get("state"), "flow_sampling": cfg.get("flowSampling")}
      )

  for page in _pages(
      session,
      "https://compute.googleapis.com/compute/v1/projects/"
      f"{project_id}/aggregated/subnetworks",
      {"maxResults": 500},
      "subnet flow log configs",
      120,
      unavailable,
  ):
    for scoped in (page.get("items") or {}).values():
      for subnet in scoped.get("subnetworks") or []:
        log_config = subnet.get("logConfig") or {}
        if log_config.get("enable"):
          configs.append({
              "state": "ENABLED",
              "flow_sampling": log_config.get("flowSampling"),
          })

  return configs, unavailable


_DEFAULT_SCOPE_URL = (
    "https://observability.googleapis.com/v1/projects/{project_id}"
    "/locations/global/scopes/_Default"
)
_LOGGING_V2 = "https://logging.googleapis.com/v2/"
# `Scope.logScope` carries the service prefix; the Logging API path does not.
_LOG_SCOPE_PREFIX = "logging.googleapis.com/"


def project_read_scope(
    project_id: str, note: Optional[str] = None
) -> Dict[str, Any]:
  """The read scope that covers only the project's own buckets."""
  scope: Dict[str, Any] = {
      "source": "project",
      "log_scope": None,
      "resource_names": [f"projects/{project_id}"],
  }
  if note:
    scope["note"] = note
  return scope


def resolve_log_read_scope(session: Any, project_id: str) -> Dict[str, Any]:
  """Returns the resources to read log entries from, as Logs Explorer would.

  Logs Explorer reads through the project's default observability scope, whose
  log scope may list log views in other buckets or projects instead of the
  project itself. Reading only `projects/{id}` then returns nothing even though
  the user can see the logs. Any failure falls back to the project alone and is
  recorded in `note`, so an unresolved scope is disclosed rather than read as
  "no logs".

  Args:
    session: authorized `requests.Session`, or None.
    project_id: project whose default scope is read.

  Returns:
    `{"source": "default_scope" | "project", "log_scope", "resource_names"}`,
    plus `note` when the fallback was used.
  """
  if session is None:
    return project_read_scope(project_id, "no authorized session")

  def get_json(url: str, what: str) -> Dict[str, Any]:
    response = session.get(url, params={}, timeout=30)
    if not response.ok:
      raise RuntimeError(f"{what}: HTTP {response.status_code}")
    return response.json() or {}

  try:
    scope = get_json(
        _DEFAULT_SCOPE_URL.format(project_id=project_id),
        "default observability scope",
    )
    log_scope = str(scope.get("logScope") or "")
    if log_scope.startswith(_LOG_SCOPE_PREFIX):
      log_scope = log_scope[len(_LOG_SCOPE_PREFIX):]
    if not log_scope:
      return project_read_scope(
          project_id, "the default observability scope names no log scope"
      )
    resources = get_json(_LOGGING_V2 + log_scope, f"log scope {log_scope}").get(
        "resourceNames"
    ) or []
  except Exception as e:  # pylint: disable=broad-except
    print(
        "Notice: unable to resolve the default log scope; reading"
        f" projects/{project_id} only: {e}"
    )
    return project_read_scope(project_id, str(e))

  if not resources:
    scope = project_read_scope(project_id, "the log scope lists no resources")
    scope["log_scope"] = log_scope
    return scope
  return {
      "source": "default_scope",
      "log_scope": log_scope,
      # Order kept; a repeated resource would only duplicate samples.
      "resource_names": list(dict.fromkeys(resources)),
  }
messages.py 3.4 KB
"""Reader-facing wording for the cost reduction actions.

Kept apart from `actions.py` so the merge logic reads as logic and the copy can
be reviewed (or translated) on its own. Nothing here makes a decision.
"""

# --- Verdict labels, keyed on `assurance.level` ------------------------------
LEVEL_LABELS = {
    "unmeasured": "Not quantified",
    "estimated": "Estimated — your call",
    "judgement": "Your call",
    "confirm": "Confirm before applying",
    "ready": "Ready to apply",
}

# --- How the saving was arrived at -------------------------------------------
HOW_MEASURED_LEVER = "The saving is measured against your billing metrics."
HOW_MEASURED_RULE = (
    "The saving is projected from this stream's share of a log sample, not"
    " read from a billing metric, so treat it as an estimate. The filter"
    " itself is exact."
)

# --- What the reader still has to decide (a lever's `flag`) ------------------
FLAG_INTENT_INFERRED = (
    "An exclusion rule on this project says this volume was meant to be"
    " dropped, but that rule no longer matches the stream carrying it."
    " Confirm dropping the stream is still what you want."
)
FLAG_NOT_QUANTIFIED = (
    "The change is real, but the metrics used here do not expose the"
    " volume behind it, so no saving is claimed."
)

CONFIDENCE_MEANINGS = {
    "high": "Removing this is routine and rarely costs a signal anyone wanted.",
    "medium": "There is a trade-off here; read the evidence before applying.",
    "low": (
        "The case for removing this is weak; read the evidence before acting."
    ),
}

SCOPE_JUDGEMENT = {
    "stream": (
        "Applying this stops every log of this severity in the stream being"
        " ingested."
    ),
    "signature": (
        "Applying this drops only the matching lines; the rest of the stream is"
        " still ingested."
    ),
}
READ_SAMPLE = " Read the example log below before deciding."

ALTERNATIVE_TO = (
    'An alternative to "{title}" on the same stream: applying both does not'
    " save the sum of the two figures."
)

# --- Security telemetry ------------------------------------------------------
SECURITY_CAVEAT_DROPS = (
    "This is security telemetry: dropping it removes {what}. Teams do drop it"
    " for cost, but check first whether an audit obligation or an"
    " incident-response process depends on it."
)
SECURITY_CAVEAT_REDUCES = (
    "This is security telemetry: {what}. It is still captured after this"
    " change, at lower fidelity, so check whoever relies on it can work with"
    " the coarser data."
)

# --- Why something is not offered --------------------------------------------
WITHHELD_NO_VOLUME = "no volume measured, so no saving can be quoted"
WITHHELD_NO_REMEDY = (
    "no exclusion filter could be built for the streams it measured, so there"
    " is nothing to apply"
)
WITHHELD_DATA_ACCESS = (
    "{gib:.1f} GiB/mo of Data Access audit logs, left out of the savings"
    " figure because it is a compliance decision: disabling or excluding them"
    " is frequently prohibited by audit, regulatory or security policy, so the"
    " owner must confirm with their compliance team before acting."
)

REFUSED_NO_LOG_ID = (
    "the stream has no log ID, so a filter for it would match every stream in"
    " the project"
)
REFUSED_FILTER_TOO_LONG = (
    "does not fit within Cloud Logging's {limit:,}-character exclusion filter"
    " limit; add a second exclusion for the remaining streams"
)
monitoring.py 12.6 KB
"""Cloud Monitoring (GCM) metric queries and parsing.

Buckets are aligned to UTC midnight so they are calendar days, and a failed
query is reported as a missing window, never as zero volume.
"""

import collections
import concurrent.futures
import datetime
from typing import Any, Dict, List, NamedTuple, Sequence, Tuple

from constants import BILLED_BYTES_METRIC
from constants import BYTE_COUNT_METRIC
from constants import DEFAULT_SAMPLE_DAYS
from constants import MONITORING_RETENTION_DAYS
from google.api_core import exceptions as api_exceptions
from google.cloud import monitoring_v3

_ALIGNMENT_SECONDS = 86400

# Short so a too-wide window fails fast enough to be halved and retried.
_CHUNK_TIMEOUT_SECONDS = 60.0

# Series are day-aligned, so splitting below one day cannot help.
_MIN_CHUNK_DAYS = 1

_MAX_WORKERS = 12

_BYTE_COUNT = f'metric.type = "{BYTE_COUNT_METRIC}"'

# An empty severity label is what the Log Router calls DEFAULT.
DEFAULT_SEVERITY = "DEFAULT"


class SeriesResult(NamedTuple):
  """Time series plus the windows that could not be fetched.

  Non-empty `missing_windows` means the series is a lower bound.
  """

  series: List[Any]
  missing_windows: List[str]


def floor_to_utc_day(moment: datetime.datetime) -> datetime.datetime:
  """Truncates `moment` to midnight UTC, attaching UTC if it is naive."""
  if moment.tzinfo is None:
    moment = moment.replace(tzinfo=datetime.timezone.utc)
  return moment.astimezone(datetime.timezone.utc).replace(
      hour=0, minute=0, second=0, microsecond=0
  )


def _interval(
    end: datetime.datetime, newer_days: int, older_days: int
) -> monitoring_v3.TimeInterval:
  """The window from `older_days` to `newer_days` before `end`."""
  return monitoring_v3.TimeInterval({
      "end_time": {
          "seconds": int(
              (end - datetime.timedelta(days=newer_days)).timestamp()
          )
      },
      "start_time": {
          "seconds": int(
              (end - datetime.timedelta(days=older_days)).timestamp()
          )
      },
  })


def get_query_interval(
    now: datetime.datetime, lookback_days: int = MONITORING_RETENTION_DAYS
) -> monitoring_v3.TimeInterval:
  """Returns whole days ending at the most recent UTC midnight."""
  # The partial current day is excluded, and the span is clamped to Cloud
  # Monitoring's 42-day retention (longer requests silently return less).
  return _interval(
      floor_to_utc_day(now), 0, min(lookback_days, MONITORING_RETENTION_DAYS)
  )


def _query_time_series(
    client: monitoring_v3.MetricServiceClient,
    project_id: str,
    filter_str: str,
    interval: monitoring_v3.TimeInterval,
    group_by_fields: List[str],
    timeout: float = 180.0,
) -> List[Any]:
  """Queries GCM list_time_series with daily alignment."""
  results = client.list_time_series(
      request={
          "name": f"projects/{project_id}",
          "filter": filter_str,
          "interval": interval,
          "view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL,
          "aggregation": monitoring_v3.Aggregation({
              "alignment_period": {"seconds": _ALIGNMENT_SECONDS},
              "per_series_aligner": monitoring_v3.Aggregation.Aligner.ALIGN_SUM,
              "cross_series_reducer": (
                  monitoring_v3.Aggregation.Reducer.REDUCE_SUM
              ),
              "group_by_fields": group_by_fields,
          }),
      },
      timeout=timeout,
  )
  return list(results)


# Wide `byte_count` windows on chatty projects time out with 503/504 "Please
# shorten the time interval"; such windows are halved and retried.
_TIMEOUT_MARKERS = ("timed out", "shorten the time interval", "deadline")


def _is_timeout(error: Exception) -> bool:
  """Reports whether an error is the backend asking for a smaller window."""
  if isinstance(
      error,
      (
          api_exceptions.DeadlineExceeded,
          api_exceptions.ServiceUnavailable,
          api_exceptions.GatewayTimeout,
          api_exceptions.RetryError,
      ),
  ):
    return True
  message = str(error).lower()
  return any(marker in message for marker in _TIMEOUT_MARKERS)


def query_log_volume(
    client: monitoring_v3.MetricServiceClient,
    project_id: str,
    interval: monitoring_v3.TimeInterval,
) -> List[Any]:
  """Queries GCM for billed logging volume, grouped by resource type."""
  return _query_time_series(
      client=client,
      project_id=project_id,
      filter_str=f'metric.type = "{BILLED_BYTES_METRIC}"',
      interval=interval,
      group_by_fields=["metric.label.resource_type"],
  )


def _fetch_window(
    client: monitoring_v3.MetricServiceClient,
    project_id: str,
    group_by: List[str],
    flt: str,
    name: str,
    end: datetime.datetime,
    newer_days: int,
    older_days: int,
) -> Tuple[List[Any], List[str]]:
  """Fetches one `byte_count` window, halving it while the backend times out."""
  # Returns `(series, failed_windows)`. Only a single day that fails on its
  # own, or a non-timeout error, is reported as a gap.
  window = f"{name}[{newer_days}..{older_days}d]"
  try:
    return (
        _query_time_series(
            client=client,
            project_id=project_id,
            filter_str=flt,
            interval=_interval(end, newer_days, older_days),
            group_by_fields=group_by,
            timeout=_CHUNK_TIMEOUT_SECONDS,
        ),
        [],
    )
  except api_exceptions.InvalidArgument:
    # Grouping unsupported for this resource type: a genuine absence, not a gap.
    return [], []
  except (api_exceptions.GoogleAPICallError, api_exceptions.RetryError) as e:
    span = older_days - newer_days
    if span <= _MIN_CHUNK_DAYS or not _is_timeout(e):
      print(f"Warning: byte_count query {window} failed: {e}")
      return [], [window]
    midpoint = newer_days + span // 2
    print(f"Notice: {window} exceeded the backend's limit; splitting.")
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
      halves = [
          executor.submit(
              _fetch_window,
              client,
              project_id,
              group_by,
              flt,
              name,
              end,
              lo,
              hi,
          )
          for lo, hi in ((newer_days, midpoint), (midpoint, older_days))
      ]
      series: List[Any] = []
      failures: List[str] = []
      for half in halves:
        half_series, half_missing = half.result()
        series.extend(half_series)
        failures.extend(half_missing)
    return series, failures


def _fetch_windowed(
    client: monitoring_v3.MetricServiceClient,
    project_id: str,
    group_by: List[str],
    now: datetime.datetime,
    days: int,
    chunk_days: int,
    scopes: Sequence[Tuple[str, str]],
) -> SeriesResult:
  """Fetches `byte_count` over `days` in parallel `chunk_days` windows.

  Args:
    client: Cloud Monitoring client.
    project_id: Project whose metrics are queried.
    group_by: Labels to group by.
    now: Reference instant; the window ends at the preceding UTC midnight.
    days: Width of the window, clamped to Cloud Monitoring's retention.
    chunk_days: Width of each parallel request.
    scopes: `(name, filter)` pairs, each fetched over the whole window; `name`
      labels its missing windows.

  Returns:
    The series of every scope, with any window that failed.
  """
  end = floor_to_utc_day(now)
  days = max(1, min(int(days), MONITORING_RETENTION_DAYS))
  results: List[Any] = []
  missing: List[str] = []
  with concurrent.futures.ThreadPoolExecutor(
      max_workers=_MAX_WORKERS
  ) as executor:
    tasks = []
    for name, flt in scopes:
      for newer in range(0, days, chunk_days):
        tasks.append(
            executor.submit(
                _fetch_window,
                client,
                project_id,
                group_by,
                flt,
                name,
                end,
                newer,
                min(newer + chunk_days, days),
            )
        )
    for future in concurrent.futures.as_completed(tasks):
      series, failures = future.result()
      results.extend(series)
      missing.extend(failures)
  return SeriesResult(results, sorted(missing))


def sum_filter(
    client: monitoring_v3.MetricServiceClient,
    project_id: str,
    flt: str,
    end: datetime.datetime,
    days: int,
) -> float:
  """Σ every daily point matching `flt` over the `days` before `end`.

  Args:
    client: Cloud Monitoring client.
    project_id: project to read.
    flt: time series filter.
    end: exclusive end of the window.
    days: window length in days.

  Returns:
    The sum of every matching daily point.

  Raises:
    RuntimeError: if any window could not be read, so a gap is never read as
      zero.
  """
  series, missing = _fetch_window(
      client, project_id, [], flt, "sum", end, 0, days
  )
  if missing:
    raise RuntimeError(f"could not read {', '.join(missing)}")
  total = 0
  for ts in series:
    for _, value in _extract_points(ts):
      total += value
  return float(total)


def query_severity_volume(
    client: monitoring_v3.MetricServiceClient,
    project_id: str,
    top_services: List[str],
    now: datetime.datetime,
    days: int = DEFAULT_SAMPLE_DAYS,
    chunk_days: int = 7,
) -> SeriesResult:
  """Queries `byte_count` per (severity, resource type) for `top_services`."""
  return _fetch_windowed(
      client,
      project_id,
      ['metric.label."severity"', "resource.type"],
      now,
      days,
      chunk_days,
      [(s, f'{_BYTE_COUNT} AND resource.type = "{s}"') for s in top_services],
  )


def query_stream_volume(
    client: monitoring_v3.MetricServiceClient,
    project_id: str,
    now: datetime.datetime,
    days: int = DEFAULT_SAMPLE_DAYS,
    chunk_days: int = 3,
) -> SeriesResult:
  """Queries `byte_count` per (log, severity) across `days`."""
  # Single source for all per-stream `byte_count` reads: summing a day's
  # streams equals the ungrouped total.
  return _fetch_windowed(
      client,
      project_id,
      ["metric.label.log", "metric.label.severity"],
      now,
      days,
      chunk_days,
      [("byte_count", _BYTE_COUNT)],
  )


def _extract_points(ts: Any) -> List[List[Any]]:
  """Extracts daily `[date, value]` points from a GCM TimeSeries."""
  # Points are labelled by the day the bucket covers (end_time minus one day),
  # not the following midnight at which it ends.
  points = []
  for point in ts.points:
    bucket_start = point.interval.end_time - datetime.timedelta(
        seconds=_ALIGNMENT_SECONDS
    )
    value = point.value.int64_value or int(round(point.value.double_value))
    points.append([bucket_start.strftime("%Y-%m-%d"), value])
  return points


def _collapse(parsed: Dict[Any, Dict[str, int]]) -> Dict[Any, List[List[Any]]]:
  """Renders an accumulated `{key: {date: value}}` map as sorted point lists."""
  return {
      key: [[d, dates[d]] for d in sorted(dates)]
      for key, dates in parsed.items()
  }


def parse_stream_results(
    results: List[Any],
) -> Dict[Tuple[str, str], List[List[Any]]]:
  """Parses `byte_count` series into daily history per (log_id, severity)."""
  # Values accumulate because chunked windows return one series per chunk;
  # series without a log label cannot be attributed and are dropped.
  parsed: Dict[Tuple[str, str], Dict[str, int]] = collections.defaultdict(
      lambda: collections.defaultdict(int)
  )
  for ts in results:
    labels = ts.metric.labels
    log_id = labels.get("log", "")
    if not log_id:
      continue
    key = (log_id, labels.get("severity") or DEFAULT_SEVERITY)
    for date_str, val in _extract_points(ts):
      parsed[key][date_str] += val
  return _collapse(parsed)


def parse_severity_results(
    results: List[Any],
) -> Dict[str, Dict[str, List[List[Any]]]]:
  """Parses GCM severity results into daily history per service and severity."""
  parsed: Dict[str, Dict[str, Dict[str, int]]] = collections.defaultdict(
      lambda: collections.defaultdict(lambda: collections.defaultdict(int))
  )
  for ts in results:
    service = ts.resource.type or "unknown"
    severity = ts.metric.labels.get("severity") or DEFAULT_SEVERITY
    for date_str, val in _extract_points(ts):
      parsed[service][severity][date_str] += val
  return {service: _collapse(sevs) for service, sevs in parsed.items()}


def parse_billing_results(results: List[Any]) -> Dict[str, List[List[Any]]]:
  """Parses billed-bytes series into daily history per resource type."""
  # Values accumulate because several series can share a `resource_type`;
  # series without one go under "unknown".
  parsed: Dict[str, Dict[str, int]] = collections.defaultdict(
      lambda: collections.defaultdict(int)
  )
  for ts in results:
    service = ts.metric.labels.get("resource_type") or "unknown"
    for date_str, val in _extract_points(ts):
      parsed[service][date_str] += val
  return _collapse(parsed)
output.py 5.9 KB
"""Partitioned File Exporters and Console Advisories."""

import collections
import os
from typing import Any, Dict, List, Optional

from constants import write_json


def write_monthly_details(
    billing_data: Dict[str, List[List[Any]]],
    output_dir: str,
    project_id: str,
) -> Dict[str, str]:
  """Writes daily history grouped by month into partitioned JSON files."""
  monthly_daily: Dict[str, Dict[str, List[Any]]] = collections.defaultdict(
      lambda: collections.defaultdict(list)
  )
  for service, points in billing_data.items():
    for date_str, val in points:
      monthly_daily[date_str[:7]][service].append(
          [date_str, {"billing_total": val}]
      )

  written_files = {}
  for month, services in monthly_daily.items():
    for srv in services:
      services[srv].sort(key=lambda x: x[0])

    file_name = f"{month}.json"
    write_json(
        os.path.join(output_dir, file_name),
        {"project_id": project_id, "month": month, "services": dict(services)},
    )
    written_files[month] = os.path.join("monthly_details", file_name)

  return written_files


def write_service_details(
    merged_data: Dict[str, Dict[str, Dict[str, Any]]],
    output_dir: str,
    project_id: str,
    samples_by_service: Optional[
        Dict[str, Dict[str, List[Dict[str, Any]]]]
    ] = None,
) -> Dict[str, str]:
  """Writes daily history grouped by service into partitioned JSON files."""
  written_files = {}
  for service, dates in merged_data.items():
    safe_name = service.replace("/", "_")
    file_name = f"{safe_name}.json"
    service_content: Dict[str, Any] = {
        "project_id": project_id,
        "service": service,
        "daily_history": [[d, dates[d]] for d in sorted(dates.keys())],
    }
    if samples_by_service and service in samples_by_service:
      service_content["samples_by_severity"] = samples_by_service[service]
    write_json(
        os.path.join(output_dir, file_name),
        service_content,
    )
    written_files[service] = os.path.join("service_details", file_name)

  return written_files


def _print_billing_advisory(billing: Dict[str, Any]) -> None:
  """Says what the cost figures rest on and how discovery got there."""
  print(
      f"  BigQuery Billing Sync status: {billing['status']} (days available:"
      f" {billing['days_available']:.1f})"
  )
  for step in billing["fallback_chain"]:
    table = f" ({step['table']})" if step.get("table") else ""
    print(f"    - {step['tier']}: {step['status']}{table} - {step['detail']}")

  if not billing["invoiced"]:
    print(
        "\n[FINOPS ADVISORY - BILLING SYNC] No billing export was read, so"
        " costs are list-price estimates from Cloud Monitoring volume."
    )
    print(
        "  - Action for Agent: Tell the user, in plain language, what the"
        " discovery steps above checked and found (SKILL.md Step 3A), that list"
        " pricing was applied, and that --billing-table or"
        " --billing-project/--billing-dataset points at an export elsewhere."
    )
  elif billing["status"] == "partial_window":
    print(
        "\n[FINOPS ADVISORY - BILLING SYNC] BigQuery Billing Export has"
        f" {billing['days_available']:.1f} days of data (active since"
        f" {billing['earliest_date']})."
    )
    print(
        "  - Action for Agent: Hybrid cost analysis used. Invoiced BQ billing"
        " data used for available months; earlier months estimated from usage"
        " volume. Explicitly note this date demarcation in final reports."
    )
  else:
    print(
        "\n[FINOPS ADVISORY - BILLING SYNC] The billing export covers the whole"
        " analysis window. Monthly totals are invoice-accurate, including"
        " credits; service and severity splits are priced before credits."
    )


def print_advisory(summary: Dict[str, Any], output_path: str) -> None:
  """Prints formatted FinOps advisories for the agent and user."""
  analytics = summary["analytics_metadata"]
  status = analytics["status"]
  days_available = analytics["days_available"]
  flow = {
      "mature": "log_analytics",
      "partial_window": "complementary_sample",
  }.get(status, "cloud_monitoring_baseline")
  print("\n[DATA COLLECTION COMPLETE]")
  print(f"  Summary saved to: {output_path}")
  print(f"  Log Analytics status: {status} (flow: {flow})")
  _print_billing_advisory(summary["billing_metadata"])

  if not analytics["enabled"]:
    print(
        "\n[FINOPS ADVISORY - LOG ANALYTICS] Log Analytics is DISABLED on"
        " bucket '_Default'."
    )
    print(
        "  - Action for Agent: Inform the user and recommend enabling Log"
        " Analytics (no extra storage cost; unlocks granular log_name &"
        " container exclusion filters). The upgrade cannot be undone, so end"
        " your reply by asking: \"Do you want me to upgrade the '_Default'"
        " bucket to Log Analytics? This can't be undone.\" Then wait; never"
        " run it in the same turn."
    )
    print("  - Command to enable upon user approval:")
    print(
        "      /tmp/finops_venv/bin/python scripts/enable_log_analytics.py"
        f" --project-id {summary['project_id']}"
    )
  elif status == "too_fresh":
    print(
        "\n[FINOPS ADVISORY - LOG ANALYTICS] Log Analytics was enabled < 24h"
        " ago."
    )
    print(
        "  - Action for Agent: Used 14-day Cloud Monitoring baseline. SQL"
        " breakdowns will unlock as logs accumulate (~1-2 hrs for initial"
        " sample)."
    )
  elif status == "partial_window":
    print(
        "\n[FINOPS ADVISORY - LOG ANALYTICS] Log Analytics has"
        f" {days_available:.1f} days of indexed data."
    )
    print(
        "  - Action for Agent: Stratified flow used (14-day macro severity"
        f" from GCM + {days_available:.1f}-day fine-grained sample). Note this"
        " sample window in reports."
    )
  else:
    print(
        "\n[FINOPS ADVISORY - LOG ANALYTICS] Full Log Analytics data available"
        " (>= 14 days). All breakdowns powered by SQL analytics."
    )
perf.py 1.6 KB
"""Stage timing for the collection pipeline.

Stages run concurrently, so the stage total exceeds the elapsed wall clock.
"""

import contextlib
import threading
import time
from typing import Any, Dict, Iterator, List


class StageTimer:
  """Records wall-clock durations for named pipeline stages. Thread safe."""

  def __init__(self) -> None:
    self._lock = threading.Lock()
    self._stages: List[Dict[str, Any]] = []
    self._t0 = time.monotonic()

  @contextlib.contextmanager
  def stage(self, name: str) -> Iterator[None]:
    """Times the enclosed block, recording it even when it raises."""
    start = time.monotonic()
    try:
      yield
    finally:
      end = time.monotonic()
      with self._lock:
        self._stages.append({
            "stage": name,
            "seconds": round(end - start, 2),
            "started_at": round(start - self._t0, 2),
        })

  def profile(self) -> Dict[str, Any]:
    """Returns the recorded stages, slowest first, plus elapsed wall clock."""
    with self._lock:
      stages = sorted(self._stages, key=lambda s: s["seconds"], reverse=True)
    return {
        "elapsed_seconds": round(time.monotonic() - self._t0, 2),
        "stages": stages,
    }

  def render(self) -> str:
    """Formats the profile as a table for stdout."""
    profile = self.profile()
    lines = [
        f"[COLLECTION PROFILE] elapsed {profile['elapsed_seconds']:.1f}s",
        f"  {'stage':<42} {'seconds':>8}  {'start':>7}",
    ]
    for entry in profile["stages"]:
      lines.append(
          f"  {entry['stage']:<42} {entry['seconds']:>8.2f}"
          f"  {entry['started_at']:>7.2f}"
      )
    return "\n".join(lines)
pricing.py 17.2 KB
"""Per-SKU Cloud Logging ingestion pricing.

Log Storage: $0.50/GiB, first 50 GiB per project per month free.
Vended Logs Storage: $0.25/GiB, no free tier (VPC Flow, Firewall, Cloud NAT).

A `PriceBook` prices bills and savings per SKU, falling back to one blended
rate when telemetry's vended share disagrees with the invoice's.
"""

import dataclasses
import datetime
from typing import Any, Dict, Iterable, Mapping, Optional, Tuple
import urllib.parse

from constants import billable_gib
from constants import FREE_TIER_GIB_PER_MONTH
from constants import LIST_PRICE_PER_GIB
from constants import PLAUSIBLE_RATE_RANGE_PER_GIB
from constants import price_reduction

LOG_STORAGE = "log_storage"
VENDED = "vended"
BLENDED = "blended"

VENDED_LIST_PRICE_PER_GIB = 0.25

SKU_LABELS = {
    LOG_STORAGE: "Log Storage",
    VENDED: "Vended Logs Storage",
    BLENDED: "All ingestion (blended)",
}

# (list unit price, free GiB per project per month)
SKU_LIST_TERMS = {
    LOG_STORAGE: (LIST_PRICE_PER_GIB, FREE_TIER_GIB_PER_MONTH),
    VENDED: (VENDED_LIST_PRICE_PER_GIB, 0.0),
}

# Log ID suffixes of the vended network logs. The suffix, not the full ID,
# because VPC Flow Logs are written under both `compute.googleapis.com` and
# `networkmanagement.googleapis.com`.
VENDED_LOG_SUFFIXES = frozenset({"vpc_flows", "firewall", "nat_flows"})

# Monitored resource types that carry only vended network logs. Flow and
# firewall logs are written against `gce_subnetwork`; flow logs configured
# through Network Management against `vpc_flow_logs_config`; NAT logs against
# `nat_gateway`.
VENDED_RESOURCE_TYPES = frozenset(
    {"vpc_flow_logs_config", "gce_subnetwork", "nat_gateway"}
)

# Max gap between telemetry's and the invoice's vended share before the
# stream-to-SKU mapping is distrusted. Loose: catches wrong, not noisy.
MAPPING_TOLERANCE_POINTS = 15.0

# A SKU month billing less than this many GiB above its free allotment is too
# small to derive a unit price from; cents rounding dominates.
_MIN_PRICED_GIB = 1.0


def sku_of_description(description: str) -> str:
  """Maps a billing export `sku.description` to a SKU key."""
  return VENDED if "vended" in (description or "").lower() else LOG_STORAGE


def sku_of_log(log_id: str) -> str:
  """Maps a log ID (URL-encoded or not) to the SKU that bills it."""
  suffix = urllib.parse.unquote(log_id or "").rsplit("/", 1)[-1].lower()
  return VENDED if suffix in VENDED_LOG_SUFFIXES else LOG_STORAGE


def sku_of_resource(resource_type: str) -> str:
  """Maps a monitored resource type to the SKU that bills its logs."""
  return VENDED if resource_type in VENDED_RESOURCE_TYPES else LOG_STORAGE


@dataclasses.dataclass
class SkuTerms:
  """One SKU's price, free allotment and share of the monthly baseline."""

  unit_price: float
  free_gib: float
  baseline_gib: float
  price_source: str  # "invoice" or "list"
  price_month: Optional[str] = None

  def month_cost(self, gib: float) -> float:
    return round(billable_gib(gib, self.free_gib) * self.unit_price, 2)

  @property
  def baseline_cost(self) -> float:
    return self.month_cost(self.baseline_gib)

  @property
  def effective_rate(self) -> float:
    """Baseline cost per baseline GiB, free allotment included."""
    if self.baseline_gib <= 0:
      return self.unit_price
    return self.baseline_cost / self.baseline_gib


class PriceBook:
  """Prices ingestion, and reductions in it, per billing SKU."""

  def __init__(
      self,
      skus: Dict[str, SkuTerms],
      mode: str,
      notes: Optional[Iterable[str]] = None,
      mapping_check: Optional[Dict[str, Any]] = None,
  ) -> None:
    self.skus = skus
    self.mode = mode  # "per_sku" or "blended"
    self.notes = list(notes or [])
    self.mapping_check = mapping_check or {}

  # --- construction --------------------------------------------------------

  @classmethod
  def blended(
      cls,
      rate_per_gib: float,
      baseline_gib: float,
      price_source: str = "list",
      notes: Optional[Iterable[str]] = None,
      mapping_check: Optional[Dict[str, Any]] = None,
  ) -> "PriceBook":
    """One rate for every GiB; the fallback when per-SKU is untrusted."""
    return cls(
        {
            BLENDED: SkuTerms(
                unit_price=rate_per_gib,
                free_gib=FREE_TIER_GIB_PER_MONTH,
                baseline_gib=max(0.0, baseline_gib or 0.0),
                price_source=price_source,
            )
        },
        mode="blended",
        notes=notes,
        mapping_check=mapping_check,
    )

  @classmethod
  def from_dict(cls, data: Mapping[str, Any]) -> "PriceBook":
    """Rebuilds a book from its `to_dict()` form (e.g. a saved summary)."""
    skus = {
        key: SkuTerms(
            unit_price=float(v["unit_price_per_gib"]),
            free_gib=float(v["free_gib"]),
            baseline_gib=float(v["baseline_monthly_gib"]),
            price_source=v["price_source"],
            price_month=v["price_month"],
        )
        for key, v in data["skus"].items()
    }
    return cls(
        skus,
        mode=data["mode"],
        notes=data["notes"],
        mapping_check=data["mapping_check"],
    )

  # --- mapping -------------------------------------------------------------

  @property
  def per_sku(self) -> bool:
    return self.mode == "per_sku"

  def sku_for_log(self, log_id: str) -> str:
    return sku_of_log(log_id) if self.per_sku else BLENDED

  def sku_for_resource(self, resource_type: str) -> str:
    return sku_of_resource(resource_type) if self.per_sku else BLENDED

  def terms(self, sku: str) -> SkuTerms:
    if sku in self.skus:
      return self.skus[sku]
    # A stream on a SKU the invoice never billed (e.g. a new firewall log on a
    # project with no vended history) is priced at that SKU's list terms.
    price, free = SKU_LIST_TERMS.get(sku, (LIST_PRICE_PER_GIB, 0.0))
    return SkuTerms(price, free, 0.0, "list")

  # --- pricing -------------------------------------------------------------

  @property
  def baseline_gib(self) -> float:
    return sum(t.baseline_gib for t in self.skus.values())

  @property
  def baseline_cost(self) -> float:
    return round(sum(t.baseline_cost for t in self.skus.values()), 2)

  @property
  def average_rate(self) -> float:
    """Baseline bill per baseline GiB across all SKUs, free tier included.

    For figures that cannot be split by SKU (e.g. a week's total volume), so
    they sum to the monthly bill.
    """
    gib = self.baseline_gib
    return self.baseline_cost / gib if gib > 0 else 0.0

  def collapse(self, gib_by_sku: Mapping[str, float]) -> Dict[str, float]:
    """Re-keys per-SKU volumes onto this book's SKUs."""
    # A blended book prices every GiB on its one SKU, so per-SKU input (e.g.
    # invoiced daily GiB) is summed onto it rather than priced at list terms.
    if self.per_sku:
      return dict(gib_by_sku)
    return {BLENDED: sum(gib_by_sku.values())}

  def month_cost(self, gib_by_sku: Mapping[str, float]) -> float:
    """Returns a whole month's bill for the given per-SKU volumes."""
    return round(
        sum(self.terms(k).month_cost(g) for k, g in gib_by_sku.items()), 2
    )

  def saving(self, removed_by_sku: Mapping[str, float]) -> float:
    """Returns the monthly saving from removing per-SKU monthly GiB."""
    # Each SKU is priced as the difference of two bills, so the free tier
    # applies only where it exists.
    total = 0.0
    for sku, removed in removed_by_sku.items():
      if not removed:
        continue
      terms = self.terms(sku)
      # Clamped to the SKU's own baseline by `price_reduction`: a saving can
      # never exceed what that SKU is billed.
      total += price_reduction(
          removed_gib=removed,
          baseline_monthly_gib=terms.baseline_gib,
          rate_per_gib=terms.unit_price,
          free_tier_gib=terms.free_gib,
      )
    return round(total, 2)

  def split_by_logs(
      self, total_gib: float, weights: Iterable[Tuple[str, float]]
  ) -> Dict[str, float]:
    """Splits `total_gib` across SKUs in proportion to per-log weights.

    Args:
      total_gib: Monthly GiB to split.
      weights: `(log_id, weight)` pairs, e.g. each claimed stream's bytes.

    Returns:
      Monthly GiB keyed by SKU. All on one SKU when no weights are given.
    """
    by_sku: Dict[str, float] = {}
    for log_id, weight in weights:
      if weight and weight > 0:
        sku = self.sku_for_log(log_id)
        by_sku[sku] = by_sku.get(sku, 0.0) + weight
    denom = sum(by_sku.values())
    if denom <= 0:
      return {self.sku_for_log(""): total_gib}
    return {k: total_gib * w / denom for k, w in by_sku.items()}

  def saving_for_logs(
      self, total_gib: float, weights: Iterable[Tuple[str, float]]
  ) -> float:
    return self.saving(self.split_by_logs(total_gib, weights))

  def pct_of_spend(self, saving_usd: float) -> float:
    cost = self.baseline_cost
    return round(100.0 * saving_usd / cost, 2) if cost > 0 else 0.0

  def service_cost(self, resource_type: str, monthly_gib: float) -> float:
    """Estimated monthly dollars for one service at its SKU's effective rate."""
    # The effective rate spreads the Log Storage free tier across all its GiB.
    terms = self.terms(self.sku_for_resource(resource_type))
    return round(max(0.0, monthly_gib) * terms.effective_rate, 2)

  # --- publication ---------------------------------------------------------

  def formula_terms(self) -> str:
    """Human-readable per-SKU terms, for Prove It and evidence prose."""
    parts = []
    for sku, t in self.skus.items():
      free = (
          f", first {t.free_gib:g} GiB free" if t.free_gib else ", no free tier"
      )
      parts.append(f"{SKU_LABELS.get(sku, sku)} ${t.unit_price:.4g}/GiB{free}")
    return "; ".join(parts)

  def to_dict(self) -> Dict[str, Any]:
    return {
        "mode": self.mode,
        "baseline_monthly_gib": round(self.baseline_gib, 2),
        "baseline_monthly_cost_usd": self.baseline_cost,
        "skus": {
            key: {
                "label": SKU_LABELS.get(key, key),
                "unit_price_per_gib": round(t.unit_price, 4),
                "free_gib": t.free_gib,
                "baseline_monthly_gib": round(t.baseline_gib, 2),
                "baseline_monthly_cost_usd": t.baseline_cost,
                "effective_rate_per_gib": round(t.effective_rate, 4),
                "price_source": t.price_source,
                "price_month": t.price_month,
            }
            for key, t in self.skus.items()
        },
        "vended_resource_types": sorted(VENDED_RESOURCE_TYPES),
        "mapping_check": self.mapping_check,
        "notes": self.notes,
    }


# ==============================================================================
# Construction from the billing export
# ==============================================================================


def invoiced_unit_prices(
    monthly_costs: Mapping[str, Mapping[str, Any]],
    current_month: Optional[str] = None,
) -> Dict[str, Tuple[float, str, Optional[str]]]:
  """Derives each SKU's unit price from the invoice, else its list price.

  Price is raw (pre-credit) cost over billable GiB (after the free tier), so
  the free tier is not counted twice when pricing savings.

  Args:
    monthly_costs: `billing.query_logging_billing_costs()["monthly_costs"]`.
    current_month: The in-progress month, used only when no complete month
      priced a SKU.

  Returns:
    `{sku: (unit_price, "invoice" | "list", month or None)}` for both SKUs.
  """
  low, high = PLAUSIBLE_RATE_RANGE_PER_GIB
  prices: Dict[str, Tuple[float, str, Optional[str]]] = {}
  months = sorted(monthly_costs, reverse=True)
  # Complete months first; the current month only as a last resort.
  ordered = [m for m in months if m != current_month] + [
      m for m in months if m == current_month
  ]
  for sku, (list_price, free) in SKU_LIST_TERMS.items():
    for month in ordered:
      entry = monthly_costs[month]["ingestion_by_sku"].get(sku)
      if not entry:
        continue
      billable = billable_gib(entry["gib"], free)
      if billable < _MIN_PRICED_GIB:
        continue
      unit = entry["raw_cost_usd"] / billable
      if low <= unit <= high:
        prices[sku] = (round(unit, 4), "invoice", month)
        break
    prices.setdefault(sku, (list_price, "list", None))
  return prices


def last_complete_invoice_day(now: datetime.datetime) -> datetime.date:
  """The latest invoice day fully billed by `now`."""
  # Invoice days are Pacific, so day D is complete at D+1 08:00 UTC.
  return (now - datetime.timedelta(days=1, hours=8)).date()


def complete_days(
    daily: Optional[Mapping[str, float]], start: str, now: datetime.datetime
) -> Dict[str, float]:
  """The `{YYYY-MM-DD: value}` invoice days from `start` that are complete."""
  last = last_complete_invoice_day(now).isoformat()
  return {d: v for d, v in (daily or {}).items() if start <= d <= last}


def invoiced_sku_shares(
    daily_gib_by_sku: Optional[Mapping[str, Mapping[str, float]]],
    window_start: str,
    now: datetime.datetime,
) -> Optional[Dict[str, float]]:
  """Returns each SKU's share of invoiced GiB over complete window days."""
  if not daily_gib_by_sku:
    return None
  sums = {
      sku: sum(complete_days(days, window_start, now).values())
      for sku, days in daily_gib_by_sku.items()
  }
  total = sum(sums.values())
  if total <= 0:
    return None
  return {sku: v / total for sku, v in sums.items() if v > 0}


def telemetry_vended_share(
    bytes_by_stream: Optional[Mapping[Tuple[str, str], float]],
) -> Optional[float]:
  """Returns the share of `byte_count` bytes on streams mapped to Vended."""
  if not bytes_by_stream:
    return None
  total = sum(bytes_by_stream.values())
  if total <= 0:
    return None
  vended = sum(
      v
      for (log_id, _), v in bytes_by_stream.items()
      if sku_of_log(log_id) == VENDED
  )
  return vended / total


def build_price_book(
    baseline_gib: float,
    now: datetime.datetime,
    window_start: str,
    monthly_costs: Optional[Mapping[str, Mapping[str, Any]]] = None,
    daily_gib_by_sku: Optional[Mapping[str, Mapping[str, float]]] = None,
    bytes_by_stream: Optional[Mapping[Tuple[str, str], float]] = None,
) -> PriceBook:
  """Builds the price book every dollar figure in the report is priced from.

  Args:
    baseline_gib: The gross monthly ingestion run rate, all SKUs.
    now: Reference instant; see `last_complete_invoice_day`.
    window_start: First date (`YYYY-MM-DD`) of the run-rate window.
    monthly_costs: Invoiced months, carrying `ingestion_by_sku`.
    daily_gib_by_sku: Invoiced ingestion GiB per SKU per Pacific day.
    bytes_by_stream: `byte_count` bytes keyed by `(log_id, severity)`, used to
      check the stream-to-SKU mapping and, without an invoice, to split the
      baseline.

  Returns:
    A per-SKU `PriceBook`, or a blended one with the reason in `notes`.
  """
  current_month = now.strftime("%Y-%m")
  prices = invoiced_unit_prices(monthly_costs or {}, current_month)
  invoice_shares = invoiced_sku_shares(daily_gib_by_sku, window_start, now)
  tele_vended = telemetry_vended_share(bytes_by_stream)

  check: Dict[str, Any] = {
      "invoice_vended_share_pct": (
          round(100.0 * invoice_shares.get(VENDED, 0.0), 1)
          if invoice_shares
          else None
      ),
      "telemetry_vended_share_pct": (
          round(100.0 * tele_vended, 1) if tele_vended is not None else None
      ),
  }

  if invoice_shares:
    shares = invoice_shares
    split_source = "billing_export"
  elif tele_vended is not None:
    shares = {VENDED: tele_vended, LOG_STORAGE: 1.0 - tele_vended}
    split_source = "cloud_monitoring_byte_count"
  else:
    return PriceBook.blended(
        LIST_PRICE_PER_GIB,
        baseline_gib,
        notes=["No per-SKU volume available; priced at one blended rate."],
        mapping_check=check,
    )
  check["split_source"] = split_source

  if invoice_shares and tele_vended is not None:
    gap = abs(100.0 * invoice_shares.get(VENDED, 0.0) - 100.0 * tele_vended)
    check["gap_points"] = round(gap, 1)
    check["passed"] = gap <= MAPPING_TOLERANCE_POINTS
    if not check["passed"]:
      # The baseline split holds but per-stream SKUs are untrusted, so price
      # every GiB at one blended rate.
      billable = billable_gib(baseline_gib)
      invoiced_cost = sum(
          billable_gib(baseline_gib * shares.get(k, 0.0), SKU_LIST_TERMS[k][1])
          * prices[k][0]
          for k in SKU_LIST_TERMS
      )
      rate = invoiced_cost / billable if billable > 0 else LIST_PRICE_PER_GIB
      return PriceBook.blended(
          round(rate, 4),
          baseline_gib,
          price_source="invoice",
          notes=[
              f"Telemetry puts {check['telemetry_vended_share_pct']}% of"
              " volume on vended network logs but the invoice bills"
              f" {check['invoice_vended_share_pct']}% as Vended Logs Storage;"
              " the stream-to-SKU mapping was not trusted, so every GiB is"
              " priced at one blended rate."
          ],
          mapping_check=check,
      )

  skus = {}
  for sku, (price, source, month) in prices.items():
    share = shares.get(sku, 0.0)
    if share <= 0 and sku != LOG_STORAGE:
      continue
    skus[sku] = SkuTerms(
        unit_price=price,
        free_gib=SKU_LIST_TERMS[sku][1],
        baseline_gib=baseline_gib * share,
        price_source=source,
        price_month=month,
    )
  return PriceBook(skus, mode="per_sku", mapping_check=check)
provenance.py 56.4 KB
"""Builds the "Prove It" provenance for every headline number in the report.

Pure function of the summary dict: each claim gets its formula, sources with
console links, known differences, and checks that `verify_claim.py` re-runs.
Queries are literal text (no `@params`). SQL and PromQL checks run exactly the
query their drawer shows; stream checks use the Monitoring filter the collector
measured with.
"""

import datetime
import json
import re
from typing import Any, Dict, List, Optional, Sequence, Tuple
import urllib.parse

from actions import SOURCE_LEVER
from constants import bare_table_ref
from constants import BILLED_BYTES_METRIC
from constants import BYTE_COUNT_METRIC
from constants import BYTES_PER_GIB
from constants import DAYS_PER_MONTH
from constants import DEFAULT_SAMPLE_DAYS
from constants import DEFAULT_TELEMETRY_LOOKBACK_DAYS
from constants import INGESTION_PRICING_UNIT
from constants import INVOICE_TIMEZONE
from constants import LOGGING_SCOPE_SQL
from constants import LOGGING_SERVICE_ID
from constants import LOGGING_SERVICE_NAME
from constants import MONITORING_RETENTION_DAYS
from constants import PAYLOAD_BYTES_SQL
from constants import quote_table_ref
from pricing import BLENDED
from pricing import last_complete_invoice_day
from pricing import LOG_STORAGE
from pricing import PriceBook
from pricing import SKU_LABELS
from pricing import sku_of_resource
from pricing import SkuTerms
from pricing import VENDED
from pricing import VENDED_LOG_SUFFIXES

CONSOLE = "https://console.cloud.google.com"
LOGGING_PRICING_URL = "https://cloud.google.com/stackdriver/pricing"

# Cloud Monitoring's PromQL front end translates a metric type by replacing the
# domain's dots and the first slash; `billing/bytes_ingested` has no labels
# beyond `resource_type` and lives on the `global` monitored resource.
PROMQL_BILLED_BYTES = "logging_googleapis_com:billing_bytes_ingested"
PROMQL_BYTE_COUNT = "logging_googleapis_com:byte_count"

# Resource types with no PromQL schema ("no monitored resource schema found");
# streams on these are proven with a Monitoring API filter instead.
PROMQL_UNSUPPORTED_RESOURCES = frozenset({"vpc_flow_logs_config"})

# Tolerances for the live re-run. Complete invoice months should agree to the
# cent; recent invoice days still receive late rows; metric figures move with
# late-arriving points.
TOL_INVOICE_PCT = 1.0
TOL_INVOICE_RECENT_PCT = 5.0
TOL_SHARE_POINTS = 2.0
TOL_METRIC_PCT = 10.0
TOL_METRIC_TOTAL_PCT = 3.0

# Streams listed per claim in the drawer; the live check still covers all.
MAX_STREAM_SOURCES = 10

_BILLING_ACCOUNT_RE = re.compile(
    r"gcp_billing_export(?:_resource)?_v1_([0-9A-F]{6})_([0-9A-F]{6})_([0-9A-F]{6})",
    re.IGNORECASE,
)

_VENDED_LOGS = ", ".join(sorted(VENDED_LOG_SUFFIXES))

# Drawer prose shared by several claims, stated once.
_SKU_MAPPING = (
    f"Streams bill by log name: {_VENDED_LOGS} as {SKU_LABELS[VENDED]},"
    f" everything else as {SKU_LABELS[LOG_STORAGE]}."
)
_LIST_PRICES = (
    "List prices: committed-use discounts, negotiated rates and credits are"
    " not applied."
)
_LATE_POINTS = "Late-arriving metric points can shift a re-measured value."
_METRIC_LOW = (
    "The metric under-reports on some days (see the notice at the top of the"
    " report)."
)
_PACIFIC_NOTE = (
    "Days and months are Pacific usage dates, as Cloud Billing closes a month;"
    " the invoice view groups by invoice month, which can include late usage"
    " from the month before."
)
_TO_GIB = "÷ 2^30 for GiB"
_METRICS_EXPLORER = "Open Metrics Explorer"


# ==============================================================================
# Small helpers
# ==============================================================================


def _money(v: Optional[float]) -> str:
  return "—" if v is None else f"${v:,.2f}"


def _gib(v: Optional[float]) -> str:
  return "—" if v is None else f"{v:,.2f} GiB"


def _label(sku: str) -> str:
  return SKU_LABELS.get(sku, sku)


def _price_term(gib: float, t: SkuTerms) -> str:
  """One SKU's monthly bill as arithmetic: max(0, GiB − free) × price."""
  if t.free_gib:
    return f"max(0, {gib:,.2f} − {t.free_gib:g}) × ${t.unit_price:g}"
  return f"{gib:,.2f} × ${t.unit_price:g}"


def _utc_days(start: datetime.date, end: datetime.date) -> str:
  """A [start, end) metric window as inclusive UTC days."""
  return f"{start} to {end - datetime.timedelta(days=1)} (UTC)"


def billing_account_from_table(table: Optional[str]) -> Optional[str]:
  """Recovers `XXXXXX-XXXXXX-XXXXXX` from a standard export table name."""
  m = _BILLING_ACCOUNT_RE.search(table or "")
  return "-".join(g.upper() for g in m.groups()) if m else None


def _utc_midnight(d: datetime.date) -> str:
  return f"{d.isoformat()}T00:00:00Z"


def _month_bounds(month: str) -> Tuple[datetime.date, datetime.date]:
  first = datetime.date(int(month[:4]), int(month[5:7]), 1)
  nxt = (first + datetime.timedelta(days=32)).replace(day=1)
  return first, nxt - datetime.timedelta(days=1)


def _source(
    kind: str,
    name: str,
    role: str,
    steps: List[str],
    query: Optional[str] = None,
    language: Optional[str] = None,
    url: Optional[str] = None,
    label: Optional[str] = None,
) -> Dict[str, Any]:
  """One "check it yourself" entry in a claim's drawer."""
  return {
      "name": name,
      "role": role,
      "kind": kind,
      "language": language,
      "query": query,
      "console": {"label": label, "url": url} if url else None,
      "steps": steps,
  }


def _check(
    kind: str, label: str, expect: Dict[str, Any], **fields: Any
) -> Dict[str, Any]:
  """One live re-measurement `verify_claim.py` runs."""
  return {"kind": kind, "label": label, "expect": expect, **fields}


# ==============================================================================
# Console links
# ==============================================================================


def bigquery_url(project: str) -> str:
  # The BigQuery console has no supported parameter that pre-fills a query,
  # so this opens the editor in the right project and the SQL is copied.
  return f"{CONSOLE}/bigquery?project={urllib.parse.quote(project)}"


def billing_reports_url(
    account: Optional[str], project: str, start: str, end: str
) -> Optional[str]:
  """Cloud Billing Reports, filtered to Cloud Logging for one project."""
  if not account:
    return None
  state = ";".join([
      "timeRange=CUSTOM_RANGE",
      f"from={start}",
      f"to={end}",
      f"projects={project}",
      f"products=services%2F{LOGGING_SERVICE_ID}",
      "grouping=GROUP_BY_SKU",
  ])
  return f"{CONSOLE}/billing/{account}/reports;{state}?project={project}"


def metrics_explorer_url(
    project: str, promql: Optional[str] = None, days: int = 0
) -> str:
  """Metrics Explorer, with `promql` pre-filled over `days` days if given."""
  url = f"{CONSOLE}/monitoring/metrics-explorer?project={urllib.parse.quote(project)}"
  if not promql:
    return url
  # `pageState` is the console's own serialisation and is not a documented
  # contract; the PromQL is always offered for copying beside this link.
  state = {
      "xyChart": {
          "dataSets": [{
              "timeSeriesQuery": {
                  "prometheusQuery": promql,
                  "unitOverride": "",
                  "outputFullDuration": False,
              },
              "plotType": "STACKED_BAR",
              "targetAxis": "Y1",
          }],
          "chartOptions": {"mode": "COLOR"},
      },
      "timeSelection": {"timeRange": f"{days}d"},
  }
  return (
      f"{url}&pageState="
      f"{urllib.parse.quote(json.dumps(state, separators=(',', ':')))}"
  )


def logs_explorer_url(project: str, query: str, duration: str = "P14D") -> str:
  return (
      f"{CONSOLE}/logs/query;query={urllib.parse.quote(query, safe='')};"
      f"duration={duration}?project={urllib.parse.quote(project)}"
  )


def log_analytics_url(project: str) -> str:
  return f"{CONSOLE}/logs/analytics?project={urllib.parse.quote(project)}"


def log_router_url(project: str) -> str:
  return f"{CONSOLE}/logs/router?project={urllib.parse.quote(project)}"


# ==============================================================================
# Query text
# ==============================================================================

_CREDITS_SQL = "IFNULL((SELECT SUM(c.amount) FROM UNNEST(credits) c), 0)"
_INGESTION_SQL = f"LOWER(usage.pricing_unit) = '{INGESTION_PRICING_UNIT}'"
_PACIFIC_DAY_SQL = f"DATE(usage_start_time, '{INVOICE_TIMEZONE}')"
_PAYLOAD_SQL = " ".join(PAYLOAD_BYTES_SQL.split())


def _billing_from(
    table: str,
    project_id: str,
    start: datetime.date,
    end: datetime.date,
    ingestion_only: bool = False,
) -> str:
  """FROM/WHERE for one project's Cloud Logging rows on Pacific days."""
  scope = LOGGING_SCOPE_SQL.format(
      service_name=f"'{LOGGING_SERVICE_NAME}'",
      service_id=f"'{LOGGING_SERVICE_ID}'",
      project_id=f"'{project_id}'",
  )
  return (
      f"FROM {quote_table_ref(table)}\nWHERE {scope}\n"
      + (f"  AND {_INGESTION_SQL}\n" if ingestion_only else "")
      + f"  AND {_PACIFIC_DAY_SQL} BETWEEN '{start}' AND '{end}'"
  )


def billing_month_sql(table: str, project_id: str, month: str) -> str:
  """One month's Cloud Logging spend and ingestion, exactly as collected."""
  # The month total (sku = NULL) sorts first, so the live check reads row one.
  first, last = _month_bounds(month)
  return f"""-- Cloud Logging spend for {project_id}, {month} (Pacific usage date).
-- The first row (sku = NULL) is the month total.
SELECT
  sku.description AS sku,
  ROUND(SUM(cost), 2) AS raw_cost,
  ROUND(SUM({_CREDITS_SQL}), 2) AS credits,
  ROUND(SUM(cost + {_CREDITS_SQL}), 2) AS net_cost,
  ROUND(SUM(IF({_INGESTION_SQL}, usage.amount_in_pricing_units, 0)), 2) AS ingested_gib
{_billing_from(table, project_id, first, last)}
GROUP BY ROLLUP(sku)
ORDER BY sku IS NULL DESC, net_cost DESC"""


def billing_unit_price_sql(table: str, project_id: str, month: str) -> str:
  """Per-SKU unit prices, separating free-tier rows from charged ones."""
  first, last = _month_bounds(month)
  return f"""-- What each Cloud Logging SKU actually charges per GiB, {month}
SELECT
  sku.description AS sku,
  ROUND(SUM(usage.amount_in_pricing_units), 2) AS gib,
  ROUND(SUM(IF(cost = 0, usage.amount_in_pricing_units, 0)), 2) AS free_gib,
  ROUND(SAFE_DIVIDE(SUM(IF(cost > 0, cost, 0)),
                    SUM(IF(cost > 0, usage.amount_in_pricing_units, 0))), 4) AS unit_price
{_billing_from(table, project_id, first, last, ingestion_only=True)}
GROUP BY sku
ORDER BY gib DESC"""


def billing_daily_gib_sql(
    table: str, project_id: str, start: datetime.date, end: datetime.date
) -> str:
  return f"""-- Invoiced ingestion per Pacific day, {start} to {end} (complete days only)
SELECT
  COUNT(*) AS days,
  ROUND(SUM(gib), 2) AS total_gib,
  ROUND(AVG(gib), 4) AS avg_daily_gib,
  ROUND(AVG(gib) * {DAYS_PER_MONTH:g}, 2) AS monthly_run_rate_gib
FROM (
  SELECT {_PACIFIC_DAY_SQL} AS d, SUM(usage.amount_in_pricing_units) AS gib
  {_billing_from(table, project_id, start, end, ingestion_only=True)}
  GROUP BY d
)"""


def billing_sku_run_rate_sql(
    table: str, project_id: str, start: datetime.date, end: datetime.date
) -> str:
  """The baseline run rate split by SKU, as the price book splits it."""
  return f"""-- Invoiced ingestion per SKU, Pacific days {start} to {end} (complete days only)
WITH daily AS (
  SELECT sku.description AS sku, {_PACIFIC_DAY_SQL} AS d,
         SUM(usage.amount_in_pricing_units) AS gib
  {_billing_from(table, project_id, start, end, ingestion_only=True)}
  GROUP BY sku, d
)
SELECT
  sku,
  ROUND(SUM(gib), 2) AS total_gib,
  ROUND(SUM(gib) / (SELECT COUNT(DISTINCT d) FROM daily) * {DAYS_PER_MONTH:g}, 2)
    AS monthly_run_rate_gib
FROM daily
GROUP BY sku
ORDER BY total_gib DESC"""


def promql_billed(days: int, by_service: bool = True) -> str:
  """Billed bytes over `days`, per resource type or as one total."""
  inner = (
      f'increase({PROMQL_BILLED_BYTES}{{monitored_resource="global"}}[{days}d])'
  )
  return f"sum by (resource_type) ({inner})" if by_service else f"sum({inner})"


def monitoring_vended_streams_filter() -> str:
  """`byte_count` filter for Vended Logs Storage streams, by log ID suffix."""
  suffixes = "|".join(sorted(VENDED_LOG_SUFFIXES))
  return (
      f'metric.type = "{BYTE_COUNT_METRIC}" AND metric.label.log ='
      f' monitoring.regex.full_match(".*/({suffixes})")'
  )


def promql_stream(
    resource: str, log_id: str, days: int, severity: Optional[str] = None
) -> str:
  sev = f', severity="{severity}"' if severity and severity != "*" else ""
  return (
      f"sum by (log, severity) (increase({PROMQL_BYTE_COUNT}"
      f'{{monitored_resource="{resource}", log="{log_id}"{sev}}}[{days}d]))'
  )


def monitoring_stream_filter(
    log_id: str, severity: Optional[str] = None
) -> str:
  # No `resource.type`: some resources reject it and the collector never used
  # it.
  flt = f'metric.type = "{BYTE_COUNT_METRIC}" AND metric.label.log = "{log_id}"'
  if severity and severity != "*":
    flt += f' AND metric.label.severity = "{severity}"'
  return flt


def severity_share_sql(table: str, start: str, end: str) -> str:
  return f"""-- Share of log content bytes by severity, {start} to {end}
SELECT
  COALESCE(severity, 'DEFAULT') AS severity,
  SUM({_PAYLOAD_SQL}) AS content_bytes,
  ROUND(100 * SUM({_PAYLOAD_SQL})
        / SUM(SUM({_PAYLOAD_SQL})) OVER (), 2) AS share_pct
FROM `{table}`
WHERE timestamp BETWEEN TIMESTAMP('{start}') AND TIMESTAMP('{end}')
GROUP BY severity
ORDER BY content_bytes DESC"""


# ==============================================================================
# Claim builders
# ==============================================================================


class _Ctx:
  """Everything the claim builders share, resolved once."""

  def __init__(self, summary: Dict[str, Any]):
    self.s = summary
    self.project = summary["project_id"]
    now = datetime.datetime.fromisoformat(
        summary["last_updated"].replace("Z", "+00:00")
    )
    self.now = now if now.tzinfo else now.replace(tzinfo=datetime.timezone.utc)
    bm = summary["billing_metadata"]
    self.invoiced = bm["invoiced"]
    self.table = bm["table_name"] and bare_table_ref(bm["table_name"])
    self.billing_project = self.table.split(".")[0] if self.table else None
    self.account = billing_account_from_table(self.table)
    self.cross_project = bool(
        self.billing_project and self.billing_project != self.project
    )
    self.monthly = summary["monthly_aggregations"]
    self.ext = summary["extraneous_spend"]
    self.actions = summary["reduction_actions"]["actions"]
    # Absent when the floor could not be measured.
    self.basis = self.ext.get("basis", {})
    self.window = int(self.basis.get("window_days", DEFAULT_SAMPLE_DAYS))
    self.calibration = self.basis.get("byte_count_to_billed_calibration", 1.0)
    self.t30 = summary["trailing_30d_summary"]
    self.book = PriceBook.from_dict(summary["pricing"])
    self.per_sku = self.book.per_sku
    # A blended book's one rate, free tier spread across its GiB, as the
    # report's tables price it.
    self.rate = round(self.book.average_rate, 4)
    # log_id -> resource types it was seen on, for PromQL's exact-resource rule.
    self.log_resources: Dict[str, List[str]] = {}
    # Present only when the Log Analytics breakdown ran.
    top = summary.get("granular_analytics", {}).get("top_log_names", {})
    for resource, rows in top.items():
      for row in rows:
        lid = row["log_id"]
        if resource not in self.log_resources.setdefault(lid, []):
          self.log_resources[lid].append(resource)
    # No invoice: every volume is the billed-bytes metric and every dollar a
    # list-price estimate, so claims must not borrow the invoiced wording.
    self.telemetry = (
        not self.invoiced
        and self.t30.get("volume_basis") == "cloud_monitoring_metric"
    )

  # --- windows --------------------------------------------------------------

  def utc_window(self, days: int) -> Tuple[datetime.date, datetime.date]:
    """(first day, exclusive end) of a metric window, in UTC days."""
    # The collector floors to UTC midnight, so today is excluded.
    end = self.now.astimezone(datetime.timezone.utc).date()
    return end - datetime.timedelta(days=days), end

  @property
  def invoice_window(self) -> Tuple[datetime.date, datetime.date]:
    """The trailing run-rate window over complete invoice days."""
    start = (
        self.now - datetime.timedelta(days=DEFAULT_TELEMETRY_LOOKBACK_DAYS)
    ).date()
    return start, last_complete_invoice_day(self.now)

  # --- wording that depends on where the numbers came from -----------------

  @property
  def volume_basis(self) -> str:
    """Where the monthly baseline volume came from, for formula text."""
    days = DEFAULT_TELEMETRY_LOOKBACK_DAYS
    if self.invoiced:
      return f"trailing {days} days of invoiced ingestion"
    return f"trailing {days} days of {BILLED_BYTES_METRIC}; no billing export"

  @property
  def priced_against(self) -> str:
    if self.invoiced:
      return " invoiced baseline."
    return " estimated baseline at list price (no billing export)."

  # --- per-SKU pricing, shared by every dollar claim ------------------------

  def _split_basis(self) -> str:
    check = self.book.mapping_check
    if check.get("split_source") == "billing_export":
      return "split by the SKU the invoice billed it under"
    share = check.get("telemetry_vended_share_pct")
    return f"split by SKU in proportion to byte_count on the {_VENDED_LOGS}" + (
        f" streams ({share}% of measured volume)" if share is not None else ""
    )

  def baseline_formula(self) -> List[str]:
    """The per-SKU baseline bill, as arithmetic with the real inputs."""
    book = self.book
    skus = book.skus.items()
    list_priced = all(t.price_source == "list" for t in book.skus.values())
    return [
        f"Baseline: {_gib(book.baseline_gib)}/month ({self.volume_basis}),"
        f" {self._split_basis()}: "
        + ", ".join(f"{_label(k)} {_gib(t.baseline_gib)}" for k, t in skus)
        + ".",
        "  Bill = "
        + " + ".join(_price_term(t.baseline_gib, t) for _, t in skus)
        + f" = {_money(book.baseline_cost)}/month"
        + (" at list prices." if list_priced else "."),
    ]

  def saving_formula(
      self, gib_by_sku: Dict[str, float], usd: Optional[float]
  ) -> List[str]:
    """One line per SKU showing how a saving was priced."""
    lines = [f"Saving {_money(usd)}/mo = the sum over the SKUs it removes:"]
    for sku, gib in sorted(gib_by_sku.items()):
      if not gib:
        continue
      t = self.book.terms(sku)
      part = _money(self.book.saving({sku: gib}))
      base = _gib(t.baseline_gib)
      if t.free_gib:
        lines.append(
            f"  • {_label(sku)}: (billable({base}) − billable({base} −"
            f" {_gib(gib)})) × ${t.unit_price:g}/GiB = {part}, billable(x) ="
            f" max(0, x − {t.free_gib:g} GiB)."
        )
      else:
        lines.append(
            f"  • {_label(sku)}: {_gib(gib)} × ${t.unit_price:g}/GiB = {part}."
        )
    return lines

  def pricing_sources(self) -> List[Dict[str, Any]]:
    """The sources that reproduce the unit prices behind a dollar figure."""
    if not self.invoiced:
      if not self.telemetry:
        return []
      return [
          _source(
              "pricing",
              "Cloud Logging list prices",
              "The unit prices and free tier behind every dollar figure",
              [f"Prices applied: {self.book.formula_terms()}."],
              url=LOGGING_PRICING_URL,
              label="Open the pricing page",
          )
      ]
    if not self.per_sku:
      return []
    start, end = self.invoice_window
    sources = [
        self.billing_source(
            "Baseline split by SKU",
            billing_sku_run_rate_sql(self.table, self.project, start, end),
            "How much of the monthly volume each SKU bills",
        )
    ]
    for month in sorted(
        {t.price_month for t in self.book.skus.values() if t.price_month}
    ):
      sources.append(
          self.billing_source(
              f"Per-SKU unit prices, {month}",
              billing_unit_price_sql(self.table, self.project, month),
              "What each SKU charged per GiB, free-tier rows separated",
          )
      )
    return sources

  def rate_desc(self) -> str:
    """The rate behind a table's estimated dollars, to follow "GiB × "."""
    if not self.per_sku:
      kind = "the invoiced blended rate" if self.invoiced else "list price"
      return f"${self.rate}/GiB ({kind})."
    rates = ", ".join(
        f"{_label(k)} ${t.effective_rate:.4f}/GiB"
        for k, t in sorted(self.book.skus.items())
    )
    return (
        f"its SKU's effective rate: {rates} (monthly bill ÷ monthly GiB, so"
        " the free tier is spread across the SKU's GiB)."
    )

  def pricing_differences(self) -> List[str]:
    """Why a priced figure may differ from the console, per pricing mode."""
    if not self.per_sku:
      return self.book.notes or [
          "One blended rate across SKUs; Vended Logs Storage streams (e.g. VPC"
          " flow logs) bill at a lower unit price than it assumes."
      ]
    check = self.book.mapping_check
    gap = check.get("gap_points")
    if gap is not None:
      return [
          f"{_SKU_MAPPING} That puts"
          f" {check.get('telemetry_vended_share_pct')}% of measured volume on"
          f" Vended against {check.get('invoice_vended_share_pct')}% on the"
          f" invoice ({gap} points apart)."
      ]
    if not self.invoiced:
      return [
          (
              f"{_SKU_MAPPING} With no billing export, no invoice checks that"
              " split."
          ),
          _LIST_PRICES,
      ]
    return [_SKU_MAPPING]

  # --- sources --------------------------------------------------------------

  def billing_source(self, name: str, sql: str, role: str) -> Dict[str, Any]:
    steps = [
        f"Open BigQuery in project `{self.billing_project}` and paste the SQL."
    ]
    if self.cross_project:
      steps.append(
          f"The export lives in `{self.billing_project}`, not"
          f" `{self.project}`: you need BigQuery Data Viewer on that dataset"
          " and Job User in some project."
      )
    return _source(
        "billing_export",
        name,
        role,
        steps,
        query=sql,
        language="sql",
        url=bigquery_url(self.billing_project or self.project),
        label="Open BigQuery",
    )

  def reports_source(self, month: str) -> Optional[Dict[str, Any]]:
    first, last = _month_bounds(month)
    url = billing_reports_url(
        self.account, self.project, first.isoformat(), last.isoformat()
    )
    if not url:
      return None
    return _source(
        "billing_reports",
        f"Cloud Billing Reports, {month}",
        "Independent cross-check in the console",
        [
            "Pre-filtered to Cloud Logging, this project and the month, by"
            " SKU. Include 'Promotions and others' credits to match the net."
        ],
        url=url,
        label="Open Billing Reports",
    )

  def promql_source(
      self, name: str, promql: str, days: int, role: str, eval_note: str
  ) -> Dict[str, Any]:
    return _source(
        "cloud_monitoring",
        name,
        role,
        ["Metrics Explorer → Code → PromQL, paste the query, Run.", eval_note],
        query=promql,
        language="promql",
        url=metrics_explorer_url(self.project, promql, days),
        label=_METRICS_EXPLORER,
    )

  def daily_bars_source(
      self, name: str, days: int, role: str, step: str
  ) -> Dict[str, Any]:
    """The billed-bytes metric as one stacked bar per day."""
    return self.promql_source(
        name, promql_billed(1), days, role, f"Stacked bars, 1-day step; {step}"
    )

  def telemetry_volume_source(self, role: str) -> Dict[str, Any]:
    """The PromQL that reproduces the trailing 30-day billed total."""
    days = DEFAULT_TELEMETRY_LOOKBACK_DAYS
    start, end = self.utc_window(days)
    return self.promql_source(
        f"Billed bytes, {_utc_days(start, end)}",
        promql_billed(days, by_service=False),
        days,
        role,
        f"Evaluate at {_utc_midnight(end)} so the window is exactly the whole"
        f" UTC days summed. Result is bytes; {_TO_GIB}.",
    )

  def baseline_source(self, name: str, role: str) -> Optional[Dict[str, Any]]:
    """The monthly volume every percentage and saving is taken from."""
    if self.invoiced:
      start, end = self.invoice_window
      return self.billing_source(
          name,
          billing_daily_gib_sql(self.table, self.project, start, end),
          role,
      )
    if self.telemetry:
      return self.telemetry_volume_source(role)
    return None

  def run_rate_check(self, label: str) -> Optional[Dict[str, Any]]:
    """Live check of the monthly run-rate GiB, re-read from its source."""
    run_rate = self.t30.get("monthly_run_rate_gib")
    if run_rate is None:
      return None
    if self.invoiced:
      start, end = self.invoice_window
      return _check(
          "bigquery",
          label,
          {"monthly_run_rate_gib": run_rate},
          project=self.billing_project,
          query=billing_daily_gib_sql(self.table, self.project, start, end),
          tolerance_pct=TOL_INVOICE_RECENT_PCT,
      )
    days_seen = self.t30.get("days_observed")
    if not self.telemetry or not days_seen:
      return None
    days = DEFAULT_TELEMETRY_LOOKBACK_DAYS
    return _check(
        "promql",
        label,
        {"total": run_rate},
        query=promql_billed(days, False),
        time=_utc_midnight(self.utc_window(days)[1]),
        compare="total",
        scale=DAYS_PER_MONTH / days_seen / BYTES_PER_GIB,
        unit="GiB/month",
        tolerance_pct=TOL_METRIC_TOTAL_PCT,
    )

  def stream_sources_and_checks(
      self,
      claims: Sequence[Dict[str, Any]],
      expect_gib: float,
      fraction: float = 1.0,
  ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
    """Sources for the largest streams behind an action, and one live check.

    Args:
      claims: The action's per-stream claims.
      expect_gib: The monthly GiB the check should re-measure.
      fraction: Share of each stream the action claims (e.g. the bytes a lower
        flow-log sampling rate would drop). 1.0 for whole-stream actions.

    Returns:
      (sources, checks). The check covers every stream; the drawer lists the
      `MAX_STREAM_SOURCES` largest.
    """
    role = "Claimed stream volume"
    window, cal = self.window, self.calibration
    start, end = self.utc_window(window)
    scale = (
        f"× {cal:g} (calibration)"
        + (f" × {fraction:g} (claimed share)" if fraction != 1.0 else "")
        + f" × {DAYS_PER_MONTH:g}/{window} {_TO_GIB}/month."
    )
    streams = sorted(
        (c for c in claims if c.get("log_id")),
        key=lambda c: -(c.get("monthly_gib") or 0.0),
    )
    sources: List[Dict[str, Any]] = []
    for claim in streams[:MAX_STREAM_SOURCES]:
      lid = claim["log_id"]
      sev = claim.get("severity") or "*"
      sev_label = f" ({sev})" if sev != "*" else ""
      resources = self.log_resources.get(lid) or []
      if resources and not PROMQL_UNSUPPORTED_RESOURCES.intersection(resources):
        sources += [
            self.promql_source(
                f"{lid} on {resource}{sev_label}",
                promql_stream(resource, lid, window, sev),
                window,
                role,
                f"Evaluate at {_utc_midnight(end)}. Bytes over {window} days;"
                f" {scale}",
            )
            for resource in resources
        ]
        continue
      # PromQL needs an exact resource; the Monitoring filter does not.
      sources.append(
          _source(
              "cloud_monitoring",
              f"{lid}{sev_label}",
              role,
              [
                  (
                      f"Metric = {BYTE_COUNT_METRIC}, this filter, Aggregation"
                      f" = Sum, Alignment = 1 day, {_utc_days(start, end)}."
                  ),
                  f"Sum the daily bars, then {scale}",
              ],
              query=monitoring_stream_filter(lid, sev),
              language="monitoring_filter",
              url=metrics_explorer_url(self.project),
              label=_METRICS_EXPLORER,
          )
      )
    hidden = len(streams) - MAX_STREAM_SOURCES
    if hidden > 0:
      sources.append(
          _source(
              "cloud_monitoring",
              f"…and {hidden} smaller streams",
              role,
              [f"verify_claim.py re-measures all {len(streams)} streams."],
          )
      )
    if not streams:
      return sources, []
    series = [
        {
            "filter": monitoring_stream_filter(c["log_id"], c.get("severity")),
            "log_id": c["log_id"],
        }
        for c in streams
    ]
    return sources, [
        _check(
            "monitoring_sum",
            "Re-measure the claimed streams (Monitoring API)",
            {"total": expect_gib},
            series=series,
            start=_utc_midnight(start),
            end=_utc_midnight(end),
            multiplier=cal * fraction * DAYS_PER_MONTH / window / BYTES_PER_GIB,
            unit="GiB/month",
            tolerance_pct=TOL_METRIC_PCT,
        )
    ]

  def metric_differences(self) -> List[str]:
    """Why a metric-derived figure may differ from a console reading."""
    diffs = [
        (
            "No billing export: this is Cloud Monitoring's"
            f" {BILLED_BYTES_METRIC}, not an invoice. Healthy, it reads a few"
            " percent above the invoice; on some days it reads far below with"
            " no gap to signal it."
        ),
        (
            "Whole UTC days; today is excluded. PromQL increase() extrapolates"
            " slightly at the window edges."
        ),
    ]
    days_seen = self.t30.get("days_observed")
    lookback = DEFAULT_TELEMETRY_LOOKBACK_DAYS
    if days_seen and days_seen < lookback:
      diffs.append(
          f"Only {days_seen} of {lookback} days had data, so the daily average"
          f" divides by {days_seen}."
      )
    return diffs


def _claim(
    cid: str,
    title: str,
    value: str,
    summary_line: str,
    formula: List[str],
    sources: Sequence[Optional[Dict[str, Any]]],
    differences: List[str],
    checks: Sequence[Optional[Dict[str, Any]]],
    see_also: Sequence[str] = (),
) -> Dict[str, Any]:
  return {
      "id": cid,
      "title": title,
      "value": value,
      "summary": summary_line,
      "formula": formula,
      "sources": [s for s in sources if s],
      "differences": differences,
      "checks": [c for c in checks if c],
      # Claims this one is built from; each proves its own inputs.
      "see_also": list(see_also),
  }


def _invoice_check(
    c: _Ctx, label: str, month: str, expect: Dict[str, Any], tol: float
) -> Dict[str, Any]:
  return _check(
      "bigquery",
      label,
      expect,
      project=c.billing_project,
      query=billing_month_sql(c.table, c.project, month),
      tolerance_pct=tol,
  )


def _latest_invoiced_month(c: _Ctx) -> Optional[Dict[str, Any]]:
  """The latest complete month, if the invoice covers it."""
  # A month estimated from telemetry before the export began has no invoice to
  # prove it against.
  month = c.s["latest_complete_month"]
  if not c.invoiced or not month:
    return None
  m = c.monthly[month]
  return m if m["data_source"] == "actual_bq_billing" else None


def _latest_complete_spend(c: _Ctx) -> Optional[Dict[str, Any]]:
  """Proves the last complete invoice month's net Cloud Logging spend."""
  m = _latest_invoiced_month(c)
  if not m:
    return None
  month = c.s["latest_complete_month"]
  sql = billing_month_sql(c.table, c.project, month)
  return _claim(
      "latest_complete_spend",
      "Latest Complete Spend",
      f"{_money(m['net_cost_usd'])} · {month}",
      "Read directly from your Cloud Billing export; no estimate.",
      [
          (
              f"{_money(m['net_cost_usd'])} = Σ (cost + credits) over every"
              f" Cloud Logging SKU for {c.project}, {month}"
          ),
          (
              f"  = {_money(m['raw_cost_usd'])} cost +"
              f" {_money(m['credits_usd'])} credits:"
          ),
          *(
              f"  • {k}: {_money(v)}"
              for k, v in sorted(m["cost_by_sku"].items())
          ),
          (
              f"{_gib(m['total_gib'])} = Σ usage in '{INGESTION_PRICING_UNIT}'"
              " (ingestion only; retention bills in GiB-months)."
          ),
      ],
      [
          c.billing_source(
              f"Billing export, {month}", sql, "Every dollar and GiB here"
          ),
          c.reports_source(month),
      ],
      [
          _PACIFIC_NOTE,
          (
              "Dollars cover every Cloud Logging SKU, retention included; GiB"
              " is ingestion only, so dollars ÷ GiB is not a unit price."
          ),
          "The export can receive corrections for a few days after month end.",
      ],
      [
          _invoice_check(
              c,
              f"Re-run the {month} billing query",
              month,
              {"net_cost": m["net_cost_usd"], "ingested_gib": m["total_gib"]},
              TOL_INVOICE_PCT,
          )
      ],
  )


def _mtd_run_rate(c: _Ctx) -> Optional[Dict[str, Any]]:
  """Proves month-to-date spend and the straight-line month-end projection."""
  proj = c.s["cost_projection"]
  month = proj["month"]
  # On the 1st the export may have no rows for the projected month yet; never
  # pair last month's spend with this month's projection.
  if not c.invoiced or month not in c.monthly:
    return None
  m = c.monthly[month]
  first, last = _month_bounds(month)
  complete_end = min(last_complete_invoice_day(c.now), last)
  eom = sorted(proj["projected_eom_gib_by_sku"].items())
  formula = [
      f"Month to date: {_money(m['net_cost_usd'])} = Σ (cost + credits),"
      f" {first} to today (Pacific), all Cloud Logging SKUs."
  ]
  if eom:
    formula += [
        f"Projected month end: {_money(proj['projected_eom_cost_usd'])} = "
        + " + ".join(_price_term(g, c.book.terms(k)) for k, g in eom)
        + " ("
        + ", ".join(f"{_label(k)} {_gib(g)}" for k, g in eom)
        + ").",
        (
            "  Each SKU's month-end GiB = its mean invoiced GiB/day over"
            f" complete days {first} to {complete_end} × {last.day} days."
        ),
    ]
  return _claim(
      "mtd_run_rate",
      "Current MTD Run-Rate",
      f"{_money(m['net_cost_usd'])} MTD · projected"
      f" {_money(proj['projected_eom_cost_usd'])}",
      "Month-to-date spend is invoiced; month end is a straight-line"
      " projection of invoiced daily volume.",
      formula,
      [
          c.billing_source(
              f"Billing export, {month} to date",
              billing_month_sql(c.table, c.project, month),
              "Month-to-date spend and GiB",
          ),
          c.billing_source(
              "Daily invoiced GiB behind the projection",
              billing_daily_gib_sql(c.table, c.project, first, complete_end),
              "Mean GiB/day",
          ),
          c.billing_source(
              "Per-SKU unit prices",
              billing_unit_price_sql(c.table, c.project, month),
              "What each SKU charges per GiB",
          ),
          c.reports_source(month),
      ],
      [
          _PACIFIC_NOTE,
          "The export lags up to a day, so today's spend grows between runs.",
          (
              "The projection holds each SKU at its month-to-date daily"
              " average; the free tier applies once, to the whole month."
          ),
      ],
      [
          _invoice_check(
              c,
              f"Re-run the {month} month-to-date query",
              month,
              {"net_cost": m["net_cost_usd"]},
              TOL_INVOICE_RECENT_PCT,
          )
      ],
  )


def _invoiced_driver_cost(m: Dict[str, Any], name: str, month: str) -> str:
  """How the invoice's ingestion dollars were apportioned to one service."""
  details, top = m["services_details"], m["services_details"][name]
  if m["services_cost_basis"] != "per_sku":
    return (
        f"{_money(top['cost_usd'])} = {top['pct_of_volume']}% ×"
        f" {_money(m['ingestion_cost_usd'])} invoiced ingestion cost,"
        " apportioned to the cent."
    )
  sku = sku_of_resource(name)
  pool = [v["bytes"] for k, v in details.items() if sku_of_resource(k) == sku]
  sku_cost = (m["ingestion_by_sku"].get(sku) or {}).get("net_cost_usd")
  return (
      f"{_money(top['cost_usd'])} = {top['bytes'] / (sum(pool) or 1):.1%} of"
      f" the bytes of the {len(pool)} services billed as {_label(sku)} ×"
      f" {_money(sku_cost)} {_label(sku)} cost for {month}, apportioned to the"
      " cent. Each SKU's cost is split only across the services it bills."
  )


def _top_cost_driver(c: _Ctx) -> Optional[Dict[str, Any]]:
  """Proves the top service's share of volume and its dollars."""
  if c.invoiced:
    m = _latest_invoiced_month(c)
    name = m and m["top_service"]
    if not name:
      return None
    month = c.s["latest_complete_month"]
    top = m["services_details"][name]
    share, cost = top["pct_of_volume"], top["cost_usd"]
    _, last = _month_bounds(month)
    days = max(m["services_telemetry_days"], 1)
    start = last - datetime.timedelta(days=days - 1)
    end = last + datetime.timedelta(days=1)
    summary = (
        "The share is from Cloud Monitoring; the GiB and dollars it applies to"
        " are from your invoice."
    )
    formula = [
        (
            f"{_gib(top['billed_gib'])} = {share}% × {_gib(m['total_gib'])}"
            " invoiced ingestion."
        ),
        _invoiced_driver_cost(m, name, month),
    ]
    sources = [
        c.billing_source(
            f"Billing export, {month}",
            billing_month_sql(c.table, c.project, month),
            "The invoiced GiB and dollars the share is applied to",
        )
    ]
    differences = [
        "Monitoring days are UTC; invoice days are Pacific.",
        f"{_METRIC_LOW} Shares on those days are indicative.",
    ]
    if days < last.day:
      differences.insert(
          0,
          f"Only {days} of {last.day} days of {month} are within Cloud"
          f" Monitoring's {MONITORING_RETENTION_DAYS}-day retention; the share"
          " assumes the rest of the month had the same mix.",
      )
  elif c.telemetry and c.t30.get("top_driver"):
    name = c.t30["top_driver"]
    top = next(s for s in c.t30["top_services"] if s["service"] == name)
    share, cost = top["pct_of_total"], top["cost_usd"]
    days = DEFAULT_TELEMETRY_LOOKBACK_DAYS
    start, end = c.utc_window(days)
    total = c.t30["total_gib"]
    monthly_gib = (
        top["gib"] * c.t30["monthly_run_rate_gib"] / total if total else 0
    )
    sku = c.book.sku_for_resource(name)
    summary = (
        "Share and volume from Cloud Monitoring's billed-bytes metric, priced"
        " at list. No billing export was used."
    )
    formula = [
        (
            f"{_gib(top['gib'])} = {share}% × {_gib(total)} trailing {days}-day"
            " volume."
        ),
        (
            f"{_money(cost)}/mo = {_gib(monthly_gib)}/month ×"
            f" ${c.book.terms(sku).effective_rate:.4f}/GiB, the effective"
            f" {_label(sku)} rate (its monthly bill ÷ its monthly GiB)."
        ),
        "Ranked by estimated dollars, then volume.",
    ]
    sources = c.pricing_sources()
    differences = c.metric_differences() + c.pricing_differences()
  else:
    return None
  promql = promql_billed(days)
  return _claim(
      "top_cost_driver",
      "Top Cost Driver",
      f"{name} · {share}% · {_money(cost)}",
      summary,
      [
          f"Share {share}% = {name} bytes ÷ all bytes in"
          f" {BILLED_BYTES_METRIC}, {_utc_days(start, end)}."
      ]
      + formula,
      [
          c.promql_source(
              f"Service mix, {_utc_days(start, end)}",
              promql,
              days,
              "The share",
              f"Evaluate at {_utc_midnight(end)} (or Table view on a custom"
              f" range); divide the {name} row by the sum of all rows.",
          )
      ]
      + sources,
      differences,
      [
          _check(
              "promql",
              f"Re-measure {name}'s share",
              {name: share},
              query=promql,
              time=_utc_midnight(end),
              compare="share",
              label_key="resource_type",
              tolerance_points=TOL_SHARE_POINTS,
          )
      ],
  )


# ------------------------------------------------------------------------------
# Telemetry-mode KPI claims (no billing export): metric volumes, list prices.
# ------------------------------------------------------------------------------


def _trailing_30d_volume(c: _Ctx) -> Optional[Dict[str, Any]]:
  """Proves the Trailing 30-Day Volume card shown without an invoice."""
  days_seen = c.t30.get("days_observed")
  if not c.telemetry or not days_seen:
    return None
  total, daily = c.t30["total_gib"], c.t30["daily_avg_gib"]
  days = DEFAULT_TELEMETRY_LOOKBACK_DAYS
  start, end = c.utc_window(days)
  return _claim(
      "trailing_30d_volume",
      "Trailing 30-Day Volume",
      f"{_gib(total)} · {_gib(daily)}/day",
      "Summed from Cloud Monitoring's billed-bytes metric: metered volume,"
      " not invoiced (no billing export).",
      [
          (
              f"{_gib(total)} = Σ {BILLED_BYTES_METRIC} bytes across every"
              f" resource type, {_utc_days(start, end)}, {_TO_GIB}."
          ),
          (
              f"Daily average {_gib(daily)}/day = {total:,.2f} GiB ÷"
              f" {days_seen} day{'s' if days_seen != 1 else ''} with data."
          ),
      ],
      [
          c.telemetry_volume_source("Every GiB in this figure"),
          c.daily_bars_source(
              "Same metric, one bar per day",
              days,
              "The daily series behind the average",
              f"sum the bars over {_utc_days(start, end)}.",
          ),
      ],
      c.metric_differences(),
      [
          _check(
              "promql",
              "Re-measure trailing 30-day volume",
              {"total": total},
              query=promql_billed(days, False),
              time=_utc_midnight(end),
              compare="total",
              scale=1 / BYTES_PER_GIB,
              unit="GiB",
              tolerance_pct=TOL_METRIC_TOTAL_PCT,
          )
      ],
  )


def _estimated_run_rate(c: _Ctx) -> Optional[Dict[str, Any]]:
  """Proves the Estimated Monthly Run-Rate card shown without an invoice."""
  if not c.telemetry or not c.t30.get("days_observed"):
    return None
  run_rate = c.t30["monthly_run_rate_gib"]
  cost = c.t30["projected_monthly_cost_usd"]
  annual = c.t30["projected_annual_cost_usd"]
  formula = [
      (
          f"Run rate {_gib(run_rate)}/month ="
          f" {_gib(c.t30['daily_avg_gib'])}/day × {DAYS_PER_MONTH:g} days."
      ),
      *c.baseline_formula(),
      f"Annualized {_money(annual)} = {_money(cost)} × 12.",
  ]
  sources: List[Optional[Dict[str, Any]]] = [
      c.telemetry_volume_source("The volume behind the run rate")
  ]
  check = c.book.mapping_check
  if c.per_sku and check.get("split_source") == "cloud_monitoring_byte_count":
    sources.append(
        _source(
            "cloud_monitoring",
            "Vended network log streams (byte_count)",
            "How the run rate splits between the two SKUs",
            [
                (
                    f"Metric = {BYTE_COUNT_METRIC}, Aggregation = Sum,"
                    " Alignment = 1 day, over the stream window. Vended share"
                    " = total with this filter ÷ total without it"
                    f" ({check.get('telemetry_vended_share_pct')}% in the"
                    " report)."
                ),
                (
                    "On a large project read the unfiltered total a few days at"
                    " a time; one read over the whole window can time out."
                ),
            ],
            query=monitoring_vended_streams_filter(),
            language="monitoring_filter",
            url=metrics_explorer_url(c.project),
            label=_METRICS_EXPLORER,
        )
    )
  return _claim(
      "estimated_run_rate",
      "Estimated Monthly Run-Rate",
      f"{_money(cost)}/mo · {_money(annual)}/yr",
      "Trailing 30-day metered volume projected to a month and priced at"
      " Cloud Logging list prices (no billing export).",
      formula,
      sources + c.pricing_sources(),
      c.metric_differences()
      + [
          "Ingestion only; retention past the included 30 days bills"
          " separately."
      ]
      + c.pricing_differences(),
      [c.run_rate_check("Re-measure the monthly run-rate volume")],
  )


# ------------------------------------------------------------------------------
# Savings and breakdowns.
# ------------------------------------------------------------------------------


def _calibration_line(b: Dict[str, Any], cal: float, window: int) -> str:
  """The byte_count → billed calibration, as arithmetic that adds up."""
  anchor, received = b["anchor_window_gib"], b["byte_count_window_gib"]
  anchor_label = (
      "invoiced"
      if b["calibration_anchor"] == "billing_export"
      else f"billed ({BILLED_BYTES_METRIC})"
  )
  sides = (
      f"{_gib(anchor)} {anchor_label} ÷ {_gib(received)} received (byte_count)"
      f" over {window} days"
  )
  raw = anchor / received if anchor and received else None
  if raw is not None and raw > cal + 0.005:
    # Calibration is capped at 1: scaling stream bytes up would invent savings.
    return (
        f"Calibration ×{cal:g}: {sides} = ×{raw:.2f}, capped at ×1. Billed"
        " exceeds received (e.g. entries routed to several buckets), so stream"
        " bytes are used as measured and every action stays a floor."
    )
  return f"Calibration ×{cal:g} = {sides}; stream volumes scale onto billed."


def _extraneous_spend(c: _Ctx) -> Optional[Dict[str, Any]]:
  """Proves the extraneous-spend floor; each counted action proves itself."""
  if c.ext.get("status") != "ok":
    return None
  hl, b, window = c.ext["headline"], c.basis, c.window
  levers = [a for a in c.actions if a["counted"]]
  rule = (
      "Each counted action: GiB/month = claimed stream bytes × calibration ×"
      f" {DAYS_PER_MONTH:g}/{window}"
  )
  if c.per_sku:
    formula = c.baseline_formula() + [
        _calibration_line(b, c.calibration, window),
        (
            f"{rule}, priced on the SKU each stream bills under; % = saving ÷"
            f" {_money(c.book.baseline_cost)} baseline bill."
        ),
    ]
  else:
    t = c.book.terms(BLENDED)
    formula = [
        (
            f"Baseline: {_gib(b['baseline_monthly_gib'])}/month"
            f" ({c.volume_basis}) − {t.free_gib:g} GiB free ="
            f" {_gib(b['billable_monthly_gib'])} billable ×"
            f" ${t.unit_price:g}/GiB = {_money(c.book.baseline_cost)}/month."
        ),
        _calibration_line(b, c.calibration, window),
        (
            f"{rule}; saving = billable(baseline) − billable(baseline − action"
            " GiB), × rate."
        ),
    ]
  for lv in levers:
    split = ", ".join(
        f"{_gib(g)} {_label(k)}" for k, g in sorted(lv["gib_by_sku"].items())
    )
    formula.append(
        f"  • {lv['title']}: {_gib(lv['monthly_gib'])}/mo"
        + (f" ({split})" if split and c.per_sku else "")
        + f" → {_money(lv['monthly_usd'])}/mo ({lv['pct_of_billable']}%)"
    )
  formula.append(
      f"Floor = Σ counted actions = ≥ {hl['pct_of_billable_spend']}%"
      f" ({_money(hl['monthly_savings_usd'])}/mo). Uncounted actions are never"
      " added. Each action's own Prove It lists and re-measures its streams."
  )
  return _claim(
      "extraneous_spend",
      "Extraneous Log Spend",
      f"≥ {hl['pct_of_billable_spend']}% ·"
      f" {_money(hl['monthly_savings_usd'])}/mo",
      "A floor: only actions measured from Cloud Monitoring volume metrics"
      " count, each against an"
      + c.priced_against,
      formula,
      [
          c.baseline_source(
              f"Baseline: {c.volume_basis}", "Denominator of every percentage"
          ),
          *c.pricing_sources(),
      ],
      [
          "Each action is priced alone against the full baseline, so the sum"
          " is not a joint saving where the free tier matters."
      ]
      + c.pricing_differences(),
      [c.run_rate_check("Re-measure the baseline")],
      see_also=[f"action::{lv['id']}" for lv in levers],
  )


def _shared_window(summary: Dict[str, Any]) -> List[str]:
  daily = summary["daily_services"]
  dates = sorted(d for d, v in daily.items() if sum(v.values()) > 0)
  return dates[-DEFAULT_SAMPLE_DAYS:]


def _service_mix(c: _Ctx) -> Optional[Dict[str, Any]]:
  """Proves the By Service table's daily GiB and estimated dollars."""
  dates = _shared_window(c.s)
  if not dates:
    return None
  totals: Dict[str, float] = {}
  for d in dates:
    for svc, b in c.s["daily_services"][d].items():
      totals[svc] = totals.get(svc, 0.0) + b
  grand = sum(totals.values()) or 1.0
  top = sorted(totals.items(), key=lambda kv: kv[1], reverse=True)[:5]
  start = datetime.date.fromisoformat(dates[0])
  end = datetime.date.fromisoformat(dates[-1]) + datetime.timedelta(days=1)
  window = _utc_days(start, end)
  promql = promql_billed(len(dates))
  return _claim(
      "service_mix",
      "Service mix",
      f"{len(dates)}-day breakdown by service",
      "Straight from Cloud Monitoring's billed-bytes metric, one of the"
      " metrics Google bills from.",
      [
          (
              f"GiB per service = Σ {BILLED_BYTES_METRIC} bytes by"
              f" resource_type, {window}, {_TO_GIB}."
          ),
          f"Est. cost = service GiB × {c.rate_desc()}",
          *(
              f"  • {svc}: {_gib(b / BYTES_PER_GIB)} ({b / grand * 100:.1f}%)"
              for svc, b in top
          ),
      ],
      [
          c.promql_source(
              f"Billed bytes by service, {window}",
              promql,
              len(dates),
              "Every row in the table",
              f"Evaluate at {_utc_midnight(end)}; Table view gives one total"
              " per service.",
          ),
          c.daily_bars_source(
              "Same metric, one bar per day",
              len(dates),
              "The daily chart",
              "one bar per service per day.",
          ),
      ],
      [
          (
              "Dollars are GiB × rate with no credits, so the table will not"
              " equal invoiced dollars for the same days."
          ),
          f"Raw metric bytes, not rescaled to the invoice. {_METRIC_LOW}",
      ],
      [
          _check(
              "promql",
              "Re-measure service GiB",
              {svc: round(b / BYTES_PER_GIB, 2) for svc, b in top},
              query=promql,
              time=_utc_midnight(end),
              compare="value",
              scale=1 / BYTES_PER_GIB,
              label_key="resource_type",
              tolerance_pct=TOL_METRIC_TOTAL_PCT,
          )
      ],
  )


def _severity_costs(c: _Ctx) -> Optional[Dict[str, Any]]:
  """Proves the By Severity table's shares, GiB and estimated dollars."""
  sev = c.s["severity_summary"]
  totals = sev["severity_totals"]
  if not totals:
    return None
  grand = sum(totals.values()) or 1.0
  shares = {k: round(v / grand * 100, 2) for k, v in totals.items()}
  ga = c.s.get("granular_analytics") or {}
  start, end = ga.get("sample_start"), ga.get("sample_end")
  if c.per_sku:
    cost_line = (
        "Est. cost = severity share × the day's dollars, each service's GiB"
        f" priced at {c.rate_desc()}"
    )
  else:
    cost_line = f"Est. cost = severity GiB × ${c.rate}/GiB."
  formula = [
      (
          "Per day: severity GiB = that severity's share of log content bytes ×"
          f" the day's billed GiB ({BILLED_BYTES_METRIC})."
      ),
      cost_line,
      "Window shares:",
      *(
          f"  • {k}: {v}%"
          for k, v in sorted(shares.items(), key=lambda kv: -kv[1])
      ),
  ]
  sources: List[Optional[Dict[str, Any]]] = []
  checks: List[Optional[Dict[str, Any]]] = []
  table = c.s["analytics_metadata"]["table_name"]
  if sev.get("severity_source") == "log_analytics" and start and end and table:
    sql = severity_share_sql(table, start, end)
    sources.append(
        _source(
            "log_analytics",
            "Severity weights (Log Analytics)",
            "The share of each severity",
            [
                "Observability Analytics → paste the SQL → Run. It also runs"
                " as is in BigQuery, where the collector ran it."
            ],
            query=sql,
            language="sql",
            url=log_analytics_url(c.project),
            label="Open Observability Analytics",
        )
    )
    checks.append(
        _check(
            "bigquery",
            "Re-run the severity share query",
            shares,
            project=c.project,
            query=sql,
            compare="share_rows",
            row_key="severity",
            row_value="share_pct",
            tolerance_points=TOL_SHARE_POINTS,
        )
    )
  return _claim(
      "severity_costs",
      "Severity costs",
      "Breakdown by severity",
      "Severity shares come from your log contents; the daily volume they"
      " split is the service mix's billed-bytes metric.",
      formula,
      sources,
      [
          (
              "Content bytes exclude labels and metadata, so large payloads"
              " weigh more."
          ),
          "Log Analytics buckets by event time, the metric by ingestion time.",
          "As in the service table: no credits, free tier spread per SKU.",
      ],
      checks,
      see_also=["service_mix"] if _shared_window(c.s) else [],
  )


def _action(c: _Ctx, action: Dict[str, Any]) -> Optional[Dict[str, Any]]:
  """Proves one cost optimization action's volume and saving."""
  gib = action["monthly_gib"]
  if gib is None:
    return None
  formula = c.saving_formula(action["gib_by_sku"], action["monthly_usd"])
  sources: List[Optional[Dict[str, Any]]] = []
  checks: List[Dict[str, Any]] = []
  if action["source"] == SOURCE_LEVER:
    fraction = action["stream_fraction"]
    formula.insert(
        0,
        f"{_gib(gib)}/mo = claimed stream bytes over {c.window} days ×"
        f" calibration {c.calibration} × {DAYS_PER_MONTH:g}/{c.window}"
        + (f" × {fraction:g} (share removed)." if fraction != 1.0 else "."),
    )
    sources, checks = c.stream_sources_and_checks(
        action["claims"], gib, fraction
    )
    if action["id"].startswith("stale_exclusion"):
      sources.append(
          _source(
              "log_router",
              "Log Router exclusions",
              "The exclusion rule this action is inferred from",
              [
                  "Open the _Default sink → Exclusions and compare each"
                  " filter's LOG_ID with the stream above."
              ],
              url=log_router_url(c.project),
              label="Open Log Router",
          )
      )
  else:
    pct = action["projected_savings_pct"]
    formula.insert(
        0,
        f"{_gib(gib)}/mo = {pct}% of the"
        f" {_gib(c.t30.get('monthly_run_rate_gib'))}/mo"
        f" {'invoiced' if c.invoiced else 'estimated'} run rate; {pct}% ="
        " bytes matching the filter ÷ all log content bytes in the Log"
        " Analytics sample window.",
    )
  if action.get("filter"):
    sources.append(
        _source(
            "logs_explorer",
            "What this filter would drop",
            "Preview the exact entries the exclusion matches",
            [
                "Runs the exclusion as a search over the sample window;"
                " everything listed would stop being ingested."
            ],
            query=action["filter"],
            language="logging_query",
            url=logs_explorer_url(c.project, action["filter"], f"P{c.window}D"),
            label="Open in Logs Explorer",
        )
    )
  sources.append(
      c.baseline_source(
          "Baseline run rate", "The monthly volume the saving is taken from"
      )
  )
  return _claim(
      f"action::{action['id']}",
      f"Saving: {action['title']}",
      f"{_money(action['monthly_usd'])}/mo · {_gib(gib)}/mo",
      "Volume measured from your own logs, priced against your"
      + c.priced_against,
      formula,
      sources + c.pricing_sources(),
      c.pricing_differences() + [_LATE_POINTS],
      checks,
  )


def build_provenance(summary: Dict[str, Any]) -> Dict[str, Any]:
  """Returns the `provenance` block for a finished summary."""
  c = _Ctx(summary)
  claims: Dict[str, Dict[str, Any]] = {}
  for claim in [
      _latest_complete_spend(c),
      _mtd_run_rate(c),
      _top_cost_driver(c),
      _trailing_30d_volume(c),
      _estimated_run_rate(c),
      _extraneous_spend(c),
      _service_mix(c),
      _severity_costs(c),
      *(_action(c, a) for a in c.actions),
  ]:
    if claim:
      claims[claim["id"]] = claim
  return {
      "billing_project": c.billing_project,
      "cross_project_billing": c.cross_project,
      "claims": claims,
  }
requirements.txt 0.2 KB
google-auth>=2.20.0,<3.0.0
google-api-python-client>=2.90.0,<3.0.0
google-cloud-logging>=3.5.0,<4.0.0
google-cloud-monitoring>=2.14.0,<3.0.0
google-cloud-bigquery>=3.10.0,<4.0.0
absl-py>=1.4.0,<3.0.0
telemetry_integrity.py 7.6 KB
"""Detects days whose `billing/bytes_ingested` telemetry cannot be believed.

The metric is the only per-service volume source but can silently under-report
a day while its series stays dense and on schedule. Days are checked against
the billing export when available (ratio ~1.0 when healthy), else against
`byte_count` (received bytes; only its ratio stability is informative). This
module only reports; no day is dropped.
"""

import datetime
import statistics
from typing import Any, Dict, List, Mapping, Optional, Sequence

from constants import BYTE_COUNT_METRIC
from constants import BYTES_PER_GIB
from pricing import complete_days

INVOICE_CONTROL = "cloud_billing_bigquery_export"

# --- Invoice control ---------------------------------------------------------

# Healthy days sit near 1.0 of the invoice; failures lose most of the volume.
COMPROMISED_INVOICE_RATIO = 0.5

# Smaller invoiced days are skipped: rounding and the 8h Pacific/UTC day offset
# dominate their ratio.
MIN_INVOICED_GIB = 0.1

# Each day is judged on its own, so fewer days are needed than for `byte_count`.
MIN_DAYS_FOR_INVOICE_VERDICT = 3

# --- `byte_count` fallback control -------------------------------------------

# A day is compromised below this fraction of the window's median ratio.
SUSPECT_RATIO_FRACTION = 0.5

# Below this median the router may drop most logs, or the metric may be broken
# throughout; telemetry alone cannot tell which.
MIN_PLAUSIBLE_MEDIAN_RATIO = 0.15

# Fewer comparable days give no stable median.
MIN_DAYS_FOR_VERDICT = 5

# Near-idle days give ratios dominated by rounding.
MIN_CONTROL_BYTES = 1024 * 1024


def daily_totals(
    parsed: Mapping[Any, Sequence[Sequence[Any]]],
) -> Dict[str, float]:
  """Collapses a `{key: [[date, value], ...]}` series into per-day totals."""
  totals: Dict[str, float] = {}
  for points in parsed.values():
    for day, value in points:
      totals[day] = totals.get(day, 0.0) + value
  return totals


def assess_against_invoice(
    billed_daily: Mapping[str, float],
    invoiced_daily_gib: Mapping[str, float],
    now: datetime.datetime,
) -> Dict[str, Any]:
  """Reports which days of billed telemetry disagree with the invoice.

  Args:
    billed_daily: Per-day bytes from `billing/bytes_ingested`, by UTC day.
    invoiced_daily_gib: Per-day GiB from the billing export, by Pacific day. The
      8h offset is left uncorrected; it cannot cross a 2x threshold.
    now: Current time; invoice days not yet complete are dropped.

  Returns:
    A verdict dict; `status` is `ok`, `degraded` (see `compromised_days`) or
    `unverified` (too few comparable days).
  """
  # Only days the metric also reported are compared, so the metric's own
  # window bounds the overlap.
  ratios = {
      day: billed_daily[day] / (gib * BYTES_PER_GIB)
      for day, gib in complete_days(invoiced_daily_gib, "", now).items()
      if gib >= MIN_INVOICED_GIB and day in billed_daily
  }
  if len(ratios) < MIN_DAYS_FOR_INVOICE_VERDICT:
    return _verdict(
        "unverified",
        INVOICE_CONTROL,
        None,
        len(ratios),
        f"Only {len(ratios)} fully-invoiced day(s) overlap the metric window,"
        " too few to judge whether billing/bytes_ingested reports the volume"
        " that was billed. Service and severity shares are unverified.",
    )

  median_ratio = statistics.median(ratios.values())
  compromised = sorted(
      d for d, r in ratios.items() if r < COMPROMISED_INVOICE_RATIO
  )
  if not compromised:
    return _verdict(
        "ok",
        INVOICE_CONTROL,
        median_ratio,
        len(ratios),
        f"All {len(ratios)} invoiced days in the window are matched by"
        " billing/bytes_ingested.",
    )
  return _verdict(
      "degraded",
      INVOICE_CONTROL,
      median_ratio,
      len(ratios),
      "Cloud Monitoring's billing/bytes_ingested reported under"
      f" {COMPROMISED_INVOICE_RATIO:.0%} of the invoiced volume on"
      f" {len(compromised)} of {len(ratios)} days"
      f" ({_summarise_days(compromised)}). Costs, volumes and run rates come"
      " from the billing export and are unaffected; the service and severity"
      " split on those days is indicative only.",
      compromised,
  )


def _summarise_days(days: Sequence[str]) -> str:
  """Renders a day list compactly; never as a range, as days are scattered."""
  if len(days) <= 4:
    return ", ".join(days)
  return (
      f"{', '.join(days[:3])} and {len(days) - 3} others, most recently"
      f" {days[-1]}"
  )


def assess(
    billed_daily: Mapping[str, float],
    received_daily: Mapping[str, float],
) -> Dict[str, Any]:
  """Reports which days of billed telemetry are too low to be believed.

  Used only without a billing export. `byte_count` is not billed volume, so
  only a day's billed:received ratio relative to the window median is judged.

  Args:
    billed_daily: per-day totals from `billing/bytes_ingested`.
    received_daily: per-day totals from `byte_count`.

  Returns:
    A verdict dict; `status` is `ok`, `degraded` (`compromised_days` far below
    the window median) or `unverified` (no usable control or too few days).
  """
  control = BYTE_COUNT_METRIC
  ratios = {
      day: billed_daily[day] / received
      for day, received in received_daily.items()
      if received >= MIN_CONTROL_BYTES and day in billed_daily
  }
  if len(ratios) < MIN_DAYS_FOR_VERDICT:
    return _verdict(
        "unverified",
        control,
        None,
        len(ratios),
        f"Only {len(ratios)} day(s) could be compared against {control}, too"
        " few to tell an incomplete metric write from a real change in"
        " volume. Figures derived from billing/bytes_ingested are unverified.",
    )

  median_ratio = statistics.median(ratios.values())
  if median_ratio < MIN_PLAUSIBLE_MEDIAN_RATIO:
    return _verdict(
        "unverified",
        control,
        median_ratio,
        len(ratios),
        "Across the window, billing/bytes_ingested reports a median of"
        f" {median_ratio:.1%} of what {control} received. Either the Log"
        " Router drops most of this project's volume, or the billed metric is"
        " incomplete throughout; telemetry alone cannot tell which, so no day"
        " was flagged.",
    )

  threshold = median_ratio * SUSPECT_RATIO_FRACTION
  compromised = sorted(d for d, r in ratios.items() if r < threshold)
  if not compromised:
    return _verdict(
        "ok",
        control,
        median_ratio,
        len(ratios),
        f"All {len(ratios)} comparable days hold a billed:received ratio"
        f" consistent with the window median of {median_ratio:.2f}.",
    )
  return _verdict(
      "degraded",
      control,
      median_ratio,
      len(ratios),
      "billing/bytes_ingested reported under"
      f" {SUSPECT_RATIO_FRACTION:.0%} of its usual share of {control} on"
      f" {len(compromised)} day(s) ({_summarise_days(compromised)}), against"
      f" a window median billed:received ratio of {median_ratio:.2f}. With no"
      " billing export, the comparison is against received rather than"
      " invoiced bytes and cannot rule out a genuine change in what is"
      " billable.",
      compromised,
  )


def _verdict(
    status: str,
    control_metric: str,
    median_ratio: Optional[float],
    days_observed: int,
    note: str,
    compromised: Optional[List[str]] = None,
) -> Dict[str, Any]:
  """Assembles the verdict dict shared by every branch of both assessors."""
  return {
      "status": status,
      "control_metric": control_metric,
      "median_billed_to_received_ratio": (
          None if median_ratio is None else round(median_ratio, 4)
      ),
      "days_observed": days_observed,
      "compromised_days": list(compromised or []),
      "note": note,
  }
verify_claim.py 10.2 KB
"""Re-measures a report claim live, using the queries its Prove It panel shows.

    python3 verify_claim.py --summary logging_usage_summary.json --claim
    top_cost_driver
    python3 verify_claim.py --summary logging_usage_summary.json --claim all

Runs each claim's `checks` (SQL, PromQL or Monitoring filter) live and prints
reported vs. current values against the tolerance each check carries. Drift is
reported; only a failure to run a check exits non-zero.
"""

import argparse
import concurrent.futures
import datetime
import json
import sys
from typing import Any, Callable, Dict, List, NamedTuple, Optional

import attribution
from google.cloud import monitoring_v3
import monitoring

# Concurrent Monitoring reads per check; modest to respect read quota.
MONITORING_SUM_WORKERS = 16


def _pct_delta(expected: float, measured: float) -> float:
  if not expected:
    return 0.0 if not measured else 100.0
  return (measured - expected) / abs(expected) * 100.0


def _parse_ts(value: str) -> datetime.datetime:
  return datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))


# ==============================================================================
# Source runners (injectable for tests)
# ==============================================================================


def run_bigquery(query: str, project: Optional[str]) -> List[Dict[str, Any]]:
  from google.cloud import bigquery  # pylint: disable=g-import-not-at-top

  client = bigquery.Client(
      project=project,
      client_info=attribution.client_info(attribution.VERIFY_CLAIM),
  )
  return [dict(row) for row in client.query(query).result()]


def run_promql(project: str, query: str, time: str) -> Dict[str, float]:
  """Evaluates an instant PromQL query; returns {label-set: value}."""
  import google.auth  # pylint: disable=g-import-not-at-top
  from google.auth.transport.requests import AuthorizedSession  # pylint: disable=g-import-not-at-top

  creds, _ = google.auth.default(
      scopes=["https://www.googleapis.com/auth/monitoring.read"]
  )
  url = (
      "https://monitoring.googleapis.com/v1/projects/"
      f"{project}/location/global/prometheus/api/v1/query"
  )
  session = attribution.tag_session(
      AuthorizedSession(creds), attribution.VERIFY_CLAIM
  )
  resp = session.post(url, data={"query": query, "time": time})
  body = resp.json()
  if resp.status_code != 200 or body.get("status") != "success":
    raise RuntimeError(body.get("error") or resp.text[:300])
  out: Dict[str, float] = {}
  for item in body["data"]["result"]:
    key = json.dumps(item.get("metric", {}), sort_keys=True)
    out[key] = float(item["value"][1])
  return out


def run_monitoring_sum(project: str, flt: str, start: str, end: str) -> float:
  """Σ bytes for one filter, in daily buckets like the collector."""
  client = monitoring_v3.MetricServiceClient(
      client_info=attribution.client_info(attribution.VERIFY_CLAIM)
  )
  s, e = _parse_ts(start), _parse_ts(end)
  return monitoring.sum_filter(client, project, flt, e, (e - s).days)


class Runners(NamedTuple):
  """The live query runners; tests replace them with fakes."""

  bigquery: Callable[..., List[Dict[str, Any]]] = run_bigquery
  promql: Callable[..., Dict[str, float]] = run_promql
  monitoring_sum: Callable[..., float] = run_monitoring_sum


# ==============================================================================
# Check evaluation
# ==============================================================================


def _row(
    key: str,
    expected: float,
    measured: float,
    unit: str,
    tol: float,
    points: bool = False,
) -> Dict[str, Any]:
  delta = (measured - expected) if points else _pct_delta(expected, measured)
  return {
      "key": key,
      "expected": expected,
      "measured": round(measured, 4),
      "unit": unit,
      "delta": round(delta, 2),
      "delta_unit": "points" if points else "%",
      "ok": abs(delta) <= tol,
  }


def _label_value(key_json: str, label: str) -> str:
  return json.loads(key_json).get(label, "")


def evaluate_check(
    check: Dict[str, Any], project: str, runners: Runners
) -> Dict[str, Any]:
  """Runs one check and compares it with what the report printed."""
  kind = check.get("kind")
  rows: List[Dict[str, Any]] = []
  try:
    if kind == "bigquery":
      result = runners.bigquery(check["query"], check.get("project"))
      if check.get("compare") == "share_rows":
        got = {
            str(r[check["row_key"]]): float(r[check["row_value"]] or 0)
            for r in result
        }
        tol = check["tolerance_points"]
        for k, exp in check["expect"].items():
          rows.append(_row(k, exp, got.get(k, 0.0), "%", tol, points=True))
      else:
        # Row one: a single-row query, or the ROLLUP total sorted first.
        first = result[0]
        for k, exp in check["expect"].items():
          if exp is None:
            continue
          rows.append(
              _row(k, exp, float(first[k] or 0), "", check["tolerance_pct"])
          )
    elif kind == "promql":
      result = runners.promql(project, check["query"], check["time"])
      by_label = {
          _label_value(k, check.get("label_key", "")): v
          for k, v in result.items()
      }
      if check.get("compare") == "total":
        # `sum(...)` returns one unlabeled series; add up everything.
        rows.append(
            _row(
                "total",
                check["expect"]["total"],
                sum(result.values()) * check.get("scale", 1.0),
                check.get("unit", "GiB"),
                check["tolerance_pct"],
            )
        )
      elif check.get("compare") == "share":
        total = sum(by_label.values()) or 1.0
        tol = check["tolerance_points"]
        for k, exp in check["expect"].items():
          rows.append(
              _row(
                  k,
                  exp,
                  by_label.get(k, 0.0) / total * 100,
                  "%",
                  tol,
                  points=True,
              )
          )
      else:
        scale = check.get("scale", 1.0)
        tol = check["tolerance_pct"]
        for k, exp in check["expect"].items():
          rows.append(_row(k, exp, by_label.get(k, 0.0) * scale, "GiB", tol))
    elif kind == "monitoring_sum":
      series = check["series"]
      # One independent read per claimed stream, run concurrently.
      with concurrent.futures.ThreadPoolExecutor(
          max_workers=min(MONITORING_SUM_WORKERS, max(len(series), 1))
      ) as pool:
        total = sum(
            pool.map(
                lambda s: runners.monitoring_sum(
                    project, s["filter"], check["start"], check["end"]
                ),
                series,
            )
        )
      measured = total * check.get("multiplier", 1.0)
      rows.append(
          _row(
              "total",
              check["expect"]["total"],
              measured,
              check.get("unit", ""),
              check["tolerance_pct"],
          )
      )
    else:
      raise ValueError(f"unknown check kind {kind!r}")
  except Exception as e:  # pylint: disable=broad-except
    return {
        "label": check.get("label"),
        "kind": kind,
        "error": str(e),
        "rows": [],
    }
  return {
      "label": check.get("label"),
      "kind": kind,
      "rows": rows,
      "ok": all(r["ok"] for r in rows),
  }


def verify(
    summary: Dict[str, Any], claim_ids: List[str], runners: Runners
) -> List[Dict[str, Any]]:
  """Runs each claim's recorded checks against the live sources.

  Args:
    summary: The collected summary holding a `provenance` block.
    claim_ids: Claim IDs to check, or `["all"]`.
    runners: The query runners to execute each check with.

  Returns:
    One result per claim: its checks' outcomes and recorded differences, or an
    `error` when the claim is unknown.
  """
  claims = summary["provenance"]["claims"]
  project = summary["project_id"]
  if claim_ids == ["all"]:
    claim_ids = list(claims)
  # A claim built from others (the floor from its actions) re-checks them too.
  for cid in list(claim_ids):
    if cid in claims:
      claim_ids += [r for r in claims[cid]["see_also"] if r not in claim_ids]
  out = []
  for cid in claim_ids:
    claim = claims.get(cid)
    if not claim:
      out.append({"claim": cid, "error": "no such claim in provenance"})
      continue
    results = [evaluate_check(c, project, runners) for c in claim["checks"]]
    out.append({
        "claim": cid,
        "title": claim["title"],
        "value": claim["value"],
        "checks": results,
        "differences": claim["differences"],
    })
  return out


def render(results: List[Dict[str, Any]]) -> str:
  """Formats `verify` results as one ✓/✗ line per check, for the chat."""
  lines = []
  for res in results:
    if res.get("error"):
      lines.append(f"✗ {res['claim']}: {res['error']}")
      continue
    lines.append(f"■ {res['title']} — report says {res['value']}")
    if not res["checks"]:
      lines.append("  (no live check for this claim; see its sources)")
    for chk in res["checks"]:
      if chk.get("error"):
        lines.append(f"  ✗ {chk['label']}: could not run — {chk['error']}")
        continue
      for r in chk["rows"]:
        mark = "✓" if r["ok"] else "△"
        lines.append(
            f"  {mark} {chk['label']} [{r['key']}]: report {r['expected']}"
            f" · now {r['measured']} {r['unit']}".rstrip()
            + f" · Δ {r['delta']:+} {r['delta_unit']}"
        )
  return "\n".join(lines)


def main(argv: Optional[List[str]] = None) -> int:
  parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
  parser.add_argument("--summary", default="logging_usage_summary.json")
  parser.add_argument(
      "--claim",
      action="append",
      required=True,
      help="Claim id (repeatable), or 'all'.",
  )
  parser.add_argument(
      "--json", action="store_true", help="Print machine-readable results."
  )
  args = parser.parse_args(argv)
  with open(args.summary, encoding="utf-8") as f:
    summary = json.load(f)
  results = verify(summary, args.claim, Runners())
  print(json.dumps(results, indent=2) if args.json else render(results))
  errored = any(
      r.get("error") or any(c.get("error") for c in r.get("checks", []))
      for r in results
  )
  return 1 if errored else 0


if __name__ == "__main__":
  sys.exit(main())
waste.py 19.1 KB
"""Extraneous log spend model for Cloud Logging FinOps.

Computes a conservative floor for recoverable spend from billing/bytes_ingested
and byte_count only; Log Analytics payload bytes overstate billed volume ~2x.
Each lever is emitted as an `actions.Action`; the headline is the sum of the
counted ones, priced on exactly the claims their remedy can act on.
"""

import re
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple

from actions import Action
from actions import ALL_SEVERITIES
from actions import Claim
from actions import filter_from_claims
from actions import SOURCE_LEVER
from constants import billable_gib
from constants import BYTES_PER_GIB
from constants import FLOW_LOG_TARGET_SAMPLING
from constants import IMMUTABLE_RETENTION_BUCKETS
from constants import INCLUDED_RETENTION_DAYS
from constants import WASTE_SANITY_CEILING_PCT
from exclusion_rules import decode_log_id
from exclusion_rules import is_data_access
from exclusion_rules import is_free_required
import messages
from pricing import PriceBook

# Matches LOG_ID("...") / logName tokens inside a Log Router filter.
_LOG_ID_RE = re.compile(r'LOG_ID\(\s*"([^"]+)"\s*\)', re.IGNORECASE)
_LOG_NAME_RE = re.compile(r'logs/([^"\s$]+)', re.IGNORECASE)

# Max share a "dead" exclusion target may still carry (tolerates stragglers).
_DEAD_RULE_MAX_SHARE = 0.02

# Removing one of two destinations recovers half the billed bytes (a floor).
_DUPLICATE_COPY_FRACTION = 0.5

# Unfiltered sinks pair up combinatorially; evidence shows a sample plus count.
_MAX_EVIDENCE_PAIRS = 8

_LOG_ID_TERM = r'LOG_ID\(\s*"[^"]+"\s*\)'
# A sink filter of `NOT LOG_ID(...)` terms joined by AND, the shape of the stock
# `_Default` sink filter: "every stream but these".
_EXCLUSION_ONLY_FILTER_RE = re.compile(
    rf"^\s*NOT\s+{_LOG_ID_TERM}(\s+AND\s+NOT\s+{_LOG_ID_TERM})*\s*$",
    re.IGNORECASE,
)
# A sink exclusion of `LOG_ID(...)` terms joined by OR: drops whole streams.
_WHOLE_STREAM_EXCLUSION_RE = re.compile(
    rf"^\s*{_LOG_ID_TERM}(\s+OR\s+{_LOG_ID_TERM})*\s*$", re.IGNORECASE
)


class _ClaimLedger:
  """Prevents two levers from counting the same bytes twice.

  Each stream can be claimed at most once in total. `retain` records that only
  part of a stream stays billed (e.g. after dedup), scaling later claims.
  """

  def __init__(self) -> None:
    self._claimed: Dict[str, float] = {}
    self._retained: Dict[str, float] = {}

  def retain(self, key: str, factor: float) -> None:
    """Records that only `factor` of `key`'s bytes stay billed hereafter."""
    self._retained[key] = self.retained(key) * max(0.0, min(1.0, factor))

  def retained(self, key: str) -> float:
    return self._retained.get(key, 1.0)

  def claim(self, key: str, fraction: float) -> float:
    """Claims up to `fraction` of `key`'s billed rest; returns the share won."""
    # The returned share is relative to all of `key`'s bytes.
    fraction = max(0.0, min(1.0, fraction)) * self.retained(key)
    already = self._claimed.get(key, 0.0)
    granted = max(0.0, min(fraction, 1.0 - already))
    if granted > 0:
      self._claimed[key] = already + granted
    return granted


def _log_ids_in_filter(filter_expr: str) -> List[str]:
  """Extracts referenced log IDs, decoded, from a Log Router filter."""
  found = _LOG_ID_RE.findall(filter_expr or "")
  found += _LOG_NAME_RE.findall(filter_expr or "")
  return [decode_log_id(f).rstrip("$") for f in found]


def _stream_suffix(log_id: str) -> str:
  """Returns the service-independent suffix of a log ID."""
  # `compute.googleapis.com/vpc_flows` and
  # `networkmanagement.googleapis.com/vpc_flows` share the suffix `vpc_flows`,
  # which identifies a migrated stream as the successor of an excluded one.
  return log_id.rsplit("/", 1)[-1].lower()


def _sink_streams(
    sink: Dict[str, Any], log_ids: Set[str]
) -> Optional[Set[str]]:
  """Returns the log IDs a bucket sink provably stores, or None if unknown."""
  # Only empty filters and conjunctions of `NOT LOG_ID(...)` are evaluated, and
  # only whole-stream `LOG_ID(...)` exclusions are subtracted.
  expr = (sink.get("filter") or "").strip()
  if not expr:
    routed = set(log_ids)
  elif _EXCLUSION_ONLY_FILTER_RE.match(expr):
    routed = log_ids - set(_log_ids_in_filter(expr))
  else:
    return None
  for exclusion in sink.get("exclusions") or ():
    if exclusion.get("disabled"):
      continue
    excluded = (exclusion.get("filter") or "").strip()
    if not _WHOLE_STREAM_EXCLUSION_RE.match(excluded):
      return None
    routed -= set(_log_ids_in_filter(excluded))
  return routed


def _duplicate_pairs(
    sinks: Sequence[Dict[str, Any]], log_ids: Set[str]
) -> List[Tuple[str, str, Set[str]]]:
  """Returns `(a, b, overlap)` for bucket-sink pairs billing streams twice."""
  # Ingestion is billed per destination bucket. Only pairs whose overlap is
  # provable and non-empty are returned.
  routed = []
  for sink in sinks:
    if (
        "logging.googleapis.com" not in str(sink.get("destination", ""))
        or sink.get("name") == "_Required"
        or sink.get("disabled")
    ):
      continue
    streams = _sink_streams(sink, log_ids)
    if streams:
      routed.append((str(sink.get("name")), streams))
  pairs = []
  for i, (first, first_streams) in enumerate(routed):
    for second, second_streams in routed[i + 1 :]:
      overlap = first_streams & second_streams
      if overlap:
        pairs.append((first, second, overlap))
  return pairs


def _format_pairs(pairs: Sequence[Tuple[str, str, Set[str]]]) -> str:
  """Renders sink pairs for evidence prose, bounded to a readable sample."""
  shown = ", ".join(f"{a} + {b}" for a, b, _ in pairs[:_MAX_EVIDENCE_PAIRS])
  remainder = len(pairs) - _MAX_EVIDENCE_PAIRS
  if remainder > 0:
    return f"{shown}, and {remainder} more pair(s)"
  return shown


def compute_extraneous_spend(
    billed_by_service: Dict[str, float],
    byte_count_by_stream: Dict[Tuple[str, str], float],
    window_days: float,
    monthly_gib: float,
    price_book: PriceBook,
    project_id: str,
    sinks: Optional[Sequence[Dict[str, Any]]] = None,
    exclusions: Optional[Sequence[Dict[str, Any]]] = None,
    buckets: Optional[Sequence[Dict[str, Any]]] = None,
    flow_log_configs: Optional[Sequence[Dict[str, Any]]] = None,
    billed_window_gib: Optional[float] = None,
) -> Tuple[Dict[str, Any], List[Action]]:
  """Computes the conservative extraneous-spend floor and its lever actions.

  Args:
    billed_by_service: bytes from billing/bytes_ingested keyed by resource type,
      over the sample window.
    byte_count_by_stream: bytes from byte_count keyed by (log_id, severity).
    window_days: length of the measurement window in days.
    monthly_gib: gross monthly ingestion run-rate used as the baseline.
    price_book: per-SKU prices and baselines every saving is priced from.
    project_id: project the exclusion filters target.
    sinks: Log Router sinks.
    exclusions: project-level exclusions.
    buckets: log buckets with retention metadata.
    flow_log_configs: VPC flow log configs from the Compute / Network Management
      APIs.
    billed_window_gib: invoiced ingestion over the same window; preferred
      calibration anchor so numerator and (invoiced) denominator share a basis.

  Returns:
    `(extraneous_spend, lever_actions)`: the report contract, and the actions
    to pass to `actions.merge_actions`.
  """
  billable_monthly_gib = billable_gib(monthly_gib)
  if not byte_count_by_stream or billable_monthly_gib <= 0:
    return {
        "status": "insufficient_data",
        "reason": (
            "Authoritative volume metrics unavailable; refusing to estimate."
        ),
    }, []

  # Decoded once here so every comparison below is on plain IDs. Always-free
  # _Required streams are left out of every calculation.
  billable_streams: Dict[Tuple[str, str], float] = {}
  for (log_id, severity), num_bytes in byte_count_by_stream.items():
    key = (decode_log_id(log_id), severity)
    if not is_free_required(key[0]):
      billable_streams[key] = billable_streams.get(key, 0.0) + num_bytes

  # byte_count (received, carries log/severity labels) exceeds billed bytes by
  # ~1.5x, so rescale it onto the billed basis. Prefer the invoice as anchor.
  raw_stream_total = sum(billable_streams.values()) or 1.0
  if billed_window_gib is not None and billed_window_gib > 0:
    billed_total = billed_window_gib * BYTES_PER_GIB
  else:
    billed_total = sum(billed_by_service.values()) if billed_by_service else 0.0
  # Only ever scale down: if billed exceeds byte_count the labels are
  # incomplete, and inflating measured bytes would invent savings.
  calibration = min(
      billed_total / raw_stream_total if billed_total > 0 else 1.0, 1.0
  )
  billable_streams = {k: v * calibration for k, v in billable_streams.items()}
  total_stream_bytes = sum(billable_streams.values()) or 1.0

  bytes_by_log: Dict[str, float] = {}
  for (log_id, _), num_bytes in billable_streams.items():
    bytes_by_log[log_id] = bytes_by_log.get(log_id, 0.0) + num_bytes

  days = window_days if window_days > 0 else 1.0

  def monthly(num_bytes: float) -> float:
    return num_bytes / days * 30.0 / BYTES_PER_GIB

  def measured(log_id: str, severity: str) -> float:
    if severity == ALL_SEVERITIES:
      return bytes_by_log[log_id]
    return billable_streams[(log_id, severity)]

  ledger = _ClaimLedger()
  levers: List[Action] = []

  def add(
      lever_id: str,
      title: str,
      evidence: str,
      claims: Sequence[Tuple[str, str, float]] = (),
      manual_step: str = "",
      withheld: str = "",
      counted: bool = True,
      **kwargs: Any,
  ) -> None:
    """Prices one lever on the claims its remedy can act on."""
    # `claims` are `(log_id, severity|"*", window_bytes)`. A lever without a
    # manual step is remedied by an exclusion filter, so its claims pass the
    # same safety gate as every exclusion before anything is priced.
    claimed = [Claim(l, s, monthly(b)) for l, s, b in claims if b > 0]
    action = Action(
        id=lever_id,
        title=title,
        source=SOURCE_LEVER,
        evidence=evidence,
        manual_step=manual_step,
        withheld=withheld,
        **kwargs,
    )
    if manual_step or withheld:
      action.claims = claimed
    else:
      action.filter, action.claims, action.refused_claims = filter_from_claims(
          claimed, project_id
      )
      if not action.claims:
        action.withheld = messages.WITHHELD_NO_REMEDY
    gib = sum(c.monthly_gib for c in action.claims)
    action.counted = counted and gib > 0 and not action.withheld
    if gib > 0:
      gib_by_sku = price_book.split_by_logs(
          gib, ((c.log_id, c.monthly_gib) for c in action.claims)
      )
      action.monthly_gib = round(gib, 2)
      action.monthly_usd = price_book.saving(gib_by_sku)
      # Share of spend, not of volume: SKUs are priced differently.
      action.pct_of_billable = price_book.pct_of_spend(action.monthly_usd)
      action.gib_by_sku = {k: round(v, 2) for k, v in gib_by_sku.items() if v}
      # Prove It re-measures whole streams and scales by this share.
      stream_gib = sum(
          monthly(measured(c.log_id, c.severity)) for c in action.claims
      )
      action.stream_fraction = round(gib / stream_gib, 4)
    levers.append(action)

  # --- Duplicate bucket routing (billing mechanics) --------------------------
  dup_pairs = _duplicate_pairs(sinks or (), set(bytes_by_log))
  if dup_pairs:
    # Calibrated stream bytes include every copy; claim half (floor) of the
    # streams some pair provably routes twice.
    dup_claims = []
    for log_id in sorted(set().union(*(o for _, _, o in dup_pairs))):
      granted = ledger.claim(log_id, _DUPLICATE_COPY_FRACTION)
      ledger.retain(log_id, 1.0 - _DUPLICATE_COPY_FRACTION)
      dup_claims.append(
          (log_id, ALL_SEVERITIES, bytes_by_log[log_id] * granted)
      )
    add(
        "duplicate_bucket_routing",
        "Duplicate log bucket routing",
        "Sink pairs route the same streams to separate log buckets, and GCP"
        " bills ingestion once per destination bucket: "
        + _format_pairs(dup_pairs),
        dup_claims,
        manual_step=(
            "Add an exclusion to the redundant sink so each entry is billed to"
            " one destination bucket (google_logging_project_sink.exclusions)."
        ),
    )

  # --- Retention beyond the included 30 days (not measurable here) -----------
  over_retention = [
      b
      for b in buckets or ()
      if b["retention_days"] > INCLUDED_RETENTION_DAYS
      and b["bucket_id"] not in IMMUTABLE_RETENTION_BUCKETS
  ]
  if over_retention:
    add(
        "over_retention",
        "Buckets retaining logs beyond the included 30 days",
        "Buckets exceed the 30 days of retention included with ingestion: "
        + ", ".join(
            f"{b['bucket_id']} ({b['retention_days']}d)" for b in over_retention
        )
        + ". Per-bucket stored volume is not exposed by the metrics used"
        " here, so no savings are claimed.",
        manual_step=(
            "Reduce bucket retention to the 30 days included with ingestion"
            " (google_logging_project_bucket_config.retention_days)."
        ),
        counted=False,
        flag=messages.FLAG_NOT_QUANTIFIED,
    )

  # --- Stale exclusion: the rule's target stream moved -----------------------
  for exclusion in exclusions or ():
    if exclusion.get("disabled"):
      continue
    name = str(exclusion.get("name") or "exclusion")
    for log_id in _log_ids_in_filter(str(exclusion.get("filter") or "")):
      target_bytes = bytes_by_log.get(log_id, 0.0)
      if target_bytes / total_stream_bytes > _DEAD_RULE_MAX_SHARE:
        continue  # Rule is still doing its job.

      # Dead rule: a successor stream with the same suffix is the target.
      successors = {
          other: other_bytes
          for other, other_bytes in bytes_by_log.items()
          if other != log_id
          and not is_data_access(other)
          and _stream_suffix(other) == _stream_suffix(log_id)
          and other_bytes / total_stream_bytes > _DEAD_RULE_MAX_SHARE
      }
      stale_claims = [
          (other, ALL_SEVERITIES, other_bytes * ledger.claim(other, 1.0))
          for other, other_bytes in successors.items()
      ]
      if not any(b > 0 for _, _, b in stale_claims):
        continue
      add(
          f"stale_exclusion_intent::{_stream_suffix(log_id)}",
          f"Exclusion '{name}' no longer matches its target stream",
          f"Exclusion '{name}' targets LOG_ID(\"{log_id}\"), which now"
          f" carries only {monthly(target_bytes):.2f} GiB/mo. The equivalent"
          f" stream {', '.join(successors)} carries"
          f" {monthly(sum(successors.values())):.2f} GiB/mo and is matched by"
          " no exclusion. The documented intent was to drop this volume.",
          stale_claims,
          confidence="medium",
          flag=messages.FLAG_INTENT_INFERRED,
      )

  # --- VPC flow logs sampled above the vendor default ------------------------
  enabled = [
      c
      for c in flow_log_configs or ()
      if str(c.get("state", "")).upper() == "ENABLED"
  ]
  samplings = [
      float(c["flow_sampling"]) for c in enabled if c.get("flow_sampling")
  ]
  # The least-sampled config bounds what every config would shed. Volume per
  # config is unknown, so anything higher could claim bytes that stay.
  floor_sampling = min(samplings) if samplings else 0.0
  if floor_sampling > FLOW_LOG_TARGET_SAMPLING:
    reduction = 1.0 - FLOW_LOG_TARGET_SAMPLING / floor_sampling
    flow_claims = [
        (log_id, ALL_SEVERITIES, num_bytes * ledger.claim(log_id, reduction))
        for log_id, num_bytes in bytes_by_log.items()
        if _stream_suffix(log_id) == "vpc_flows"
    ]
    if any(b > 0 for _, _, b in flow_claims):
      add(
          "flow_log_oversampling",
          "VPC flow logs sampled above the GCP default",
          f"All {len(samplings)} enabled flow log configs with a known rate"
          f" sample at {floor_sampling:.2f} or more, against the GCP console"
          f" default of {FLOW_LOG_TARGET_SAMPLING}. Flows are still captured,"
          " at lower fidelity.",
          flow_claims,
          manual_step=(
              f"Set flow_sampling to the {FLOW_LOG_TARGET_SAMPLING} console"
              " default on the VPC flow log configs"
              " (google_compute_subnetwork.log_config.flow_sampling, or the"
              " Network Management vpcFlowLogsConfigs API)."
          ),
          confidence="medium",
      )

  # --- DEBUG severity in production ------------------------------------------
  debug_claims = []
  for (log_id, severity), num_bytes in billable_streams.items():
    if severity.upper() != "DEBUG" or is_data_access(log_id):
      continue
    stream_total = bytes_by_log[log_id]
    granted = ledger.claim(log_id, num_bytes / stream_total)
    debug_claims.append((log_id, severity, stream_total * granted))
  debug_bytes = sum(b for _, _, b in debug_claims)
  if debug_bytes > 0:
    add(
        "debug_severity",
        "DEBUG severity logs retained in production",
        f"{monthly(debug_bytes):.2f} GiB/mo of DEBUG logs across"
        f" {sum(1 for _, _, b in debug_claims if b > 0)} stream(s).",
        debug_claims,
    )

  # --- Data Access audit logs: reported, never offered -----------------------
  # Measured against what stays billed: a duplicate copy is counted once, by
  # the duplicate-routing lever.
  audit_claims = [
      (log_id, severity, v * ledger.retained(log_id))
      for (log_id, severity), v in billable_streams.items()
      if is_data_access(log_id)
  ]
  audit_bytes = sum(b for _, _, b in audit_claims)
  if audit_bytes > 0:
    add(
        "data_access_audit_logs",
        "Data Access audit logs",
        f"{monthly(audit_bytes):.2f} GiB/mo of Data Access audit logs.",
        audit_claims,
        withheld=messages.WITHHELD_DATA_ACCESS.format(gib=monthly(audit_bytes)),
        counted=False,
    )

  counted = [a for a in levers if a.counted]
  total_pct = round(sum(a.pct_of_billable for a in counted), 2)
  return {
      "status": "ok",
      "basis": {
          "window_days": window_days,
          "source": "billing/bytes_ingested + byte_count (Cloud Monitoring)",
          "byte_count_to_billed_calibration": round(calibration, 4),
          # Both sides of the calibration ratio, so Prove It can re-derive it.
          "calibration_anchor": (
              "billing_export"
              if billed_window_gib is not None and billed_window_gib > 0
              else "billing/bytes_ingested"
          ),
          "anchor_window_gib": round(billed_total / BYTES_PER_GIB, 2),
          "byte_count_window_gib": round(raw_stream_total / BYTES_PER_GIB, 2),
          "baseline_monthly_gib": round(monthly_gib, 2),
          "billable_monthly_gib": round(billable_monthly_gib, 2),
          "billable_monthly_cost_usd": price_book.baseline_cost,
      },
      # The sum of the counted actions in `reduction_actions`.
      "headline": {
          "pct_of_billable_spend": total_pct,
          "monthly_savings_usd": round(sum(a.monthly_usd for a in counted), 2),
          "monthly_savings_gib": round(sum(a.monthly_gib for a in counted), 2),
          "exceeds_sanity_ceiling": total_pct > WASTE_SANITY_CEILING_PCT,
      },
      "uncounted_total_pct": round(
          sum(a.pct_of_billable or 0.0 for a in levers if not a.counted), 2
      ),
  }, levers

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