# Optiwise - GCP project discovery and Compute Engine rightsizing V2

This archive replaces the previous normalized rightsizing delivery. It contains
complete files at repository-relative paths, not diffs. It does not contain
credentials, a complete repository, or existing unrelated migrations. Base:
Archive.zip + optiwise-rightsizing-normalise.zip, plus the reported Ruff and
Mypy corrections. The actual working branch after the user's local changes
was not available. Review the diff of bootstrap.py and config/batches.yaml
against current local files before replacing them, preserving unrelated work.

## 1. Architecture and configuration

Two standard DataBatchJob jobs use DET EXTRACT/TRANSFORM/LOAD, registry,
SQLAlchemy and ADC:

- `gcp.projects.discovery.daily` (04:00 UTC, `daily-discovery`), source
  `gcp_resource_manager_service_usage`, dataset `finops_gcp_project_directory`.
- `gcp.compute.rightsizing.daily` (05:00 UTC, `daily-rightsizing`), source
  `gcp_compute_monitoring_recommender`, dataset
  `finops_gcp_compute_rightsizing_collection`.

Both catalogue entries are disabled by default. Register both definitions and
both datasets in DET using your private SDK/administration conventions.
Configure the existing external .env using `config/gcp-rightsizing.env.example`.
Remove `GCP_RIGHTSIZING_PROJECT_IDS`. No static project list in ORGANIZATION mode.

`GCP_ORGANIZATION_ID` is required in all modes. The full organization hierarchy
is traversed in all three modes; FOLDER and EXPLICIT select the projects for
service discovery/rightsizing, not a different IAM security boundary. FOLDER
selects all descendants of configured numeric folder IDs; EXPLICIT selects
GCP_PROJECT_IDS. INCLUDE is an optional allowlist intersection and EXCLUDE
always wins. Unknown explicit/include/folder IDs fail the scan to catch typos.
Use organization-level IAM for this implementation; folder-only IAM requires
an adapted traversal entry point. The complete project/folder inventory is
retained even when a logical filter excludes projects. Only selected ACTIVE
projects have enabled services collected. `is_selected` indicates scope and
`is_present` indicates visibility in the last full scan, not a proof of deletion.
No project state is inferred from billing consumption.

Resource Manager v3 lists direct children; recursion follows all active
folders, pagination is consumed and repeated tokens are rejected. Service
Usage v1 lists enabled services by project number with a partial response
containing service name/title/state. A new project is included on the next
successful scan. APIs not listed for a selected ACTIVE project in a successful
scan are not enabled. For projects out of scope the absence of service rows
means unknown, not disabled. Project and folder payloads can contain labels;
review label sensitivity. No credentials or instance metadata are collected.

## 2. IAM and API activation

Grant both custom roles defined in config at the ORGANIZATION level:

- `optiwiseResourceDiscoveryReader`: Resource Manager and Service Usage reads.
- `optiwiseComputeRightsizingReader`: Compute inventory, Monitoring reads and
  native instance recommendations. No write, mutation or service enable rights.

Example (admin identity, not the collector):

```bash
export ORGANIZATION_ID=123456789012
export FINOPS_PROJECT_ID=my-finops-project
export SA_EMAIL=optiwise@my-finops-project.iam.gserviceaccount.com

gcloud services enable cloudresourcemanager.googleapis.com serviceusage.googleapis.com \
  --project="$FINOPS_PROJECT_ID"

# Use `gcloud iam roles update` rather than create if the role already exists.
gcloud iam roles create optiwiseResourceDiscoveryReader \
  --organization="$ORGANIZATION_ID" --file=config/gcp-resource-discovery-reader.yaml

gcloud iam roles create optiwiseComputeRightsizingReader \
  --organization="$ORGANIZATION_ID" --file=config/gcp-compute-rightsizing-reader.yaml

for ROLE in optiwiseResourceDiscoveryReader optiwiseComputeRightsizingReader; do
  gcloud organizations add-iam-policy-binding "$ORGANIZATION_ID" \
    --member="serviceAccount:$SA_EMAIL" \
    --role="organizations/$ORGANIZATION_ID/roles/$ROLE"
done
```

Terraform example: `examples/terraform/gcp-rightsizing/main.tf`, using the same
YAML definitions; merge/import into the existing IAM state rather than applying
an independent state for existing resources. If credentials explicitly use a
quota project, grant `roles/serviceusage.serviceUsageConsumer` on that project
only, not the organization. The needed underlying permission is
`serviceusage.services.use`; API activation in the consumer project may be
needed as indicated by GCP. A service account with existing project bindings
can retain them during validation; remove redundant project bindings only
once the inherited organization roles are tested. No roles are applied here.

Enable Compute, Monitoring and optionally Recommender on relevant projects
through the organization's normal administrative provisioning. The batch never
activates APIs. Rightsizing excludes projects without Compute enabled. If
Monitoring is disabled, it records API_DISABLED without erasing previous metric
rows for the same scope. If Recommender is disabled, the inventory is collected
without recommendations and marked PARTIAL; this replaces the same-day snapshot
(including older recommendation rows from that day). Neither is proof of no
usage or no recommendations. A 403, 429, HTTP failure or incomplete response
aborts extraction and DET records failure; no partial database publication.
For quotas, use external scheduled retry/backoff and inspect DET; for a much
larger organization consider Cloud Asset Inventory as Google recommends.

References:
- https://cloud.google.com/resource-manager/docs/listing-all-resources
- https://cloud.google.com/resource-manager/reference/rest/v3/projects/list
- https://cloud.google.com/service-usage/docs/reference/rest/v1/services/list
- https://cloud.google.com/iam/docs/roles-permissions/recommender
- https://cloud.google.com/compute/docs/reference/rest/v1/instanceGroupManagers/aggregatedList
- https://cloud.google.com/iam/docs/roles-permissions/serviceusage

## 3. DDL / migration / retention

Fresh install: execute 050, 051, 052 in that order. Existing install with 050:
execute 051 and 052 only. 050 is unchanged; 051 creates five directory tables;
052 adds two status columns (MariaDB ADD COLUMN IF NOT EXISTS), and labels
legacy successful-empty rows NO_DATA. It does not erase metric history.
DDL is not executed automatically; backup and apply in recipe first.

| Table | Grain | Retention |
| --- | --- | --- |
| finops_gcp_project_bronze | organization/day/kind/resource | 30 days |
| finops_gcp_folder_silver | organization/folder | current + tombstones, permanent |
| finops_gcp_project_silver | organization/project number | current + tombstones, permanent |
| finops_gcp_project_service_silver | organization/project number/enabled API | current only, replaced after successful full scan |
| finops_gcp_project_discovery_status | organization | last successful publication |
| finops_gcp_compute_snapshot_bronze | project/day/kind/location/resource | 30 days |
| finops_gcp_compute_metric_silver | project/day/zone/instance/metric | 120 days |
| finops_gcp_compute_collection_status | project/day/kind | 120 days |

Directory publication is atomic: lock current generation, reject stale writes,
replace same-day Bronze, mark absent folders/projects, retain first_seen_at,
replace current enabled services and update publication marker in one transaction.
For directory Bronze, all expired rows for this organization are deleted per
successful run. Compute retention remains bounded (1000 rows per table per
run); for fleets where more expire, schedule repeated bounded SQL deletes or
use the existing partition manager. At 100 VMs, 11 metrics/day, 120 days,
expect at most 132,000 metric rows before purge backlog and indexes; at 2 KB
per row approximately 264 MB. Machine type snapshots may be significant.
No raw Monitoring points are persisted. Histograms remain sparse and versioned.

Collection statuses: SUCCESS = nonempty complete source; NO_DATA = successful
empty source; API_DISABLED = metrics not collected, older rows preserved;
PARTIAL = inventory collected without native recommendations. The status row
represents the latest attempt loaded, not necessarily the same ingestion run
as preserved metric rows. Future rule engines must join/check status and
coverage, not interpret API_DISABLED/PARTIAL as absence. HTTP failures and
DISCOVERY_STALE are DET failures, not statuses synthesized into database rows.

## 4. Execution

Schedule the two jobs as a dependent chain, not only separate independent cron
entries. Use one external lock for the chain (prevent concurrent discovery,
replays and rightsizing runs) and `&&` to stop on a failed discovery:

```bash
finops-batches run gcp.projects.discovery.daily && \
finops-batches run gcp.compute.rightsizing.daily
```

Default business date is yesterday UTC. Discovery only accepts J-1 and writes
actual collection date, not historical fake snapshots. Rightsizing reads a
successful directory for the configured organization and matching scope hash,
collected today UTC and within `GCP_DISCOVERY_MAX_AGE_HOURS`. If discovery fails
before any publication today, old directory is rejected. A same-day earlier
successful generation may still be fresh: use the chained command to stop on
failure of a later refresh. Changed scope requires a new discovery.

The complete empty scope returns successful zero rows without deleting data.
Historical rightsizing replays use the current project scope and current API
states; they do not recreate historical scope or VM configuration. Deleted
projects not in the current scope cannot be backfilled by this implementation.
Use `run` to force replay, including previously successful dates with disabled
APIs; `backfill` skips DET-successful dates. Example initial metrics backfill:

```bash
finops-batches run gcp.projects.discovery.daily
finops-batches run gcp.compute.rightsizing.daily --from 2026-10-25 --to 2026-11-23
```

Adjust the dates. Rightsizing accepts the last 120 completed UTC days. Only J-1
collects current inventory, actual collection date is stored in the snapshot.
The implementation preserves the existing 11 metric definitions, histogram
logic and source field allowlist; Gold and recommendation rules are not part of
this delivery. Real Monitoring sampling, disk/network limits and Ops Agent
coverage still need validation. Missing memory metrics are not zero.

## 5. Verification / rollback

Run in the actual development environment:

```bash
ruff format --check .
ruff check --no-cache .
mypy --cache-dir=/tmp/optiwise-batchs-mypy-cache src
PYTHONDONTWRITEBYTECODE=1 pytest -p no:cacheprovider
git diff --check
```

Archive lacks .git, AGENTS.md, pyproject.toml and private DET SDK. Isolated tests
use Python 3.13 in this environment, with SQLite rather than MariaDB locking;
project target remains Python >=3.12. See delivery report for actual results.
Google auth/DET integration, actual API responses, real MariaDB migrations and
Ruff/Mypy must be verified in the real repository.

Rollback: disable the two catalogue entries and schedules; restore earlier
rightsizing files only if desired, then restore GCP_RIGHTSIZING_PROJECT_IDS.
Keep additive DDL and data; earlier loader can ignore extra status columns.
Do not drop tables or revoke inherited roles until backup and explicit approval.
No commits, pushes, Merge Requests, IAM changes or deployments performed.
