ukaf-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.
ukaf/recommend.py ADDED
@@ -0,0 +1,357 @@
1
+ """Rule-based recommendations. Every item names the action, the evidence, and a number."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from decimal import ROUND_HALF_EVEN, Decimal
7
+ from statistics import median
8
+
9
+ from ukaf.dora import Dora
10
+ from ukaf.money import mul_div_half_even
11
+ from ukaf.story import Feature, Story
12
+ from ukaf.timeutil import delta_us, fmt_duration
13
+
14
+ US_PER_DAY = 86_400 * 1_000_000
15
+ US_PER_MIN = 60 * 1_000_000
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Recommendation:
20
+ rule_id: str
21
+ action_en: str
22
+ action_he: str
23
+ evidence_en: str
24
+ evidence_he: str
25
+ impact_en: str
26
+ impact_he: str
27
+ billed_month_micro: int
28
+ list_month_micro: int
29
+ minutes_month: int
30
+
31
+ def rank(self) -> tuple[int, int, int]:
32
+ return (self.billed_month_micro, self.list_month_micro, self.minutes_month)
33
+
34
+
35
+ def recommend(story: Story, dora: Dora) -> list[Recommendation]:
36
+ scale = _scale(story)
37
+ items = [
38
+ _fast(story, scale),
39
+ _overhead_on_demand(story, scale),
40
+ _max_mode(story, scale),
41
+ _change_failure(story, dora, scale),
42
+ _testing(story, scale),
43
+ _tier_split(story, scale),
44
+ ]
45
+ kept = [item for item in items if item is not None]
46
+ kept.sort(key=lambda item: item.rank(), reverse=True)
47
+ return kept
48
+
49
+
50
+ def _scale(story: Story) -> Decimal:
51
+ if story.window_start is None or story.window_end is None:
52
+ return Decimal(1)
53
+ days = Decimal(delta_us(story.window_start, story.window_end)) / Decimal(US_PER_DAY)
54
+ if days < 1:
55
+ days = Decimal(1)
56
+ return Decimal(30) / days
57
+
58
+
59
+ def _month(micro: int, scale: Decimal) -> int:
60
+ return int((Decimal(micro) * scale).quantize(Decimal("1"), rounding=ROUND_HALF_EVEN))
61
+
62
+
63
+ def _fast(story: Story, scale: Decimal) -> Recommendation | None:
64
+ fast = story.fast
65
+ if fast.events == 0 or story.list_micro <= 0:
66
+ return None
67
+ share = fast.list_micro / story.list_micro
68
+ if share < 0.15 and fast.saving_billed_micro <= 0:
69
+ return None
70
+ billed_month = _month(fast.saving_billed_micro, scale)
71
+ list_month = _month(fast.saving_list_micro, scale)
72
+ if billed_month <= 0 and list_month < 5_000_000:
73
+ return None
74
+ models = ", ".join(sorted(fast.models))
75
+ pct = round(share * 100)
76
+ action_en = (
77
+ "Turn off Fast mode for cloud agents (model picker: Fast = off) and rerun those jobs at the standard rate."
78
+ )
79
+ action_he = "כבו מצב Fast לסוכני הענן (בורר המודל: Fast כבוי) והריצו את אותן עבודות במחיר הרגיל."
80
+ evidence_en = (
81
+ f"{pct}% of list cost was Fast ({models}), {fast.events} events, "
82
+ f"list {_usd(fast.list_micro)} of {_usd(story.list_micro)}. "
83
+ f"On-demand billed on those rows was {_usd(fast.billed_micro)}. "
84
+ "Fast list price on the rate card is the published fast rate; the counterfactual "
85
+ "re-prices the same tokens at the matching non-fast model."
86
+ )
87
+ evidence_he = (
88
+ f"{pct}% ממחיר המחירון היה Fast ({models}), {fast.events} אירועים, "
89
+ f"מחירון {_usd(fast.list_micro)} מתוך {_usd(story.list_micro)}. "
90
+ f"החיוב לפי דרישה בשורות האלה היה {_usd(fast.billed_micro)}. "
91
+ "החיסכון מחשב את אותם טוקנים לפי המודל בלי Fast."
92
+ )
93
+ impact_en = f"Saves about {_usd(billed_month)}/month billed" + (
94
+ f" and {_usd(list_month)}/month of list price." if list_month else "."
95
+ )
96
+ impact_he = f"חיסכון של כ-{_usd(billed_month)} לחודש בחיוב" + (
97
+ f" ועוד {_usd(list_month)} לחודש במחירון." if list_month else "."
98
+ )
99
+ return Recommendation(
100
+ "fast-mode",
101
+ action_en,
102
+ action_he,
103
+ evidence_en,
104
+ evidence_he,
105
+ impact_en,
106
+ impact_he,
107
+ billed_month,
108
+ list_month,
109
+ 0,
110
+ )
111
+
112
+
113
+ def _overhead_on_demand(story: Story, scale: Decimal) -> Recommendation | None:
114
+ overhead = story.overhead
115
+ if overhead.on_demand_billed_micro <= 0:
116
+ return None
117
+ billed_month = _month(overhead.on_demand_billed_micro, scale)
118
+ if billed_month < 1_000_000:
119
+ return None
120
+ models = ", ".join(sorted(overhead.on_demand_models))
121
+ share = overhead.on_demand_billed_micro / story.billed_micro if story.billed_micro else 0
122
+ pct = round(share * 100)
123
+ return Recommendation(
124
+ "unattached-on-demand",
125
+ "Stop on-demand runs that are not attached to a pull request "
126
+ "(set their on-demand cap to $0, or run them only inside the included pool).",
127
+ "עצרו הרצות לפי דרישה שאינן משויכות לבקשת משיכה (תקרת on-demand של $0, או רק בתוך המכסה הכלולה).",
128
+ (
129
+ f"{overhead.on_demand_events} on-demand events with no pull request billed "
130
+ f"{_usd(overhead.on_demand_billed_micro)} ({pct}% of billed). Models: {models}."
131
+ ),
132
+ (
133
+ f"{overhead.on_demand_events} אירועי on-demand בלי בקשת משיכה חייבו "
134
+ f"{_usd(overhead.on_demand_billed_micro)} ({pct}% מהחיוב). מודלים: {models}."
135
+ ),
136
+ f"Saves about {_usd(billed_month)}/month billed if those runs stop.",
137
+ f"חיסכון של כ-{_usd(billed_month)} לחודש בחיוב אם ההרצות האלה נעצרות.",
138
+ billed_month,
139
+ _month(overhead.on_demand_list_micro, scale),
140
+ 0,
141
+ )
142
+
143
+
144
+ def _max_mode(story: Story, scale: Decimal) -> Recommendation | None:
145
+ if story.max_mode_events == 0 or story.list_micro <= 0:
146
+ return None
147
+ share = story.max_mode_list_micro / story.list_micro
148
+ if share < 0.10:
149
+ return None
150
+ # Legacy Max Mode is +20% on top of the token price, so the premium is 1/6 of the gross.
151
+ list_save = mul_div_half_even(story.max_mode_list_micro, 1, 6)
152
+ billed_save = mul_div_half_even(story.max_mode_billed_micro, 1, 6)
153
+ billed_month = _month(billed_save, scale)
154
+ list_month = _month(list_save, scale)
155
+ if billed_month <= 0 and list_month < 5_000_000:
156
+ return None
157
+ pct = round(share * 100)
158
+ return Recommendation(
159
+ "max-mode",
160
+ "Turn Max Mode off except on tasks that need the longer context window.",
161
+ "כבו Max Mode חוץ ממשימות שבאמת צריכות את חלון ההקשר הארוך.",
162
+ (
163
+ f"Max Mode was on for {story.max_mode_events} events and {pct}% of list cost "
164
+ f"({_usd(story.max_mode_list_micro)}). The pricing rule used here is the legacy +20%."
165
+ ),
166
+ (
167
+ f"Max Mode היה דלוק ב-{story.max_mode_events} אירועים וב-{pct}% ממחיר המחירון "
168
+ f"({_usd(story.max_mode_list_micro)}). הכלל כאן הוא +20% של התוכניות הישנות."
169
+ ),
170
+ (f"Saves about {_usd(billed_month)}/month billed ({_usd(list_month)}/month list) by dropping the 20% uplift."),
171
+ (f"חיסכון של כ-{_usd(billed_month)} לחודש בחיוב ({_usd(list_month)} לחודש מחירון) בלי תוספת ה-20%."),
172
+ billed_month,
173
+ list_month,
174
+ 0,
175
+ )
176
+
177
+
178
+ def _change_failure(story: Story, dora: Dora, scale: Decimal) -> Recommendation | None:
179
+ if not dora.shipped_changes or dora.change_failure_rate is None:
180
+ return None
181
+ if dora.change_failure_rate < 0.20 or dora.time_to_restore_us is None:
182
+ return None
183
+ extra_rate = Decimal(str(dora.change_failure_rate)) - Decimal("0.15")
184
+ if extra_rate <= 0:
185
+ return None
186
+ per_month = Decimal(dora.deploys) * scale
187
+ minutes = extra_rate * per_month * Decimal(dora.time_to_restore_us) / Decimal(US_PER_MIN)
188
+ minutes_month = int(minutes.quantize(Decimal("1"), rounding=ROUND_HALF_EVEN))
189
+ if minutes_month < 30:
190
+ return None
191
+ names = ", ".join(f"{feature.repo}#{feature.number}" for feature in story.features if feature.failed)
192
+ pct = round(float(dora.change_failure_rate) * 100)
193
+ restore = fmt_duration(dora.time_to_restore_us)
194
+ restore_he = fmt_duration(dora.time_to_restore_us, hebrew=True)
195
+ return Recommendation(
196
+ "change-failure",
197
+ "Block merge while required CI is red, and name an owner who reverts a bad production deploy the same day.",
198
+ "חסמו מיזוג כש-CI הנדרש אדום, וקבעו אחראי שמחזיר פריסה כושלת באותו היום.",
199
+ (
200
+ f"{dora.failed_changes} of {dora.shipped_changes} shipped changes failed ({pct}%): {names}. "
201
+ f"Median time to restore, which is the fixes stage, was {restore}."
202
+ ),
203
+ (
204
+ f"{dora.failed_changes} מתוך {dora.shipped_changes} שינויים שנמסרו נכשלו ({pct}%): {names}. "
205
+ f"חציון הזמן לשיקום, שהוא שלב התיקונים, היה {restore_he}."
206
+ ),
207
+ (
208
+ f"Holding the failure rate at 15% would avoid about {minutes_month} minutes/month of restore time "
209
+ f"at this deploy rate ({dora.deploy_source})."
210
+ ),
211
+ (f"החזקת שיעור הכשל על 15% תחסוך כ-{minutes_month} דקות בחודש של זמן שיקום בקצב הפריסה הזה."),
212
+ 0,
213
+ 0,
214
+ minutes_month,
215
+ )
216
+
217
+
218
+ def _testing(story: Story, scale: Decimal) -> Recommendation | None:
219
+ usable = [feature for feature in story.features if feature.lead_time_us > 0]
220
+ if not usable:
221
+ return None
222
+ testing = [feature.stages[2].duration_us for feature in usable]
223
+ leads = [feature.lead_time_us for feature in usable]
224
+ med_test = int(median(testing))
225
+ med_lead = int(median(leads))
226
+ if med_lead <= 0 or med_test < 10 * US_PER_MIN:
227
+ return None
228
+ if med_test / med_lead < 0.5:
229
+ return None
230
+ saved_each = Decimal("0.3") * Decimal(med_test) / Decimal(US_PER_MIN)
231
+ monthly = saved_each * Decimal(len(usable)) * scale
232
+ minutes_month = int(monthly.quantize(Decimal("1"), rounding=ROUND_HALF_EVEN))
233
+ if minutes_month < 15:
234
+ return None
235
+ pct = round(100 * med_test / med_lead)
236
+ worst = max(usable, key=lambda feature: feature.stages[2].duration_us)
237
+ return Recommendation(
238
+ "shrink-testing",
239
+ (
240
+ f"Cache the dependency install in CI and skip jobs that already passed on the same SHA. "
241
+ f"Start with {worst.repo}#{worst.number}, where testing was "
242
+ f"{fmt_duration(worst.stages[2].duration_us)}."
243
+ ),
244
+ (
245
+ f"שמרו במטמון את התקנת התלויות ב-CI ודלגו על עבודות שכבר עברו על אותו SHA. "
246
+ f"התחילו ב-{worst.repo}#{worst.number}, שם הבדיקות נמשכו "
247
+ f"{fmt_duration(worst.stages[2].duration_us, hebrew=True)}."
248
+ ),
249
+ (
250
+ f"Median testing stage is {fmt_duration(med_test)} and that is {pct}% of median lead time "
251
+ f"({fmt_duration(med_lead)}, which is testing + deploy) across {len(usable)} features."
252
+ ),
253
+ (
254
+ f"חציון שלב הבדיקות הוא {fmt_duration(med_test, hebrew=True)} וזה {pct}% מחציון זמן ההובלה "
255
+ f"({fmt_duration(med_lead, hebrew=True)}, שהוא בדיקות + פריסה) על פני {len(usable)} פיצ'רים."
256
+ ),
257
+ (
258
+ f"A 30% shorter testing stage is about {int(saved_each)} minutes per feature, "
259
+ f"{minutes_month} minutes/month at this feature rate."
260
+ ),
261
+ (f"קיצור של 30% בשלב הבדיקות הוא כ-{int(saved_each)} דקות לפיצ'ר, {minutes_month} דקות בחודש בקצב הזה."),
262
+ 0,
263
+ 0,
264
+ minutes_month,
265
+ )
266
+
267
+
268
+ def _tier_split(story: Story, scale: Decimal) -> Recommendation | None:
269
+ def bucket(tier: str) -> list[Feature]:
270
+ return [feature for feature in story.features if feature.tier == tier and feature.sloc > 0]
271
+
272
+ bench_features = bucket("S") or bucket("M")
273
+ if not bench_features:
274
+ return None
275
+ bench_sloc = sum(feature.sloc for feature in bench_features)
276
+ bench_list = sum(feature.list_micro for feature in bench_features)
277
+ if bench_sloc <= 0 or bench_list <= 0:
278
+ return None
279
+ bench_tier = bench_features[0].tier
280
+ candidates = bucket("XL") or bucket("L")
281
+ worst: tuple[int, Feature] | None = None
282
+ for feature in candidates:
283
+ if feature.list_micro <= 0:
284
+ continue
285
+ # micro-dollars per hand-written line, compared with the benchmark tier.
286
+ feature_rate = feature.list_micro / feature.sloc
287
+ bench_rate = bench_list / bench_sloc
288
+ if feature_rate <= bench_rate * 1.5:
289
+ continue
290
+ list_save = int(feature.list_micro - bench_rate * feature.sloc)
291
+ if list_save <= 0:
292
+ continue
293
+ billed_save = (
294
+ mul_div_half_even(feature.billed_micro, list_save, feature.list_micro) if feature.list_micro else 0
295
+ )
296
+ score = billed_save or list_save
297
+ if worst is None or score > worst[0]:
298
+ worst = (score, feature)
299
+ if worst is None:
300
+ return None
301
+ feature = worst[1]
302
+ bench_rate = bench_list / bench_sloc
303
+ list_save = int(feature.list_micro - bench_rate * feature.sloc)
304
+ billed_save = mul_div_half_even(feature.billed_micro, list_save, feature.list_micro) if feature.list_micro else 0
305
+ billed_month = _month(billed_save, scale)
306
+ list_month = _month(list_save, scale)
307
+ if billed_month <= 0 and list_month < 5_000_000:
308
+ return None
309
+ per_100_feature = int(feature.list_micro / feature.sloc * 100)
310
+ per_100_bench = int(bench_list / bench_sloc * 100)
311
+ return Recommendation(
312
+ "split-large-change",
313
+ (
314
+ f"Split {feature.repo}#{feature.number} into reviews of at most 300 hand-written lines "
315
+ f"(tier M or smaller) before the agent keeps going."
316
+ ),
317
+ (
318
+ f"פצלו את {feature.repo}#{feature.number} לסקירות של לכל היותר 300 שורות כתובות יד "
319
+ f"(דרגה M או קטנה יותר) לפני שהסוכן ממשיך."
320
+ ),
321
+ (
322
+ f"{feature.repo}#{feature.number} is tier {feature.tier}: {feature.sloc} hand-written lines, "
323
+ f"list {_usd(feature.list_micro)} ({_usd(per_100_feature)} per 100 lines). "
324
+ f"Tier {bench_tier} in this window was {_usd(per_100_bench)} per 100 lines."
325
+ ),
326
+ (
327
+ f"{feature.repo}#{feature.number} בדרגה {feature.tier}: {feature.sloc} שורות כתובות יד, "
328
+ f"מחירון {_usd(feature.list_micro)} ({_usd(per_100_feature)} ל-100 שורות). "
329
+ f"דרגה {bench_tier} בחלון הזה הייתה {_usd(per_100_bench)} ל-100 שורות."
330
+ ),
331
+ (
332
+ f"At the tier {bench_tier} list rate the same lines would have been about "
333
+ f"{_usd(list_month)}/month less on the list price"
334
+ + (
335
+ f" and {_usd(billed_month)}/month less billed."
336
+ if billed_month
337
+ else ", with no billed saving while the pool covers it."
338
+ )
339
+ ),
340
+ (
341
+ f"לפי מחיר המחירון של דרגה {bench_tier} אותן שורות היו עולות כ-"
342
+ f"{_usd(list_month)} פחות לחודש במחירון"
343
+ + (
344
+ f" וכ-{_usd(billed_month)} פחות בחיוב."
345
+ if billed_month
346
+ else ", בלי חיסכון בחיוב כל עוד המכסה מכסה את זה."
347
+ )
348
+ ),
349
+ billed_month,
350
+ list_month,
351
+ 0,
352
+ )
353
+
354
+
355
+ def _usd(micro: int) -> str:
356
+ amount = (Decimal(micro) / Decimal(1_000_000)).quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN)
357
+ return f"${amount}"
ukaf/reconcile.py ADDED
@@ -0,0 +1,185 @@
1
+ """Fail loudly when a partition does not add up to the whole."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from ukaf.dora import Dora
8
+ from ukaf.money import money
9
+ from ukaf.story import STAGE_NAMES, Story
10
+
11
+
12
+ class ReconciliationError(ValueError):
13
+ """Parts do not sum to the whole. The report must not look finished."""
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Check:
18
+ name: str
19
+ ok: bool
20
+ detail: str
21
+
22
+
23
+ def reconciliation(story: Story, dora: Dora) -> list[Check]:
24
+ checks: list[Check] = []
25
+
26
+ feature_list = sum(feature.list_micro for feature in story.features)
27
+ feature_billed = sum(feature.billed_micro for feature in story.features)
28
+ feature_tokens = sum(feature.tokens for feature in story.features)
29
+ feature_events = sum(feature.events for feature in story.features)
30
+
31
+ checks.append(
32
+ _eq(
33
+ "list price: features + overhead = export",
34
+ feature_list + story.overhead.list_micro,
35
+ story.list_micro,
36
+ money,
37
+ )
38
+ )
39
+ checks.append(
40
+ _eq(
41
+ "billed cost: features + overhead = export",
42
+ feature_billed + story.overhead.billed_micro,
43
+ story.billed_micro,
44
+ money,
45
+ )
46
+ )
47
+ checks.append(
48
+ _eq(
49
+ "tokens: features + overhead = export",
50
+ feature_tokens + story.overhead.tokens,
51
+ story.tokens,
52
+ str,
53
+ )
54
+ )
55
+ checks.append(
56
+ _eq(
57
+ "events: features + overhead = export",
58
+ feature_events + story.overhead.events,
59
+ story.events,
60
+ str,
61
+ )
62
+ )
63
+
64
+ model_list = sum(row.list_micro for row in story.models)
65
+ model_billed = sum(row.billed_micro for row in story.models)
66
+ model_tokens = sum(row.tokens for row in story.models)
67
+ model_events = sum(row.events for row in story.models)
68
+ checks.append(_eq("list price by model = export", model_list, story.list_micro, money))
69
+ checks.append(_eq("billed cost by model = export", model_billed, story.billed_micro, money))
70
+ checks.append(_eq("tokens by model = export", model_tokens, story.tokens, str))
71
+ checks.append(_eq("events by model = export", model_events, story.events, str))
72
+
73
+ for feature in story.features:
74
+ label = f"{feature.repo}#{feature.number}"
75
+ checks.append(
76
+ _eq(
77
+ f"{label} stage list = feature list",
78
+ sum(stage.list_micro for stage in feature.stages),
79
+ feature.list_micro,
80
+ money,
81
+ )
82
+ )
83
+ checks.append(
84
+ _eq(
85
+ f"{label} stage billed = feature billed",
86
+ sum(stage.billed_micro for stage in feature.stages),
87
+ feature.billed_micro,
88
+ money,
89
+ )
90
+ )
91
+ checks.append(
92
+ _eq(
93
+ f"{label} stage tokens = feature tokens",
94
+ sum(stage.tokens for stage in feature.stages),
95
+ feature.tokens,
96
+ str,
97
+ )
98
+ )
99
+ checks.append(
100
+ _eq(
101
+ f"{label} stage events = feature events",
102
+ sum(stage.events for stage in feature.stages),
103
+ feature.events,
104
+ str,
105
+ )
106
+ )
107
+ checks.append(
108
+ _eq(
109
+ f"{label} stage durations = feature duration",
110
+ sum(stage.duration_us for stage in feature.stages),
111
+ feature.duration_us,
112
+ str,
113
+ )
114
+ )
115
+ testing = feature.stages[2].duration_us
116
+ deploy = feature.stages[3].duration_us
117
+ checks.append(
118
+ _eq(
119
+ f"{label} DORA lead time = testing + deploy",
120
+ feature.lead_time_us,
121
+ testing + deploy,
122
+ str,
123
+ )
124
+ )
125
+ names = tuple(stage.name for stage in feature.stages)
126
+ checks.append(
127
+ Check(
128
+ name=f"{label} stages are the five consecutive names",
129
+ ok=names == STAGE_NAMES,
130
+ detail=" → ".join(names),
131
+ )
132
+ )
133
+ # Tier costs are a partition of feature spend, then overhead closes the books.
134
+ # An empty tier contributes zero and still appears in the rendered table.
135
+ tier_list = sum(feature.list_micro for feature in story.features)
136
+ tier_billed = sum(feature.billed_micro for feature in story.features)
137
+ checks.append(
138
+ _eq(
139
+ "list price by tier + overhead = export",
140
+ tier_list + story.overhead.list_micro,
141
+ story.list_micro,
142
+ money,
143
+ )
144
+ )
145
+ checks.append(
146
+ _eq(
147
+ "billed cost by tier + overhead = export",
148
+ tier_billed + story.overhead.billed_micro,
149
+ story.billed_micro,
150
+ money,
151
+ )
152
+ )
153
+
154
+ if dora.shipped_changes:
155
+ lead_ok = all(
156
+ feature.lead_time_us == feature.stages[2].duration_us + feature.stages[3].duration_us
157
+ for feature in story.features
158
+ if feature.merged or feature.deployed
159
+ )
160
+ checks.append(
161
+ Check(
162
+ name="every shipped lead time is testing + deploy",
163
+ ok=lead_ok,
164
+ detail=f"median lead time {dora.lead_time_us} µs over {dora.shipped_changes} changes",
165
+ )
166
+ )
167
+ return checks
168
+
169
+
170
+ def assert_reconciled(story: Story, dora: Dora) -> list[Check]:
171
+ checks = reconciliation(story, dora)
172
+ bad = [item for item in checks if not item.ok]
173
+ if bad:
174
+ lines = ["reconciliation failed:"]
175
+ lines.extend(f"- {item.name}: {item.detail}" for item in bad)
176
+ raise ReconciliationError("\n".join(lines))
177
+ return checks
178
+
179
+
180
+ def _eq(name: str, left: int, right: int, fmt) -> Check:
181
+ return Check(
182
+ name=name,
183
+ ok=left == right,
184
+ detail=f"{fmt(left)} == {fmt(right)}" if left == right else f"{fmt(left)} != {fmt(right)}",
185
+ )