cloudleak-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cloudleak/findings.py ADDED
@@ -0,0 +1,223 @@
1
+ """The ``cloudleak.finding.v1`` contract and its invariants.
2
+
3
+ Evidence ladder (CloudLeak's billing-only ceiling is Level 2):
4
+
5
+ L1 billing observation validated line items; spend, reconciliation, variance
6
+ L2 billing-supported hypothesis a provider-explicit billing signature
7
+ L3 corroborated by an offline inventory snapshot (not produced from billing alone)
8
+ L4 owner-confirmed recommendation (recorded by people, not inferred)
9
+ L5 validated outcome on a later finalized bill (recorded by people, not inferred)
10
+
11
+ Invariants enforced at construction time, so no code path can emit a
12
+ finding that breaks them:
13
+
14
+ * ``verified_savings`` is always null at L1 and L2.
15
+ * L2 findings must list unknown information, potential false positives and
16
+ at least one read-only verification step.
17
+ * Verification steps are read-only; CloudLeak never emits a command that
18
+ changes infrastructure.
19
+ * Billing data alone can never produce L3-L5.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import json
26
+ import re
27
+ from dataclasses import asdict, dataclass, field
28
+ from decimal import Decimal
29
+ from typing import Any
30
+
31
+ from cloudleak.money import fmt
32
+
33
+ SCHEMA_VERSION = "cloudleak.finding.v1"
34
+ LEVELS = ("L1", "L2", "L3", "L4", "L5")
35
+ CLASSIFICATIONS = ("qa_defect", "reconciliation_delta", "variance_driver", "billing_signature_candidate")
36
+ FINALITY = ("finalized", "preliminary_estimate", "unknown")
37
+ REVIEW_STATUS = ("unreviewed", "investigating", "accepted", "dismissed", "resolved")
38
+ ACTION_RISK = ("none_readonly", "low", "medium", "high", "unknown")
39
+ SEVERITY = ("info", "low", "medium", "high")
40
+
41
+
42
+ class ContractViolation(AssertionError):
43
+ """A finding was constructed that breaks the evidence contract. Always a bug."""
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class VerificationStep:
48
+ description: str
49
+ command: str | None = None # read-only; shell-quoted
50
+ tool: str | None = None # aws | az | gcloud | console | sql
51
+ action_risk: str = "none_readonly"
52
+
53
+ def __post_init__(self) -> None:
54
+ if self.action_risk != "none_readonly":
55
+ raise ContractViolation("verification steps must be read-only")
56
+ if self.command:
57
+ # Quoted arguments are data (resource IDs from the export), not verbs.
58
+ unquoted = re.sub(r"'[^']*'", "''", self.command.lower())
59
+ lowered = f" {unquoted} "
60
+ for verb in (" delete", " terminate", " release-address", " remove", " destroy", " modify-",
61
+ " update ", " stop-", " deallocate", " purge", " rm "):
62
+ if verb in lowered:
63
+ raise ContractViolation(f"verification command looks mutating: {self.command!r}")
64
+
65
+
66
+ @dataclass
67
+ class Finding:
68
+ rule_id: str
69
+ title: str
70
+ summary: str
71
+ classification: str
72
+ evidence_level: str
73
+ severity: str
74
+ provider: str | None
75
+ currency: str | None
76
+ billing_period: str | None
77
+ period_finality: str
78
+ observed_cost: Decimal | None = None
79
+ observed_effective_cost: Decimal | None = None
80
+ cost_basis: str | None = None
81
+ billing_account_id: str | None = None
82
+ sub_account_id: str | None = None
83
+ resource_id: str | None = None
84
+ resource_id_source: str | None = None
85
+ region: str | None = None
86
+ service: str | None = None
87
+ matched_rows: int = 0
88
+ source_sha256: list[str] = field(default_factory=list)
89
+ sample_rows: list[dict[str, int]] = field(default_factory=list)
90
+ matched_values: list[str] = field(default_factory=list)
91
+ unknown_information: list[str] = field(default_factory=list)
92
+ potential_false_positives: list[str] = field(default_factory=list)
93
+ verification_steps: list[VerificationStep] = field(default_factory=list)
94
+ owner_routing: dict[str, Any] = field(default_factory=lambda: {"status": "unattributed"})
95
+ details: dict[str, Any] = field(default_factory=dict)
96
+ verified_savings: Decimal | None = None
97
+ review_status: str = "unreviewed"
98
+ action_risk: str = "unknown"
99
+ approval_history: list[dict] = field(default_factory=list)
100
+ verified_outcome: dict | None = None
101
+ observed_billed_cost: Decimal | None = None
102
+
103
+ def __post_init__(self) -> None:
104
+ self.check()
105
+
106
+ def check(self) -> None:
107
+ if self.evidence_level not in LEVELS:
108
+ raise ContractViolation(f"bad evidence level {self.evidence_level}")
109
+ if self.evidence_level in ("L3", "L4", "L5"):
110
+ raise ContractViolation("billing exports alone cannot produce evidence above L2")
111
+ if self.classification not in CLASSIFICATIONS:
112
+ raise ContractViolation(f"bad classification {self.classification}")
113
+ if self.period_finality not in FINALITY:
114
+ raise ContractViolation(f"bad period finality {self.period_finality}")
115
+ if self.severity not in SEVERITY or self.review_status not in REVIEW_STATUS:
116
+ raise ContractViolation("bad severity or review status")
117
+ if self.action_risk not in ACTION_RISK:
118
+ raise ContractViolation("bad action risk")
119
+ if self.evidence_level in ("L1", "L2") and self.verified_savings is not None:
120
+ raise ContractViolation("verified_savings must be null at L1 and L2")
121
+ if self.evidence_level == "L2":
122
+ if not self.unknown_information or not self.potential_false_positives:
123
+ raise ContractViolation("L2 findings must disclose unknowns and false positives")
124
+ if not self.verification_steps:
125
+ raise ContractViolation("L2 findings need at least one read-only verification step")
126
+ if self.verified_outcome is not None:
127
+ raise ContractViolation("verified outcomes are recorded by people at L5, never inferred")
128
+
129
+ def identity(self) -> dict[str, Any]:
130
+ """The fields that make a finding *this* finding (stable across runs)."""
131
+ return {
132
+ "rule_id": self.rule_id,
133
+ "provider": self.provider,
134
+ "billing_account_id": self.billing_account_id,
135
+ "sub_account_id": self.sub_account_id,
136
+ "resource_id": self.resource_id,
137
+ "region": self.region,
138
+ "billing_period": self.billing_period,
139
+ "currency": self.currency,
140
+ "cost_basis": self.cost_basis,
141
+ "key": self.details.get("key"),
142
+ }
143
+
144
+ @property
145
+ def finding_id(self) -> str:
146
+ blob = json.dumps(self.identity(), sort_keys=True, separators=(",", ":"))
147
+ return "clf_" + hashlib.sha256(blob.encode()).hexdigest()[:20]
148
+
149
+ def to_dict(self, *, report_run_id: str, reproducibility: dict) -> dict[str, Any]:
150
+ start, end = _period_bounds(self.billing_period)
151
+ return {
152
+ "schema_version": SCHEMA_VERSION,
153
+ "finding_id": self.finding_id,
154
+ "report_run_id": report_run_id,
155
+ "rule_id": self.rule_id,
156
+ "title": self.title,
157
+ "summary": self.summary,
158
+ "classification": self.classification,
159
+ "evidence_level": self.evidence_level,
160
+ "severity": self.severity,
161
+ "provider": self.provider,
162
+ "billing_account_id": self.billing_account_id,
163
+ "sub_account_id": self.sub_account_id,
164
+ "resource_id": self.resource_id,
165
+ "resource_id_source": self.resource_id_source,
166
+ "region": self.region,
167
+ "service": self.service,
168
+ "billing_period": self.billing_period,
169
+ "billing_period_start": start,
170
+ "billing_period_end": end,
171
+ "period_finality": self.period_finality,
172
+ "currency": self.currency,
173
+ "financials": {
174
+ "cost_basis": self.cost_basis,
175
+ "observed_cost": fmt(self.observed_cost),
176
+ "observed_billed_cost": fmt(self.observed_billed_cost),
177
+ "observed_effective_cost": fmt(self.observed_effective_cost),
178
+ "verified_savings": None,
179
+ },
180
+ "exact_evidence": {
181
+ "rule_id": self.rule_id,
182
+ "matched_rows": self.matched_rows,
183
+ "matched_values": sorted(self.matched_values)[:20],
184
+ "source_sha256": sorted(self.source_sha256),
185
+ "sample_rows": self.sample_rows[:10],
186
+ },
187
+ "unknown_information": list(self.unknown_information),
188
+ "potential_false_positives": list(self.potential_false_positives),
189
+ "required_verification_steps": [asdict(v) for v in self.verification_steps],
190
+ "owner_routing": self.owner_routing,
191
+ "details": _jsonable(self.details),
192
+ "review_status": self.review_status,
193
+ "action_risk": self.action_risk,
194
+ "approval_history": list(self.approval_history),
195
+ "verified_outcome": None,
196
+ "reproducibility": reproducibility,
197
+ }
198
+
199
+
200
+ def _period_bounds(period: str | None) -> tuple[str | None, str | None]:
201
+ if not period or len(period) != 7:
202
+ return None, None
203
+ year, month = int(period[:4]), int(period[5:])
204
+ ny, nm = (year + 1, 1) if month == 12 else (year, month + 1)
205
+ return f"{year:04d}-{month:02d}-01T00:00:00Z", f"{ny:04d}-{nm:02d}-01T00:00:00Z"
206
+
207
+
208
+ def _jsonable(value: Any) -> Any:
209
+ if isinstance(value, Decimal):
210
+ return fmt(value)
211
+ if isinstance(value, dict):
212
+ return {str(k): _jsonable(v) for k, v in value.items()}
213
+ if isinstance(value, (list, tuple)):
214
+ return [_jsonable(v) for v in value]
215
+ if hasattr(value, "isoformat"):
216
+ return value.isoformat()
217
+ return value
218
+
219
+
220
+ def sort_key(f: Finding) -> tuple:
221
+ sev = {"high": 0, "medium": 1, "low": 2, "info": 3}[f.severity]
222
+ cost = -(f.observed_cost or f.observed_effective_cost or Decimal(0))
223
+ return (sev, cost, f.rule_id, f.finding_id)
cloudleak/fixtures.py ADDED
@@ -0,0 +1,411 @@
1
+ """Deterministic synthetic billing exports with exact ground truth.
2
+
3
+ Every file written here is marked SYNTHETIC_TEST_FIXTURE_ONLY. The data is
4
+ invented; it imitates the *shape* of real exports, including the traps that
5
+ break naive tools:
6
+
7
+ * AWS: a finalized month and a preliminary month (blank bill_invoice_id),
8
+ tax, credits, a refund, a support fee, an unused reserved-instance fee,
9
+ idle and in-use public IPv4, NAT processing, cross-AZ transfer, gp2
10
+ volumes, snapshots, extended support, an intentionally expensive GPU
11
+ instance, and inconsistent tag keys.
12
+ * Azure: separate actual and amortized exports (summing both double counts),
13
+ identical amortized rows that must not be de-duplicated, unused
14
+ reservation, and MM/DD/YYYY dates.
15
+ * GCP: credits embedded in rows, late usage billed to the next invoice
16
+ month, labels as a JSON array, a tax row.
17
+ * FOCUS 1.2: an InvoiceId column that is present but entirely empty, and an
18
+ unused commitment.
19
+
20
+ ``generate()`` returns the exact totals so tests can assert reconciliation to
21
+ the last decimal place.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import calendar
27
+ import csv
28
+ import json
29
+ import random
30
+ from collections import defaultdict
31
+ from dataclasses import dataclass, field
32
+ from datetime import date, timedelta
33
+ from decimal import ROUND_HALF_EVEN, Decimal
34
+ from pathlib import Path
35
+
36
+ MARK = "SYNTHETIC_TEST_FIXTURE_ONLY"
37
+ Q10 = Decimal("0.0000000001")
38
+
39
+
40
+ def d(x: float | str | Decimal) -> Decimal:
41
+ return Decimal(str(x)).quantize(Q10, rounding=ROUND_HALF_EVEN)
42
+
43
+
44
+ def s(x: Decimal) -> str:
45
+ text = format(x.normalize(), "f")
46
+ return "0" if text in ("-0", "0") else text
47
+
48
+
49
+ @dataclass
50
+ class Truth:
51
+ """Ground truth: totals[(provider, basis, period, currency)] = Decimal."""
52
+
53
+ totals: dict[tuple[str, str, str, str], Decimal] = field(default_factory=lambda: defaultdict(Decimal))
54
+ by_category: dict[tuple[str, str, str], Decimal] = field(default_factory=lambda: defaultdict(Decimal))
55
+ files: list[Path] = field(default_factory=list)
56
+
57
+ def add(self, provider: str, basis: str, period: str, currency: str, amount: Decimal, cat: str) -> None:
58
+ self.totals[(provider, basis, period, currency)] += amount
59
+ self.by_category[(provider, period, cat)] += amount
60
+
61
+
62
+ def _days(year: int, month: int) -> list[date]:
63
+ return [date(year, month, i) for i in range(1, calendar.monthrange(year, month)[1] + 1)]
64
+
65
+
66
+ def _write(path: Path, header: list[str], rows: list[dict]) -> Path:
67
+ path.parent.mkdir(parents=True, exist_ok=True)
68
+ with path.open("w", newline="", encoding="utf-8") as fh:
69
+ w = csv.DictWriter(fh, fieldnames=header, lineterminator="\n")
70
+ w.writeheader()
71
+ for r in rows:
72
+ w.writerow({k: r.get(k, "") for k in header})
73
+ return path
74
+
75
+
76
+ # ----------------------------------------------------------------------- AWS
77
+ AWS_HEADER = [
78
+ "identity_line_item_id", "identity_time_interval", "bill_bill_type", "bill_billing_entity",
79
+ "bill_billing_period_start_date", "bill_billing_period_end_date", "bill_invoice_id",
80
+ "bill_payer_account_id", "bill_payer_account_name", "line_item_usage_account_id",
81
+ "line_item_usage_account_name", "line_item_line_item_type", "line_item_usage_start_date",
82
+ "line_item_usage_end_date", "line_item_product_code", "line_item_usage_type", "line_item_operation",
83
+ "line_item_resource_id", "line_item_usage_amount", "line_item_currency_code", "line_item_unblended_rate",
84
+ "line_item_unblended_cost", "line_item_line_item_description", "product_region_code",
85
+ "product_servicecode", "pricing_unit", "pricing_public_on_demand_cost", "reservation_reservation_arn",
86
+ "reservation_effective_cost", "reservation_unused_recurring_fee",
87
+ "reservation_unused_amortized_upfront_fee_for_billing_period", "savings_plan_savings_plan_effective_cost",
88
+ "savings_plan_total_commitment_to_date", "savings_plan_used_commitment", "resource_tags",
89
+ ]
90
+
91
+ PAYER, PROD, DATA = "210987654321", "123456789012", "000123456789"
92
+
93
+
94
+ def _aws(out: Path, year: int, month: int, finalized: bool, scale: int, rng: random.Random,
95
+ truth: Truth, growth: Decimal) -> Path:
96
+ period = f"{year:04d}-{month:02d}"
97
+ days = _days(year, month)
98
+ start = f"{period}-01T00:00:00Z"
99
+ end_day = days[-1] + timedelta(days=1)
100
+ end = f"{end_day.isoformat()}T00:00:00Z"
101
+ invoice = f"EUINAA{year % 100:02d}{month:02d}0001" if finalized else ""
102
+ rows: list[dict] = []
103
+ seq = 0
104
+
105
+ def add(account, ltype, product, usage_type, op, resource, qty, rate, desc, region="us-east-1",
106
+ day=None, unit="Hrs", tags=None, extra=None, cost=None, tag_style=0):
107
+ nonlocal seq
108
+ seq += 1
109
+ amount = d(cost) if cost is not None else d(Decimal(str(qty)) * Decimal(str(rate)))
110
+ s_day = day or days[0]
111
+ e_day = (s_day + timedelta(days=1)) if day else end_day
112
+ row = {
113
+ "identity_line_item_id": f"syn{period.replace('-', '')}{seq:07d}",
114
+ "identity_time_interval": f"{s_day.isoformat()}T00:00:00Z/{e_day.isoformat()}T00:00:00Z",
115
+ "bill_bill_type": "Anniversary", "bill_billing_entity": "AWS",
116
+ "bill_billing_period_start_date": start, "bill_billing_period_end_date": end,
117
+ "bill_invoice_id": invoice, "bill_payer_account_id": PAYER, "bill_payer_account_name": MARK,
118
+ "line_item_usage_account_id": account,
119
+ "line_item_usage_account_name": {PROD: "synthetic-prod", DATA: "synthetic-data"}.get(account, MARK),
120
+ "line_item_line_item_type": ltype,
121
+ "line_item_usage_start_date": f"{s_day.isoformat()}T00:00:00Z",
122
+ "line_item_usage_end_date": f"{e_day.isoformat()}T00:00:00Z",
123
+ "line_item_product_code": product, "line_item_usage_type": usage_type, "line_item_operation": op,
124
+ "line_item_resource_id": resource, "line_item_usage_amount": s(d(qty)),
125
+ "line_item_currency_code": "USD", "line_item_unblended_rate": s(d(rate)),
126
+ "line_item_unblended_cost": s(amount), "line_item_line_item_description": desc,
127
+ "product_region_code": region, "product_servicecode": product, "pricing_unit": unit,
128
+ "pricing_public_on_demand_cost": s(amount) if ltype == "Usage" else "",
129
+ "resource_tags": json.dumps(tags, sort_keys=True) if tags else "",
130
+ }
131
+ if extra:
132
+ row.update(extra)
133
+ rows.append(row)
134
+ cat = {"Usage": "usage", "Tax": "tax", "Credit": "credit", "Refund": "refund", "Fee": "fee",
135
+ "RIFee": "purchase"}.get(ltype, "other")
136
+ truth.add("aws", "billed", period, "USD", amount, cat)
137
+
138
+ g = growth
139
+ for day in days:
140
+ for i in range(2 * scale):
141
+ tags = {"user_team": "web", "user_env": "prod"} if i % 2 == 0 else {"user_Env": "prod"}
142
+ add(PROD, "Usage", "AmazonEC2", "BoxUsage:m6i.large", "RunInstances", f"i-0web{i:011x}",
143
+ 24, "0.096", "$0.096 per On Demand Linux m6i.large Instance Hour", day=day, tags=tags)
144
+ add(DATA, "Usage", "AmazonEC2", "BoxUsage:p4d.24xlarge", "RunInstances", "i-0gputrain0000001",
145
+ 24, "32.7726", "$32.7726 per On Demand Linux p4d.24xlarge Instance Hour", day=day,
146
+ tags={"user_team": "ml", "user_workload": "training"})
147
+ for i in range(scale):
148
+ add(PROD, "Usage", "AmazonEC2", "EBS:VolumeUsage.gp3", "CreateVolume-Gp3", f"vol-0prod{i:012x}",
149
+ d(Decimal(500) / len(days)), "0.08", "$0.08 per GB-month of gp3", unit="GB-Mo", day=day,
150
+ tags={"user_team": "web", "user_env": "prod"})
151
+ add(DATA, "Usage", "AmazonEC2", "EBS:VolumeUsage.gp2", "CreateVolume-Gp2", f"vol-0legacy{i:010x}",
152
+ d(Decimal(2000) / len(days)), "0.10", "$0.10 per GB-month of gp2", unit="GB-Mo", day=day)
153
+ add(DATA, "Usage", "AmazonEC2", "EBS:SnapshotUsage", "CreateSnapshot", f"snap-0arch{i:011x}",
154
+ d(Decimal(4000) * (1 + g * Decimal("0.5")) / len(days)), "0.05", "$0.05 per GB-Month of snapshot",
155
+ unit="GB-Mo", day=day)
156
+ add(PROD, "Usage", "AmazonEC2", "NatGateway-Hours", "NatGateway", "nat-0prod000000001", 24, "0.045",
157
+ "$0.045 per NAT Gateway Hour", day=day)
158
+ add(PROD, "Usage", "AmazonEC2", "NatGateway-Bytes", "NatGateway", "nat-0prod000000001",
159
+ d(Decimal(180) * (1 + g * 3)), "0.045", "$0.045 per GB Data Processed by NAT Gateways", unit="GB",
160
+ day=day)
161
+ add(PROD, "Usage", "AWSDataTransfer", "DataTransfer-Regional-Bytes", "InterZone-In", "",
162
+ d(Decimal(400) * (1 + g)), "0.01", "$0.010 per GB - regional data transfer", unit="GB", day=day)
163
+ add(PROD, "Usage", "AmazonVPC", "PublicIPv4:InUseAddress", "AssociateAddressVPC", "eipalloc-0inuse0001",
164
+ 24, "0.005", "$0.005 per In-use public IPv4 address per hour", day=day)
165
+ add(DATA, "Usage", "AmazonVPC", "PublicIPv4:IdleAddress", "AllocateAddressVPC", "eipalloc-0idle00001",
166
+ 24, "0.005", "$0.005 per Idle public IPv4 address per hour", day=day)
167
+ add(PROD, "Usage", "AmazonCloudWatch", "DataProcessing-Bytes", "PutLogEvents", "",
168
+ d(Decimal(30) * (1 + g * 2)), "0.50", "$0.50 per GB custom log data ingested", unit="GB", day=day)
169
+ add(DATA, "Usage", "AmazonRDS", "RDS:ExtendedSupport:Yr1-Yr2:MySQL5.7", "CreateDBInstance",
170
+ "arn:aws:rds:us-east-1:000123456789:db:legacy-reporting", 2 * 24, "0.100",
171
+ "$0.100 per vCPU-hour Extended Support Year 1-2 MySQL 5.7", day=day)
172
+ # Monthly line items
173
+ ri = "arn:aws:ec2:us-east-1:210987654321:reserved-instances/synthetic-ri-0001"
174
+ add(PAYER, "RIFee", "AmazonEC2", "HeavyUsage:m6i.xlarge", "RunInstances", ri, 720, "0.1200",
175
+ "Synthetic reserved instance recurring fee", extra={
176
+ "reservation_reservation_arn": ri, "reservation_unused_recurring_fee": s(d("21.60")),
177
+ "reservation_unused_amortized_upfront_fee_for_billing_period": "0"})
178
+ add(PAYER, "Usage", "AWSSupportBusiness", "Dollar", "", "", 1, "250.00", "AWS Support (Business)",
179
+ region="", unit="Dollar")
180
+ usage_total = sum(Decimal(r["line_item_unblended_cost"]) for r in rows)
181
+ add(PAYER, "Tax", "AmazonEC2", "Tax:AmazonEC2", "", "", 1, "0", "Synthetic sales tax", region="",
182
+ cost=d(usage_total * Decimal("0.0725")))
183
+ add(PROD, "Credit", "AmazonEC2", "Credit", "", "", 1, "0", "Synthetic promotional credit", region="",
184
+ cost=d("-150.00"))
185
+ if growth > 0:
186
+ add(DATA, "Refund", "AmazonEC2", "Refund", "", "", 1, "0", "Synthetic refund for service issue",
187
+ region="", cost=d("-42.17"))
188
+ name = f"{MARK}-aws-cur2-{period}.csv"
189
+ path = _write(out / name, AWS_HEADER, rows)
190
+ truth.files.append(path)
191
+ return path
192
+
193
+
194
+ # --------------------------------------------------------------------- Azure
195
+ AZURE_HEADER = [
196
+ "BillingAccountId", "BillingPeriodStartDate", "BillingPeriodEndDate", "SubscriptionId", "SubscriptionName",
197
+ "ResourceGroup", "ResourceId", "ResourceLocation", "Date", "MeterCategory", "MeterSubCategory", "MeterName",
198
+ "Quantity", "UnitOfMeasure", "EffectivePrice", "CostInBillingCurrency", "BillingCurrency", "ChargeType",
199
+ "PricingModel", "ReservationId", "Tags",
200
+ ]
201
+ AZ_SUB = "2f6c3d5e-8a91-4b7c-9d0e-1a2b3c4d5e6f"
202
+
203
+
204
+ def _azure(out: Path, year: int, month: int, scale: int, truth: Truth, growth: Decimal) -> list[Path]:
205
+ period = f"{year:04d}-{month:02d}"
206
+ days = _days(year, month)
207
+ paths = []
208
+ for basis in ("actual", "amortized"):
209
+ rows: list[dict] = []
210
+
211
+ def add(rg, res, cat, sub, meter, qty, price, day, ctype="Usage", pricing="OnDemand", tags=None,
212
+ rid="", _rows=rows, _basis=basis):
213
+ amount = d(Decimal(str(qty)) * Decimal(str(price)))
214
+ _rows.append({
215
+ "BillingAccountId": "SYNTHETIC-EA-0001", "BillingPeriodStartDate": f"{month:02d}/01/{year}",
216
+ "BillingPeriodEndDate": f"{month:02d}/{len(days):02d}/{year}", "SubscriptionId": AZ_SUB,
217
+ "SubscriptionName": f"{MARK}-subscription",
218
+ "ResourceGroup": rg, "ResourceId": (
219
+ f"/subscriptions/{AZ_SUB}/resourceGroups/{rg}/providers/{res}" if res else ""),
220
+ "ResourceLocation": "eastus", "Date": f"{day.month:02d}/{day.day:02d}/{day.year}",
221
+ "MeterCategory": cat, "MeterSubCategory": sub, "MeterName": meter, "Quantity": s(d(qty)),
222
+ "UnitOfMeasure": "1 Hour", "EffectivePrice": s(d(price)), "CostInBillingCurrency": s(amount),
223
+ "BillingCurrency": "USD", "ChargeType": ctype, "PricingModel": pricing, "ReservationId": rid,
224
+ "Tags": tags or "",
225
+ })
226
+ truth.add("azure", "billed" if _basis == "actual" else "amortized", period, "USD", amount,
227
+ "usage" if ctype in ("Usage", "UnusedReservation") else ctype.lower())
228
+
229
+ for day in days:
230
+ for i in range(scale):
231
+ add("rg-web", f"Microsoft.Compute/virtualMachines/vm-web-{i:02d}", "Virtual Machines",
232
+ "Dsv5 Series", "D4s v5", 24, "0.192", day, tags='"env": "prod","team": "web"')
233
+ add("rg-web", f"Microsoft.Compute/disks/vm-web-{i:02d}-os", "Storage",
234
+ "Premium SSD Managed Disks", "P10 LRS Disk", d(Decimal(1) / len(days)), "19.71", day,
235
+ tags='"env": "prod"')
236
+ add("rg-archive", "Microsoft.Compute/snapshots/snap-weekly", "Storage", "Standard HDD Managed Disks",
237
+ "Snapshots LRS Snapshot", d(Decimal(800) * (1 + growth) / len(days)), "0.05", day)
238
+ add("rg-net", "Microsoft.Network/natGateways/nat-hub", "NAT Gateway", "NAT Gateway",
239
+ "Data Processed", d(Decimal(120) * (1 + growth * 2)), "0.045", day)
240
+ add("rg-ops", "Microsoft.OperationalInsights/workspaces/law-main", "Log Analytics",
241
+ "Analytics Logs", "Data Ingestion", d(Decimal(12) * (1 + growth)), "2.30", day)
242
+ if basis == "amortized":
243
+ # Two genuinely identical rows: Azure documents this behavior.
244
+ for _ in range(2):
245
+ add("rg-batch", "Microsoft.Compute/virtualMachines/vm-batch-01", "Virtual Machines",
246
+ "Dsv5 Series", "D8s v5", 12, "0.2304", day, pricing="Reservation",
247
+ rid="synthetic-reservation-0001")
248
+ if basis == "actual":
249
+ add("", "", "Virtual Machines", "Reservation", "D8s v5 1 Year", 1, "1500.00", days[0],
250
+ ctype="Purchase", pricing="Reservation", rid="synthetic-reservation-0001")
251
+ else:
252
+ add("", "", "Virtual Machines", "Reservation", "D8s v5 1 Year", 1, "87.50", days[-1],
253
+ ctype="UnusedReservation", pricing="Reservation", rid="synthetic-reservation-0001")
254
+ path = _write(out / f"azure-{basis}" / f"{MARK}-azure-{basis}-{period}.csv", AZURE_HEADER, rows)
255
+ truth.files.append(path)
256
+ paths.append(path)
257
+ return paths
258
+
259
+
260
+ # ----------------------------------------------------------------------- GCP
261
+ GCP_HEADER = [
262
+ "billing_account_id", "service.id", "service.description", "sku.id", "sku.description", "usage_start_time",
263
+ "usage_end_time", "project.id", "project.name", "labels", "location.region", "resource.name",
264
+ "resource.global_name", "cost", "currency", "usage.amount", "usage.unit", "credits", "invoice.month",
265
+ "cost_type", "export_time",
266
+ ]
267
+
268
+
269
+ def _gcp(out: Path, year: int, month: int, scale: int, truth: Truth, growth: Decimal) -> Path:
270
+ period = f"{year:04d}-{month:02d}"
271
+ inv = f"{year:04d}{month:02d}"
272
+ days = _days(year, month)
273
+ rows: list[dict] = []
274
+
275
+ def add(svc, sku, project, resource, qty, price, day, unit="hour", labels=None, credit=None,
276
+ invoice_month=inv, ctype="regular", cost=None):
277
+ gross = d(cost) if cost is not None else d(Decimal(str(qty)) * Decimal(str(price)))
278
+ credits = []
279
+ if credit is not None:
280
+ credits = [{"name": "Sustained usage discount", "amount": float(d(credit)),
281
+ "type": "SUSTAINED_USAGE_DISCOUNT",
282
+ "id": "synthetic", "full_name": "Sustained usage discount"}]
283
+ credit_total = sum((d(c["amount"]) for c in credits), Decimal(0))
284
+ rows.append({
285
+ "billing_account_id": "01A2B3-C4D5E6-F7A8B9", "service.id": "6F81-5844-456A",
286
+ "service.description": svc, "sku.id": "SYN-" + sku[:8].upper().replace(" ", ""),
287
+ "sku.description": sku, "usage_start_time": f"{day.isoformat()} 00:00:00 UTC",
288
+ "usage_end_time": f"{(day + timedelta(days=1)).isoformat()} 00:00:00 UTC",
289
+ "project.id": project, "project.name": project,
290
+ "labels": json.dumps(labels) if labels else "[]", "location.region": "us-central1",
291
+ "resource.name": resource,
292
+ "resource.global_name": f"//compute.googleapis.com/{resource}" if resource else "",
293
+ "cost": s(gross), "currency": "USD", "usage.amount": s(d(qty)), "usage.unit": unit,
294
+ "credits": json.dumps(credits), "invoice.month": invoice_month, "cost_type": ctype,
295
+ "export_time": f"{day.isoformat()} 06:00:00 UTC",
296
+ })
297
+ ip = f"{invoice_month[:4]}-{invoice_month[4:]}"
298
+ truth.add("gcp", "billed", ip, "USD", gross + credit_total, "usage" if ctype == "regular" else ctype)
299
+
300
+ for day in days:
301
+ for i in range(scale):
302
+ add("Compute Engine", "N2 Instance Core running in Americas", "synthetic-analytics",
303
+ f"projects/synthetic-analytics/zones/us-central1-a/instances/etl-{i:02d}", 96, "0.031611", day,
304
+ labels=[{"key": "team", "value": "data"}], credit="-0.75")
305
+ add("Compute Engine", "Storage PD Capacity", "synthetic-analytics",
306
+ f"projects/synthetic-analytics/zones/us-central1-a/disks/etl-{i:02d}",
307
+ d(Decimal(500) / len(days)), "0.04", day, unit="gibibyte month")
308
+ add("Compute Engine", "Storage PD Snapshot in US", "synthetic-analytics",
309
+ "projects/synthetic-analytics/global/snapshots/nightly", d(Decimal(3000) / len(days)), "0.05", day,
310
+ unit="gibibyte month")
311
+ add("Compute Engine", "Cloud NAT Data Processing", "synthetic-analytics", "", d(Decimal(90) * (1 + growth)),
312
+ "0.045", day, unit="gibibyte")
313
+ add("Compute Engine", "Network Inter Zone Data Transfer Out", "synthetic-analytics", "",
314
+ d(Decimal(250) * (1 + growth)), "0.01", day, unit="gibibyte")
315
+ add("Cloud Logging", "Log Volume", "synthetic-analytics", "", d(Decimal(8) * (1 + growth * 4)), "0.50", day,
316
+ unit="gibibyte")
317
+ # Late usage for the last day of the month posts to the next invoice month.
318
+ nxt = days[-1] + timedelta(days=1)
319
+ add("BigQuery", "Analysis", "synthetic-analytics", "", 2, "6.25", days[-1],
320
+ unit="tebibyte", invoice_month=f"{nxt.year:04d}{nxt.month:02d}")
321
+ add("Invoice", "Tax", "", "", 1, "0", days[-1], unit="", ctype="tax", cost="31.40")
322
+ path = _write(out / f"{MARK}-gcp-detailed-{period}.csv", GCP_HEADER, rows)
323
+ truth.files.append(path)
324
+ return path
325
+
326
+
327
+ # --------------------------------------------------------------------- FOCUS
328
+ FOCUS_HEADER = [
329
+ "BilledCost", "EffectiveCost", "ListCost", "ContractedCost", "BillingAccountId", "BillingAccountName",
330
+ "BillingCurrency", "BillingPeriodStart", "BillingPeriodEnd", "ChargeCategory", "ChargeClass",
331
+ "ChargeDescription", "ChargePeriodStart", "ChargePeriodEnd", "CommitmentDiscountId",
332
+ "CommitmentDiscountStatus", "ConsumedQuantity", "ConsumedUnit", "InvoiceId", "PricingCategory",
333
+ "ProviderName", "PublisherName", "InvoiceIssuerName", "RegionId", "ResourceId", "ServiceCategory",
334
+ "ServiceName", "ServiceSubcategory", "SkuId", "SkuMeter", "SubAccountId", "SubAccountName", "Tags",
335
+ ]
336
+
337
+
338
+ def _focus(out: Path, year: int, month: int, truth: Truth, growth: Decimal) -> Path:
339
+ period = f"{year:04d}-{month:02d}"
340
+ days = _days(year, month)
341
+ rows = []
342
+ end = days[-1] + timedelta(days=1)
343
+
344
+ def add(cat, desc, svc, scat, meter, resource, qty, price, day, pcat="Standard", status="", effective=None,
345
+ tags=None):
346
+ billed = d(Decimal(str(qty)) * Decimal(str(price)))
347
+ rows.append({
348
+ "BilledCost": s(billed), "EffectiveCost": s(d(effective) if effective is not None else billed),
349
+ "ListCost": s(billed), "ContractedCost": s(billed), "BillingAccountId": "synthetic-oci-tenancy",
350
+ "BillingAccountName": MARK, "BillingCurrency": "USD",
351
+ "BillingPeriodStart": f"{period}-01T00:00:00Z", "BillingPeriodEnd": f"{end.isoformat()}T00:00:00Z",
352
+ "ChargeCategory": cat, "ChargeClass": "", "ChargeDescription": desc,
353
+ "ChargePeriodStart": f"{day.isoformat()}T00:00:00Z",
354
+ "ChargePeriodEnd": f"{(day + timedelta(days=1)).isoformat()}T00:00:00Z",
355
+ "CommitmentDiscountId": "synthetic-commit-01" if pcat == "Committed" else "",
356
+ "CommitmentDiscountStatus": status, "ConsumedQuantity": s(d(qty)), "ConsumedUnit": "Hours",
357
+ "InvoiceId": "", "PricingCategory": pcat, "ProviderName": "Synthetic Cloud",
358
+ "PublisherName": "Synthetic Cloud", "InvoiceIssuerName": "Synthetic Cloud", "RegionId": "us-ashburn-1",
359
+ "ResourceId": resource, "ServiceCategory": scat, "ServiceName": svc, "ServiceSubcategory": "",
360
+ "SkuId": "SYN-" + meter[:6].upper(), "SkuMeter": meter, "SubAccountId": "synthetic-compartment",
361
+ "SubAccountName": "synthetic-compartment", "Tags": json.dumps(tags) if tags else "",
362
+ })
363
+ truth.add("synthetic cloud", "billed", period, "USD", billed, cat.lower())
364
+
365
+ for day in days:
366
+ add("Usage", "Compute VM.Standard.E4", "Compute", "Compute", "OCPU Hours", "ocid1.instance.syn.app01",
367
+ 48, "0.025", day, tags={"team": "app"})
368
+ add("Usage", "Block Volume", "Block Storage", "Storage", "GB Month", "ocid1.volume.syn.app01",
369
+ d(Decimal(1000) * (1 + growth) / len(days)), "0.0255", day)
370
+ # FOCUS: unused commitment is BilledCost 0, EffectiveCost > 0 (billed by the purchase row).
371
+ add("Usage", "Unused commitment", "Compute", "Compute", "Commitment", "ocid1.commitment.syn.01", 1, "0",
372
+ day, pcat="Committed", status="Unused", effective="4.50")
373
+ add("Purchase", "Monthly commitment fee", "Compute", "Compute", "Commitment", "ocid1.commitment.syn.01",
374
+ 1, "135.00", days[0], pcat="Committed", effective="0")
375
+ path = _write(out / f"{MARK}-focus-1.2-{period}.csv", FOCUS_HEADER, rows)
376
+ truth.files.append(path)
377
+ return path
378
+
379
+
380
+ def generate(out: str | Path, *, scale: int = 1, seed: int = 20261120) -> Truth:
381
+ """Write a two-month multi-cloud demo corpus under ``out/m1`` and ``out/m2``."""
382
+ out = Path(out)
383
+ rng = random.Random(seed)
384
+ truth = Truth()
385
+ for folder, (year, month), finalized, growth in (
386
+ ("m1", (2026, 9), True, Decimal(0)),
387
+ ("m2", (2026, 10), False, Decimal("0.35")),
388
+ ):
389
+ base = out / folder
390
+ _aws(base / "aws", year, month, finalized, scale, rng, truth, growth)
391
+ _azure(base, year, month, scale, truth, growth)
392
+ _gcp(base / "gcp", year, month, scale, truth, growth)
393
+ _focus(base / "focus", year, month, truth, growth)
394
+ invoices = []
395
+ for provider in ("aws", "gcp"):
396
+ amount = truth.totals[(provider, "billed", "2026-09", "USD")]
397
+ invoices.append({
398
+ "provider": provider, "period": "2026-09", "invoice_id": "EUINAA26090001" if provider == "aws" else "",
399
+ "currency": "USD", "total": str(amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN)),
400
+ "label": f"{provider.upper()} invoice September (synthetic)",
401
+ })
402
+ _write(out / "invoices.csv", ["provider", "period", "invoice_id", "currency", "total", "label"], invoices)
403
+ (out / "README.md").write_text(
404
+ f"# {MARK}\n\nEvery file in this directory is synthetic test data generated by "
405
+ "`cloudleak demo`. Account IDs, resource names and amounts are invented.\n\n"
406
+ "From this directory, run `cloudleak reconcile m1 --invoices invoices.csv` to compare the "
407
+ "September exports with the synthetic invoices. Each invoice total is rounded to cents "
408
+ "after summing the billed amounts. The default comparison preserves any sub-cent difference.\n",
409
+ encoding="utf-8",
410
+ )
411
+ return truth