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/reconcile.py ADDED
@@ -0,0 +1,334 @@
1
+ """``cloudleak reconcile``: compare an export with the invoice it should add up to.
2
+
3
+ The comparison is exact. Only billed-basis rows take part (amortized cost is
4
+ not what an invoice charges), and only rows in the invoice's currency; rows in
5
+ other currencies are reported as excluded, never converted.
6
+
7
+ A match does not prove completeness (offsetting errors cancel), and a
8
+ preliminary period is reported as not conclusive.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import csv
14
+ import io
15
+ import re
16
+ from dataclasses import dataclass, field
17
+ from decimal import Decimal
18
+ from pathlib import Path
19
+
20
+ from cloudleak.analysis import period_statuses
21
+ from cloudleak.engine import Workspace
22
+ from cloudleak.errors import InputError
23
+ from cloudleak.findings import Finding
24
+ from cloudleak.money import ZERO, display, fmt, money_context
25
+ from cloudleak.providers.base import Columns, quote_ident
26
+
27
+ AMOUNT_RE = re.compile(r"[+-]?[0-9]{1,26}(?:\.[0-9]{1,18})?")
28
+ PERIOD_RE = re.compile(r"[0-9]{4}-(0[1-9]|1[0-2])")
29
+
30
+
31
+ def parse_amount(text: str, what: str = "amount") -> Decimal:
32
+ value = text.strip()
33
+ if not AMOUNT_RE.fullmatch(value):
34
+ raise InputError(f"{what} {text!r} is not a plain decimal (no thousands separators or symbols)")
35
+ return Decimal(value)
36
+
37
+
38
+ @dataclass
39
+ class Expectation:
40
+ total: Decimal
41
+ currency: str
42
+ invoice_id: str | None = None
43
+ period: str | None = None
44
+ provider: str | None = None
45
+ label: str | None = None
46
+ issuer: str | None = None
47
+ billing_account: str | None = None
48
+
49
+ def __post_init__(self) -> None:
50
+ self.currency = self.currency.strip().upper()
51
+ if not re.fullmatch("[A-Z]{3}", self.currency):
52
+ raise InputError(f"currency {self.currency!r} must be a three-letter ISO 4217 code")
53
+ if self.period and not PERIOD_RE.fullmatch(self.period):
54
+ raise InputError(f"period {self.period!r} must look like YYYY-MM")
55
+ if not self.invoice_id and not self.period:
56
+ raise InputError("each invoice needs an invoice ID or a billing period (YYYY-MM)")
57
+
58
+ @property
59
+ def name(self) -> str:
60
+ return self.label or self.invoice_id or f"{self.provider or 'all providers'} {self.period}"
61
+
62
+
63
+ @dataclass
64
+ class Result:
65
+ expectation: Expectation
66
+ status: str # match | difference | no_rows | not_conclusive
67
+ export_total: Decimal
68
+ difference: Decimal
69
+ rows: int
70
+ components: dict[str, Decimal]
71
+ excluded_other_currency: list[dict]
72
+ excluded_amortized_rows: int
73
+ finality: str
74
+ providers: list[str]
75
+ tolerance: Decimal
76
+ notes: list[str] = field(default_factory=list)
77
+ invoices: list[dict] = field(default_factory=list)
78
+
79
+ def to_dict(self) -> dict:
80
+ e = self.expectation
81
+ return {
82
+ "invoice": {"invoice_id": e.invoice_id, "period": e.period, "provider": e.provider,
83
+ "currency": e.currency, "total": fmt(e.total), "issuer": e.issuer,
84
+ "billing_account": e.billing_account},
85
+ "status": self.status,
86
+ "export_total": fmt(self.export_total),
87
+ "difference": fmt(self.difference),
88
+ "difference_meaning": "export minus invoice",
89
+ "arithmetic_comparison": ("no_rows" if not self.rows else "equal" if self.difference == 0
90
+ else "within_tolerance" if self.difference.copy_abs() <= self.tolerance
91
+ else "different"),
92
+ "tolerance": fmt(self.tolerance),
93
+ "rows": self.rows,
94
+ "components": {k: fmt(v) for k, v in sorted(self.components.items())},
95
+ "period_finality": self.finality,
96
+ "providers": self.providers,
97
+ "excluded_other_currency": [{**x, "amount": fmt(x["amount"])} for x in self.excluded_other_currency],
98
+ "excluded_amortized_rows": self.excluded_amortized_rows,
99
+ "invoices_in_scope": self.invoices,
100
+ "notes": self.notes,
101
+ }
102
+
103
+
104
+ def load_invoices(path: str | Path) -> list[Expectation]:
105
+ """CSV with columns: total, currency, and invoice_id and/or period; optional provider, label."""
106
+ p = Path(path)
107
+ try:
108
+ text = p.read_text(encoding="utf-8-sig")
109
+ except (OSError, UnicodeDecodeError) as exc:
110
+ raise InputError(f"{p}: cannot read invoice file ({exc})") from exc
111
+ reader = csv.DictReader(io.StringIO(text, newline=""), strict=True)
112
+ headers = [f.strip().lower() for f in (reader.fieldnames or [])]
113
+ fields = set(headers)
114
+ if len(fields) != len(headers):
115
+ raise InputError(f"{p}: duplicate invoice column")
116
+ if not {"total", "currency"} <= fields or not ({"invoice_id", "period"} & fields):
117
+ raise InputError(f"{p}: needs columns total, currency, and invoice_id and/or period")
118
+ out = []
119
+ for i, raw in enumerate(reader, 1):
120
+ if None in raw or None in raw.values():
121
+ raise InputError(f"{p}: row {i} has the wrong number of fields (quote amounts, no thousands separators)")
122
+ row = {(k or "").strip().lower(): (v or "").strip() for k, v in raw.items()}
123
+ out.append(Expectation(parse_amount(row["total"], f"row {i} total"), row["currency"],
124
+ row.get("invoice_id") or None, row.get("period") or None,
125
+ (row.get("provider") or "").lower() or None, row.get("label") or None,
126
+ row.get("issuer") or None, row.get("billing_account") or None))
127
+ if not out:
128
+ raise InputError(f"{p}: no invoices listed")
129
+ return out
130
+
131
+
132
+ _SCOPE_KEYS = ("invoice_id", "billing_period", "provider", "invoice_issuer", "billing_account_id")
133
+
134
+
135
+ def _could_belong(row: dict, anchor: dict) -> bool:
136
+ """Compare known scope evidence. Different service providers can share an issuer."""
137
+ keys = ["invoice_id", "billing_period", "invoice_issuer", "billing_account_id"]
138
+ if (not row["invoice_issuer"] or not anchor["invoice_issuer"]) and "focus" not in (row["provider"],
139
+ anchor["provider"]):
140
+ keys.append("provider")
141
+ return all(not row[k] or not anchor[k] or row[k] == anchor[k] for k in keys)
142
+
143
+
144
+ def _check_scope(rows: list[dict], selectors: dict, e: Expectation) -> list[dict]:
145
+ exact = [r for r in rows if all(r[k] == v for k, v in selectors.items())]
146
+ anchors = [r for r in exact if r["cost_basis"] != "amortized" and r["currency"] == e.currency]
147
+ for r in rows:
148
+ if r["cost_basis"] == "amortized":
149
+ continue
150
+ if r["currency"] and re.fullmatch("[A-Z]{3}", r["currency"]) and r["currency"] != e.currency:
151
+ continue
152
+ missing = [k for k, v in selectors.items() if r[k] != v]
153
+ if missing:
154
+ if not anchors or any(_could_belong(r, a) for a in anchors):
155
+ raise InputError(f"Rows could belong to this invoice but lack {', '.join(missing)}",
156
+ hint="Supply an export with complete invoice scope or isolate the correct delivery.")
157
+ continue
158
+ if not r["currency"] or not re.fullmatch("[A-Z]{3}", r["currency"]):
159
+ raise InputError("Billed rows have missing or invalid currency in this invoice scope.")
160
+ if r["cost_basis"] != "billed":
161
+ raise InputError("Rows in this invoice scope have unknown cost basis.",
162
+ hint="Identify the actual-cost delivery before reconciling.")
163
+ if r["invalid"]:
164
+ raise InputError("Billed rows have missing, invalid, or out-of-range amounts in this invoice scope.",
165
+ hint="Use decimal amounts that fit DECIMAL(38,12) exactly, including embedded credits.")
166
+ if r["coarse"]:
167
+ raise InputError("A Parquet floating-point billed amount is too large to resolve individual cents.",
168
+ hint="Supply an exact decimal or text export from the billing system.")
169
+ # Known issuer identity can span multiple service providers, e.g. a marketplace.
170
+ issuers = {r["invoice_issuer"] for r in anchors}
171
+ if len(issuers) > 1 or (issuers == {None} and len({r["provider"] for r in anchors}) > 1):
172
+ raise InputError("An invoice comparison must select one issuer.",
173
+ hint="Select --issuer or provide files from a single issuer.")
174
+ if len({r["billing_account_id"] for r in anchors}) > 1:
175
+ raise InputError("Invoice scope spans multiple or unidentified billing accounts.",
176
+ hint="Select --billing-account or supply one account's export.")
177
+ if not e.invoice_id and len({r["invoice_id"] for r in anchors}) > 1:
178
+ ids = sorted(str(r["invoice_id"]) for r in anchors if r["invoice_id"])
179
+ raise InputError("This period contains multiple or partially identified invoices"
180
+ + (f" ({', '.join(ids[:6])})" if ids else "") + "; an invoice total covers one of them.",
181
+ hint="Select --invoice-id or supply one invoice's export.")
182
+ return exact
183
+
184
+
185
+ @money_context
186
+ def reconcile(ws: Workspace, expectations: list[Expectation], tolerance: Decimal = ZERO) -> list[Result]:
187
+ for source in ws.recognized:
188
+ if not source.header_issues:
189
+ continue
190
+ mapping = source.mapping
191
+ expressions = (mapping.cost, mapping.invoice_id, mapping.invoice_issuer, mapping.currency,
192
+ mapping.billing_account_id, mapping.billing_period_start, mapping.provider_sql or "")
193
+ for first, second in Columns.from_names(source.columns).collisions:
194
+ if any(quote_ident(first) in expr for expr in expressions):
195
+ raise InputError(f"Ambiguous invoice columns {first!r} and {second!r} in {source.file.display_name}.")
196
+ statuses = period_statuses(ws)
197
+ compared = set()
198
+ requested = set()
199
+ results = []
200
+ for e in expectations:
201
+ values = (e.invoice_id, e.period, e.provider, e.issuer, e.billing_account)
202
+ if (values, e.currency) in requested:
203
+ raise InputError("Duplicate invoice expectation in the same scope and currency.")
204
+ requested.add((values, e.currency))
205
+ selectors = {k: v for k, v in zip(_SCOPE_KEYS, values) if v}
206
+ where = " AND ".join(f"{k} = ?" for k in selectors)
207
+ possible = " AND ".join("(provider = ? OR provider = 'focus')" if k == "provider"
208
+ else f"({k} = ? OR {k} IS NULL)" for k in selectors)
209
+ params = list(selectors.values())
210
+ rows = ws.rows(f"""
211
+ SELECT source_id, invoice_id, billing_period, provider, invoice_issuer, billing_account_id,
212
+ currency, cost_basis,
213
+ count(*) AS n, sum(cost) AS amount, count(*) - count(cost) AS invalid,
214
+ bool_or(billed_precision = 'cent_resolution_lost') AS coarse,
215
+ bool_or(billed_precision <> 'decimal') AS approximate
216
+ FROM items WHERE {possible} GROUP BY ALL ORDER BY ALL""", params)
217
+ scoped = _check_scope(rows, selectors, e)
218
+ billed = [r for r in scoped if r["cost_basis"] == "billed" and r["currency"] == e.currency]
219
+ keys = {tuple(r[k] for k in _SCOPE_KEYS) + (e.currency,) for r in billed}
220
+ if compared & keys:
221
+ raise InputError("Invoice expectations overlap and would reuse the same billed rows.")
222
+ compared.update(keys)
223
+ other = [{"currency": r["currency"], "rows": r["n"], "amount": None if r["invalid"] else r["amount"]}
224
+ for r in scoped if r["currency"] != e.currency and r["cost_basis"] == "billed"]
225
+ amortized = sum(r["n"] for r in scoped if r["cost_basis"] == "amortized")
226
+ comp_rows = ws.rows(f"""SELECT charge_category, sum(cost) AS amount, sum(cost - gross_cost) AS embedded
227
+ FROM items WHERE {where} AND currency = ? AND cost_basis = 'billed'
228
+ GROUP BY 1 ORDER BY 1""", [*params, e.currency])
229
+ components = {r["charge_category"]: r["amount"] for r in comp_rows}
230
+ embedded = sum((r["embedded"] or ZERO for r in comp_rows), ZERO)
231
+ if embedded:
232
+ components["credits_included_in_usage"] = embedded
233
+ n = sum(r["n"] for r in billed)
234
+ total = sum((r["amount"] for r in billed), ZERO)
235
+ diff = total - e.total
236
+ invoices = []
237
+ if not e.invoice_id:
238
+ invoices = ws.rows(f"""SELECT COALESCE(invoice_id, '(no invoice id)') AS invoice_id, sum(cost) AS amount,
239
+ count(*) AS rows
240
+ FROM valid WHERE {where} AND currency = ? AND cost_basis = 'billed'
241
+ GROUP BY 1 ORDER BY 1""", [*params, e.currency])
242
+ providers = sorted({r["provider"] for r in billed})
243
+ scopes = {(r["provider"], r["billing_account_id"], r["billing_period"]) for r in billed}
244
+ fins = {s.finality for s in statuses if (s.provider, s.billing_account_id, s.billing_period) in scopes
245
+ and s.currency == e.currency and s.cost_basis == "billed"}
246
+ if any(period is None for _, _, period in scopes):
247
+ fins.add("unknown")
248
+ finality = ("preliminary_estimate" if "preliminary_estimate" in fins
249
+ else "finalized" if fins == {"finalized"} else "unknown")
250
+ approximate = any(r["approximate"] for r in billed)
251
+ source_ids = {r["source_id"] for r in billed}
252
+ missing_credits = any(s.file.source_id in source_ids and s.detected == "gcp"
253
+ and not s.mapping.capabilities.get("credits") for s in ws.recognized)
254
+ notes = []
255
+ if not n:
256
+ status = "no_rows"
257
+ notes.append("No billed rows match this invoice's scope and currency.")
258
+ elif abs(diff) > tolerance:
259
+ status = "difference"
260
+ notes.extend(_explanations(providers, components, diff, finality))
261
+ else:
262
+ identified = all(r["invoice_id"] and r["billing_account_id"] for r in billed)
263
+ status = "match" if identified and finality == "finalized" and not approximate else "not_conclusive"
264
+ if diff:
265
+ notes.append(f"Residual {fmt(diff)} {e.currency} falls within tolerance {fmt(tolerance)}.")
266
+ else:
267
+ notes.append("The compared amounts are equal.")
268
+ if not identified:
269
+ notes.append("Missing invoice or billing account identity limits this comparison to the selected rows.")
270
+ if approximate:
271
+ notes.append("Binary floating-point source amounts limit this comparison to the stored values.")
272
+ if missing_credits:
273
+ notes.append("A GCP source lacks a credits column. Its gross cost cannot establish the net payable.")
274
+ if n and not any(r["invoice_issuer"] for r in billed):
275
+ notes.append("The selected rows carry no invoice issuer name. Scope relies on the supplied "
276
+ "provider, account and invoice identifiers where available.")
277
+ if n and finality != "finalized":
278
+ notes.append(f"Period finality is {finality}. Invoice issuance and complete delivery are unconfirmed.")
279
+ if n:
280
+ notes.append("Offsetting errors can give equal totals even when individual lines differ.")
281
+ if other:
282
+ notes.append(f"Excluded {sum(o['rows'] for o in other):,} rows in other currencies.")
283
+ if amortized:
284
+ notes.append(f"Excluded {amortized:,} amortized-basis rows from the billed comparison.")
285
+ real_invoices = [i for i in invoices if i["invoice_id"] != "(no invoice id)"]
286
+ if len(real_invoices) > 1:
287
+ notes.append(f"This scope spans {len(real_invoices)} invoices (" + ", ".join(
288
+ f"{i['invoice_id']} {fmt(i['amount'])}" for i in real_invoices[:6]) + "); an invoice total covers "
289
+ "one of them. Reconcile each with --invoice-id.")
290
+ res = Result(e, status, total, diff, n, components, other, amortized, finality, providers, tolerance, notes)
291
+ res.invoices = [{"invoice_id": i["invoice_id"], "amount": fmt(i["amount"]), "rows": i["rows"]}
292
+ for i in invoices]
293
+ results.append(res)
294
+ return results
295
+
296
+
297
+ def _explanations(providers: list[str], components: dict[str, Decimal], diff: Decimal,
298
+ finality: str) -> list[str]:
299
+ out = []
300
+ if "tax" not in components and diff < 0:
301
+ out.append("The export has no tax lines; if the invoice includes tax, the export will be lower by that "
302
+ "amount (Azure cost exports generally exclude tax).")
303
+ if "aws" in providers and diff < 0 and finality != "finalized":
304
+ out.append("AWS support and other monthly fees can post days after the month closes; re-run on the "
305
+ "finalized export.")
306
+ if diff != 0 and abs(diff) < Decimal("0.05"):
307
+ out.append("A sub-cent to few-cent difference is consistent with invoice-level rounding; compare with a "
308
+ "rounding tolerance (--tolerance) if your invoices round per line.")
309
+ if diff > 0:
310
+ out.append("The export is higher than the invoice: check for charges billed on a different invoice "
311
+ "(for example AWS Marketplace, another billing entity or account) inside the same period.")
312
+ out.append("Credits or refunds applied at invoice level, or charges from another billing account, also "
313
+ "produce differences.")
314
+ return out
315
+
316
+
317
+ def reconciliation_findings(results: list[Result]) -> list[Finding]:
318
+ out = []
319
+ for r in results:
320
+ if r.status not in ("difference", "no_rows"):
321
+ continue
322
+ e = r.expectation
323
+ out.append(Finding(
324
+ rule_id="CL-REC-001", title="Invoice reconciliation difference",
325
+ summary=(f"Export total {display(r.export_total, e.currency)} vs invoice {display(e.total, e.currency)} "
326
+ f"for {e.name}: difference {display(r.difference, e.currency)} (export minus invoice)."),
327
+ classification="reconciliation_delta", evidence_level="L1",
328
+ severity="high" if r.finality == "finalized" else "medium",
329
+ provider=r.providers[0] if len(r.providers) == 1 else None, currency=e.currency,
330
+ billing_period=e.period, period_finality=r.finality, observed_cost=r.export_total, cost_basis="billed",
331
+ matched_rows=r.rows, action_risk="none_readonly",
332
+ details={"key": e.name, "invoice_total": e.total, "difference": r.difference, "notes": r.notes},
333
+ ))
334
+ return out