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/variance.py ADDED
@@ -0,0 +1,426 @@
1
+ """``cloudleak variance``: a deterministic month-over-month bridge.
2
+
3
+ The bridge answers "what moved, why, and who owns it" with arithmetic that
4
+ adds up exactly: base total + every driver = current total, per currency and
5
+ cost basis, to the last decimal place.
6
+
7
+ Drivers, computed at SKU grain (provider, account, service, SKU, unit):
8
+
9
+ new spend SKU absent in the base period
10
+ discontinued spend SKU absent in the current period
11
+ volume (q2 - q1) x base unit cost, when both periods carry quantities
12
+ rate remaining change at constant volume (price changes, commitment
13
+ coverage shifts, discounts applied per line)
14
+ unquantified change on SKUs without usable quantities
15
+ credits & refunds credit, refund and discount lines, plus credits embedded in rows (GCP)
16
+ tax tax lines
17
+ purchases & fees commitment purchases, recurring fees, one-off fees
18
+ adjustments adjustments, rounding and unrecognized charge types
19
+
20
+ Billing periods are invoice periods. When the two periods cover a different
21
+ number of days, percentage changes are reported per day; a raw percentage
22
+ across unequal periods is never emitted.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import re
28
+ from collections import defaultdict
29
+ from dataclasses import dataclass, field
30
+ from decimal import Decimal
31
+
32
+ from cloudleak.analysis import days_in, owner_routing, period_statuses
33
+ from cloudleak.engine import Workspace
34
+ from cloudleak.errors import InputError
35
+ from cloudleak.findings import Finding
36
+ from cloudleak.money import SCALE, ZERO, display, fmt, money_context
37
+
38
+ QUANT = Decimal(1).scaleb(-SCALE)
39
+ BUCKETS = ("coverage", "new", "discontinued", "volume", "rate", "unquantified", "credits", "tax", "purchases",
40
+ "adjustments")
41
+ BUCKET_LABELS = {
42
+ "coverage": "Export missing for one period", "new": "Newly observed spend",
43
+ "discontinued": "Spend absent from current rows", "volume": "Usage volume",
44
+ "rate": "Unit rate", "unquantified": "Other usage change", "credits": "Credits, refunds & discounts",
45
+ "tax": "Tax", "purchases": "Purchases & fees", "adjustments": "Adjustments & other",
46
+ }
47
+
48
+
49
+ @dataclass
50
+ class Bridge:
51
+ currency: str | None
52
+ cost_basis: str
53
+ base_period: str
54
+ current_period: str
55
+ base_total: Decimal
56
+ current_total: Decimal
57
+ buckets: dict[str, Decimal]
58
+ drivers: dict[str, list[dict]]
59
+ categories: list[dict]
60
+ services: list[dict]
61
+ top_keys: list[dict]
62
+ base_days: int | None
63
+ current_days: int | None
64
+ notes: list[str] = field(default_factory=list)
65
+ same_accounts: bool = True
66
+ gaps: list[str] = field(default_factory=list)
67
+
68
+ @property
69
+ @money_context
70
+ def delta(self) -> Decimal:
71
+ return self.current_total - self.base_total
72
+
73
+ @property
74
+ def comparable_days(self) -> bool:
75
+ """Full calendar months compare directly; otherwise only equal day counts do."""
76
+ if not self.base_days or not self.current_days:
77
+ return False
78
+ full = self.base_days == days_in(self.base_period) and self.current_days == days_in(self.current_period)
79
+ return full or self.base_days == self.current_days
80
+
81
+ @money_context
82
+ def pct_change(self) -> str | None:
83
+ """Percent change; per-day normalized when period lengths differ."""
84
+ if (self.base_total == 0 or not self.base_days or not self.current_days or not self.same_accounts
85
+ or self.gaps):
86
+ return None
87
+ if self.comparable_days:
88
+ b, c = self.base_total, self.current_total
89
+ else:
90
+ b = self.base_total / self.base_days
91
+ c = self.current_total / self.current_days
92
+ if b == 0:
93
+ return None
94
+ return str(((c - b) / abs(b) * 100).quantize(Decimal("0.1")))
95
+
96
+ def to_dict(self) -> dict:
97
+ def rows(items):
98
+ return [{k: (fmt(v) if isinstance(v, Decimal) else v) for k, v in i.items()} for i in items]
99
+ return {
100
+ "currency": self.currency, "cost_basis": self.cost_basis,
101
+ "base_period": self.base_period, "current_period": self.current_period,
102
+ "base_total": fmt(self.base_total), "current_total": fmt(self.current_total),
103
+ "delta": fmt(self.delta),
104
+ "percent_change": self.pct_change(),
105
+ "percent_change_basis": ("period_total" if self.comparable_days else "per_day")
106
+ if self.pct_change() is not None else None,
107
+ "base_days_covered": self.base_days, "current_days_covered": self.current_days,
108
+ "bridge": [{"driver": b, "label": BUCKET_LABELS[b], "amount": fmt(self.buckets[b])} for b in BUCKETS],
109
+ "drivers": {b: rows(v) for b, v in self.drivers.items()},
110
+ "by_service_category": rows(self.categories),
111
+ "by_service": rows(self.services),
112
+ "top_line_changes": rows(self.top_keys),
113
+ "notes": self.notes,
114
+ "coverage_gaps": self.gaps,
115
+ }
116
+
117
+ def narrative(self) -> str:
118
+ cur = self.currency or ""
119
+ if self.base_days is None or self.current_days is None or not self.same_accounts:
120
+ lead = ""
121
+ if self.gaps:
122
+ lead = (f"NOT COMPARABLE AS-IS: {'; '.join(self.gaps)}. "
123
+ f"{display(self.buckets.get('coverage', 0), cur)} of the difference comes from data "
124
+ "missing in one period, not from a change in spend. ")
125
+ return lead + (f"Selected {self.cost_basis} rows total {display(self.base_total, cur)} in "
126
+ f"{self.base_period} and {display(self.current_total, cur)} in {self.current_period}. "
127
+ + " ".join(self.notes))
128
+ direction = "rose" if self.delta > 0 else "fell" if self.delta < 0 else "was unchanged"
129
+ pc = self.pct_change()
130
+ pct_text = ""
131
+ if pc is not None:
132
+ pct_text = f", {'+' if not pc.startswith('-') else ''}{pc}%"
133
+ if not self.comparable_days:
134
+ pct_text += " per day"
135
+ lines = []
136
+ if self.buckets.get("coverage"):
137
+ lines.append(f"NOT COMPARABLE AS-IS: {'; '.join(self.gaps)}. "
138
+ f"{display(self.buckets['coverage'], cur)} of the change comes from data missing in one "
139
+ "period, not from a change in spend.")
140
+ lines += [
141
+ f"{self.cost_basis.capitalize()} spend {direction} from {display(self.base_total, cur)} in "
142
+ f"{self.base_period} to {display(self.current_total, cur)} in {self.current_period} "
143
+ f"({'+' if self.delta >= 0 else ''}{display(self.delta, cur)}{pct_text})."
144
+ ]
145
+ movers = sorted(((k, v) for k, v in self.buckets.items() if v != 0), key=lambda kv: -abs(kv[1]))
146
+ if movers:
147
+ parts = [f"{BUCKET_LABELS[k].lower()} {'+' if v > 0 else ''}{display(v, cur)}" for k, v in movers[:4]]
148
+ lines.append("The change breaks down into " + ", ".join(parts) + ".")
149
+ ups = [s for s in self.services if s["delta"] > 0][:3]
150
+ if ups:
151
+ lines.append("Largest increases: " + ", ".join(
152
+ f"{s['service']} (+{display(s['delta'], cur)})" for s in ups) + ".")
153
+ downs = [s for s in sorted(self.services, key=lambda x: x["delta"]) if s["delta"] < 0][:2]
154
+ if downs:
155
+ lines.append("Largest decreases: " + ", ".join(
156
+ f"{s['service']} ({display(s['delta'], cur)})" for s in downs) + ".")
157
+ if not self.comparable_days and self.base_days and self.current_days:
158
+ lines.append(f"The periods cover {self.base_days} and {self.current_days} days; percentages are per "
159
+ "day. Amounts use the selected cost basis.")
160
+ return " ".join(lines)
161
+
162
+
163
+ def principal_periods(ws: Workspace, source_ids: list[int] | None = None) -> list[str]:
164
+ """Billing periods that contain usage dated inside the period (excludes late-usage spillover)."""
165
+ where = ""
166
+ if source_ids is not None:
167
+ where = f"AND source_id IN ({', '.join(str(int(i)) for i in source_ids) or 'NULL'})"
168
+ rows = ws.rows(f"""SELECT billing_period FROM valid
169
+ WHERE billing_period IS NOT NULL AND strftime(charge_date, '%Y-%m') = billing_period {where}
170
+ GROUP BY 1 ORDER BY 1""")
171
+ return [r["billing_period"] for r in rows]
172
+
173
+
174
+ def choose_periods(ws: Workspace, base: str | None, current: str | None,
175
+ base_sources: list[int] | None = None, current_sources: list[int] | None = None) -> tuple[str, str]:
176
+ explicit = base is not None or current is not None
177
+ if base is None or current is None:
178
+ if base_sources is not None and current_sources is not None:
179
+ b, c = principal_periods(ws, base_sources), principal_periods(ws, current_sources)
180
+ if (not base and not b) or (not current and not c):
181
+ raise InputError("one side of the comparison has no dated usage to infer a period")
182
+ base, current = base or b[-1], current or c[-1]
183
+ else:
184
+ periods = principal_periods(ws)
185
+ if len(periods) < 2:
186
+ raise InputError(
187
+ f"variance needs two billing periods; found {periods or 'none'}",
188
+ hint="Pass two exports (cloudleak variance BASE CURRENT) or a directory holding two months.",
189
+ )
190
+ base, current = base or periods[-2], current or periods[-1]
191
+ where = comparison_filter(base, current, base_sources, current_sources)
192
+ if explicit:
193
+ rows = ws.rows(f"SELECT DISTINCT billing_period FROM valid WHERE {where}")
194
+ _require_periods(base, current, {r["billing_period"] for r in rows})
195
+ return base, current
196
+
197
+
198
+ def comparison_filter(base: str, current: str, base_sources: list[int] | None = None,
199
+ current_sources: list[int] | None = None) -> str:
200
+ """Validate both role-specific selections and return their SQL predicate."""
201
+ if base == current:
202
+ raise InputError(f"both sides resolve to billing period {base}. Choose distinct periods")
203
+ predicates = []
204
+ for period, sources, role in ((base, base_sources, "base"), (current, current_sources, "current")):
205
+ if not re.fullmatch(r"[0-9]{4}-(0[1-9]|1[0-2])", period):
206
+ raise InputError(f"invalid {role} period {period!r}. Use YYYY-MM")
207
+ pred = f"billing_period = '{period}'"
208
+ if sources is not None:
209
+ pred += f" AND source_id IN ({', '.join(str(int(i)) for i in sources) or 'NULL'})"
210
+ predicates.append(f"({pred})")
211
+ return "(" + " OR ".join(predicates) + ")"
212
+
213
+
214
+ def _require_periods(base: str, current: str, observed: set[str]) -> None:
215
+ for role, period in (("base", base), ("current", current)):
216
+ if period not in observed:
217
+ raise InputError(f"no rows for {role} period {period} in the selected input")
218
+
219
+
220
+ @money_context
221
+ def compute(ws: Workspace, base: str, current: str, *, top: int = 12,
222
+ base_sources: list[int] | None = None, current_sources: list[int] | None = None) -> list[Bridge]:
223
+ where = comparison_filter(base, current, base_sources, current_sources)
224
+ statuses = period_statuses(ws, where=where)
225
+ _require_periods(base, current, {s.billing_period for s in statuses})
226
+ rows = ws.rows(f"""
227
+ SELECT currency, cost_basis, billing_period AS p, provider, billing_account_id, sub_account_id,
228
+ any_value(sub_account_name) AS sub_account_name,
229
+ COALESCE(service, '(no service)') AS service, COALESCE(sku, '(no sku)') AS sku,
230
+ usage_unit AS unit, charge_category AS cat, any_value(service_category) AS service_category,
231
+ sum(gross_cost) AS gross, sum(cost - gross_cost) AS embedded, sum(cost) AS cost,
232
+ sum(usage_quantity) AS qty, count(usage_quantity) = count(*) AS qty_complete,
233
+ arg_max(tags, cost) AS tags
234
+ FROM valid WHERE {where}
235
+ GROUP BY currency, cost_basis, billing_period, provider, billing_account_id, sub_account_id, service, sku,
236
+ usage_unit, charge_category
237
+ """)
238
+ groups: dict[tuple, dict] = defaultdict(lambda: {"b": {}, "c": {}})
239
+ for r in rows:
240
+ side = "b" if r["p"] == base else "c"
241
+ key = (r["provider"], r["billing_account_id"], r["sub_account_id"], r["service"], r["sku"], r["unit"], r["cat"])
242
+ groups[(r["currency"], r["cost_basis"])]["b" if side == "b" else "c"][key] = r
243
+
244
+ bridges = []
245
+ for (currency, basis), sides in sorted(groups.items(), key=lambda kv: (str(kv[0][0]), kv[0][1])):
246
+ bridges.append(_bridge(currency, basis, base, current, sides["b"], sides["c"], statuses, top))
247
+ if not bridges:
248
+ raise InputError(f"no rows in billing periods {base} or {current}")
249
+ return bridges
250
+
251
+
252
+ def _days(statuses, period: str, currency, basis) -> int | None:
253
+ vals = [s.days_covered for s in statuses
254
+ if s.billing_period == period and s.currency == currency and s.cost_basis == basis]
255
+ return vals[0] if vals and len(set(vals)) == 1 else None
256
+
257
+
258
+ def _bridge(currency, basis, base, current, b: dict, c: dict, statuses, top: int) -> Bridge:
259
+ buckets = dict.fromkeys(BUCKETS, ZERO)
260
+ drivers: dict[str, dict[str, Decimal]] = {k: defaultdict(lambda: ZERO) for k in BUCKETS}
261
+ key_changes = []
262
+ base_total = sum((r["cost"] for r in b.values()), ZERO)
263
+ cur_total = sum((r["cost"] for r in c.values()), ZERO)
264
+
265
+ def credit_bucket(cat):
266
+ return {"credit": "credits", "refund": "credits", "discount": "credits", "tax": "tax",
267
+ "purchase": "purchases", "fee": "purchases"}.get(cat)
268
+
269
+ # A provider/billing account present in only one of the two periods is an export gap, not a change in
270
+ # spend: route its whole difference to the "coverage" bucket instead of new/discontinued.
271
+ scopes_b = {(k[0], k[1]) for k in b}
272
+ scopes_c = {(k[0], k[1]) for k in c}
273
+ gap_scopes = scopes_b ^ scopes_c
274
+ gaps = sorted(f"{p} {a or '(no billing account)'} has no rows in "
275
+ f"{current if (p, a) in scopes_b else base}" for p, a in gap_scopes)
276
+ for key in sorted(set(b) | set(c), key=lambda k: tuple(str(x) for x in k)):
277
+ rb, rc = b.get(key), c.get(key)
278
+ provider, billing_account, sub_account, service, sku, unit, cat = key
279
+ label = f"{service} / {sku}"
280
+ g1 = rb["gross"] if rb else ZERO
281
+ g2 = rc["gross"] if rc else ZERO
282
+ e1 = rb["embedded"] if rb else ZERO
283
+ e2 = rc["embedded"] if rc else ZERO
284
+ if (key[0], key[1]) in gap_scopes:
285
+ amount = (rc["cost"] if rc else ZERO) - (rb["cost"] if rb else ZERO)
286
+ buckets["coverage"] += amount
287
+ drivers["coverage"][f"{provider} {billing_account or ''}".strip()] += amount
288
+ ref = rc or rb
289
+ key_changes.append({
290
+ "provider": provider, "billing_account_id": billing_account, "sub_account_id": sub_account,
291
+ "sub_account_name": ref["sub_account_name"], "service": service, "sku": sku, "unit": unit,
292
+ "charge_category": cat, "service_category": ref["service_category"],
293
+ "base_cost": rb["cost"] if rb else ZERO, "current_cost": rc["cost"] if rc else ZERO,
294
+ "delta": amount, "volume_effect": None, "rate_effect": None,
295
+ "base_quantity": rb["qty"] if rb else None, "current_quantity": rc["qty"] if rc else None,
296
+ "driver": "coverage", "owner_routing": owner_routing(ref["tags"], sub_account, ref["sub_account_name"]),
297
+ })
298
+ continue
299
+ if e1 != e2:
300
+ buckets["credits"] += e2 - e1
301
+ drivers["credits"][f"{service} (credits applied to usage)"] += e2 - e1
302
+ delta = g2 - g1
303
+ fixed = credit_bucket(cat)
304
+ if fixed:
305
+ bucket = fixed
306
+ parts = {bucket: delta}
307
+ elif cat in ("adjustment", "unknown"):
308
+ parts = {"adjustments": delta}
309
+ elif rb is None or (g1 == 0 and not (rb and rb["qty"])):
310
+ parts = {"new": delta}
311
+ elif rc is None or (g2 == 0 and not (rc and rc["qty"])):
312
+ parts = {"discontinued": delta}
313
+ elif (rb["qty_complete"] and rc["qty_complete"] and rb["qty"] and rc["qty"] and rb["qty"] > 0
314
+ and rc["qty"] > 0):
315
+ volume = (((rc["qty"] - rb["qty"]) * g1) / rb["qty"]).quantize(QUANT)
316
+ parts = {"volume": volume, "rate": delta - volume}
317
+ else:
318
+ parts = {"unquantified": delta}
319
+ for bk, amt in parts.items():
320
+ if amt:
321
+ buckets[bk] += amt
322
+ drivers[bk][label] += amt
323
+ if not any(parts.values()) and e1 == e2:
324
+ continue
325
+ ref = rc or rb
326
+ key_changes.append({
327
+ "provider": provider, "billing_account_id": billing_account, "sub_account_id": sub_account,
328
+ "sub_account_name": ref["sub_account_name"],
329
+ "service": service, "sku": sku, "unit": unit, "charge_category": cat,
330
+ "service_category": ref["service_category"],
331
+ "base_cost": rb["cost"] if rb else ZERO, "current_cost": rc["cost"] if rc else ZERO,
332
+ "delta": (rc["cost"] if rc else ZERO) - (rb["cost"] if rb else ZERO),
333
+ "volume_effect": parts.get("volume"), "rate_effect": parts.get("rate"),
334
+ "base_quantity": rb["qty"] if rb else None, "current_quantity": rc["qty"] if rc else None,
335
+ "driver": next(iter(parts)) if len(parts) == 1 else "volume_and_rate",
336
+ "owner_routing": owner_routing(ref["tags"], sub_account, ref["sub_account_name"]),
337
+ })
338
+
339
+ explained = sum(buckets.values(), ZERO)
340
+ if explained != cur_total - base_total: # pragma: no cover - arithmetic invariant
341
+ raise AssertionError(f"bridge does not close: {explained} vs {cur_total - base_total}")
342
+
343
+ def agg(field_name: str) -> list[dict]:
344
+ acc: dict[str, list[Decimal]] = defaultdict(lambda: [ZERO, ZERO])
345
+ for r in b.values():
346
+ acc[r[field_name] or "(none)"][0] += r["cost"]
347
+ for r in c.values():
348
+ acc[r[field_name] or "(none)"][1] += r["cost"]
349
+ out = [{field_name: k, "base_cost": v[0], "current_cost": v[1], "delta": v[1] - v[0]}
350
+ for k, v in acc.items()]
351
+ return sorted(out, key=lambda x: (-abs(x["delta"]), x[field_name]))
352
+
353
+ drv = {k: [{"item": name, "amount": amt} for name, amt in
354
+ sorted(v.items(), key=lambda kv: (-abs(kv[1]), kv[0])) if amt][:top]
355
+ for k, v in drivers.items()}
356
+ key_changes.sort(key=lambda x: (-abs(x["delta"]), x["service"], x["sku"]))
357
+ bd, cd = _days(statuses, base, currency, basis), _days(statuses, current, currency, basis)
358
+ notes = []
359
+ if bd is None or cd is None:
360
+ for period, data, coverage in ((base, b, bd), (current, c, cd)):
361
+ if not data:
362
+ notes.append(f"No rows for this currency and cost basis in {period}.")
363
+ elif coverage is None:
364
+ notes.append(f"Account scopes have different day counts in {period}.")
365
+ notes.append("Coverage does not support a percentage comparison.")
366
+ elif bd != cd and bd and cd and not (bd == days_in(base) and cd == days_in(current)):
367
+ notes.append(f"Unequal coverage: {base} has usage on {bd} days, {current} on {cd} days. Percent change is "
368
+ "per day. Amounts use the selected cost basis.")
369
+ same_accounts = ({key[:2] for key in b} == {key[:2] for key in c})
370
+ if not same_accounts and b and c:
371
+ notes.append("The selected periods cover different billing accounts or providers. "
372
+ "A like-for-like percentage comparison is unavailable.")
373
+ fin = {s.finality for s in statuses if s.billing_period in (base, current) and s.currency == currency
374
+ and s.cost_basis == basis}
375
+ if "preliminary_estimate" in fin:
376
+ notes.append("At least one period is a preliminary estimate; late charges (for example support fees, "
377
+ "credits and refunds) can still post.")
378
+ if gaps:
379
+ notes.insert(0, "Export gap: " + "; ".join(gaps) + ". Supply the missing export before reading this "
380
+ "bridge as a change in spend.")
381
+ return Bridge(currency, basis, base, current, base_total, cur_total, buckets, drv, agg("service_category"),
382
+ [{**x, "service": x["service"]} for x in agg("service")][:top], key_changes[:top * 2], bd, cd,
383
+ notes, same_accounts, gaps)
384
+
385
+
386
+ @money_context
387
+ def variance_findings(bridges: list[Bridge], *, statuses_lookup: dict | None = None,
388
+ min_share: Decimal = Decimal("0.01"), min_abs: Decimal = Decimal("1"),
389
+ limit: int = 10) -> list[Finding]:
390
+ out = []
391
+ billed = {br.currency for br in bridges if br.cost_basis == "billed"}
392
+ for br in bridges:
393
+ if br.base_days is None or br.current_days is None or not br.same_accounts:
394
+ continue
395
+ if br.cost_basis != "billed" and br.currency in billed:
396
+ continue # the billed bridge already explains this currency; avoid duplicate drivers
397
+ floor = max(min_abs, abs(br.base_total) * min_share)
398
+ for ch in br.top_keys:
399
+ if abs(ch["delta"]) < floor or ch["charge_category"] != "usage":
400
+ continue
401
+ sign = "+" if ch["delta"] > 0 else ""
402
+ explain = {"new": "new this period", "discontinued": "absent from the selected current rows",
403
+ "volume_and_rate": f"volume {display(ch['volume_effect'])}, rate {display(ch['rate_effect'])}",
404
+ "volume": "volume change", "rate": "unit rate change",
405
+ "unquantified": "no usable quantity to split volume and rate"}.get(ch["driver"], ch["driver"])
406
+ out.append(Finding(
407
+ rule_id="CL-VAR-001",
408
+ title="Month-over-month variance driver",
409
+ summary=(f"{ch['service']} / {ch['sku']} on {ch['sub_account_name'] or ch['sub_account_id'] or 'n/a'}:"
410
+ f" {sign}{display(ch['delta'], br.currency)} from {br.base_period} to {br.current_period}"
411
+ f" ({explain})."),
412
+ classification="variance_driver", evidence_level="L1",
413
+ severity="medium" if abs(ch["delta"]) >= abs(br.base_total) * Decimal("0.05") else "low",
414
+ provider=ch["provider"], currency=br.currency, billing_period=br.current_period,
415
+ period_finality="unknown",
416
+ observed_cost=ch["current_cost"], cost_basis=br.cost_basis,
417
+ billing_account_id=ch["billing_account_id"], sub_account_id=ch["sub_account_id"],
418
+ service=ch["service"], owner_routing=ch["owner_routing"], action_risk="none_readonly",
419
+ details={"key": f"{ch['service']}|{ch['sku']}|{ch['unit']}|{br.base_period}",
420
+ "base_period": br.base_period, "base_cost": ch["base_cost"], "delta": ch["delta"],
421
+ "volume_effect": ch["volume_effect"], "rate_effect": ch["rate_effect"],
422
+ "driver": ch["driver"], "sku": ch["sku"], "service_category": ch["service_category"]},
423
+ ))
424
+ if len([f for f in out if f.currency == br.currency and f.cost_basis == br.cost_basis]) >= limit:
425
+ break
426
+ return out