@trazum/core 1.38.0 → 1.40.0

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.
package/src/verify.ts ADDED
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Did it work? — the plan held to the log that came after it.
3
+ *
4
+ * Every optimisation tool says what you *would* save; almost none says what
5
+ * you *did*. This module takes a saved plan and a newer report and answers
6
+ * per action, with **three outcomes and never two**: the change arrived, the
7
+ * change did not arrive, or *it cannot be told* — because the workload
8
+ * vanished, the fields the detection needs stopped being recorded, or the
9
+ * log simply cannot see the thing (tokens do not say which tier billed
10
+ * them). The third outcome is the honest one, and the one every other tool
11
+ * renders as the first.
12
+ *
13
+ * **Differences are attributed, not just stated.** A predicted saving that
14
+ * did not appear in the bill is decomposed against the plan's recorded
15
+ * baseline: the calls moved, the output per call moved, the input per call
16
+ * moved — measured ratios with names, never a single number that blames
17
+ * nobody. And a plan priced under one catalogue verified under another says
18
+ * so: the tool must not blame a team for a saving that arithmetic revoked.
19
+ *
20
+ * Browser-safe like everything here: two documents in, one verdict out.
21
+ */
22
+
23
+ import { cacheEconomics } from './usage.js';
24
+ import type { UsageProfileReport } from './usage.js';
25
+ import type { PlanAction, PlanDocument } from './plan.js';
26
+
27
+ export type VerifyOutcome = 'arrived' | 'not-arrived' | 'cannot-tell';
28
+
29
+ /**
30
+ * Why an action cannot be told. The distinction matters to the gate: a
31
+ * workload that vanished is the world's doing; a log that stopped recording
32
+ * the fields the detection needs is the team's, and "not recorded" must not
33
+ * read as "fixed".
34
+ */
35
+ export type CannotTellReason = 'workload-vanished' | 'fields-stopped' | 'tier-not-recorded';
36
+
37
+ export interface VerifiedAction {
38
+ /** The plan's action, verbatim — the prediction being judged. */
39
+ action: PlanAction;
40
+ outcome: VerifyOutcome;
41
+ reason: CannotTellReason | null;
42
+ /**
43
+ * What the newer log measured for this slice, per kind: where the money
44
+ * sits now, the new retry bill, the new cache delta. Keys are stable.
45
+ */
46
+ observed: Record<string, number | string | null>;
47
+ /**
48
+ * The world's movement between the two logs, from the plan's recorded
49
+ * baseline: never a verdict, always the measured before and after.
50
+ */
51
+ attribution: {
52
+ calls?: { before: number; after: number };
53
+ inputPerCallTokens?: { before: number; after: number };
54
+ outputPerCallTokens?: { before: number; after: number };
55
+ } | null;
56
+ /**
57
+ * Whether this action fails `--gate`. `not-arrived` always does;
58
+ * `cannot-tell` does only for `fields-stopped` — a team that degraded its
59
+ * own log must not pass the gate on the strength of the silence. A
60
+ * vanished workload and an unrecordable tier fail nothing.
61
+ */
62
+ gateFailing: boolean;
63
+ }
64
+
65
+ export interface PlanVerification {
66
+ schemaVersion: 1;
67
+ /** When the plan was made, when it carries the stamp. */
68
+ planCreatedAt: string | null;
69
+ /** The catalogue that priced the plan, and the one pricing this check. */
70
+ planPricing: string;
71
+ currentPricing: string;
72
+ /**
73
+ * True when those differ: every dollar comparison here is then two
74
+ * measurements under two price lists, and the rendering must say so
75
+ * rather than let a repricing read as a team's failure.
76
+ */
77
+ pricesChanged: boolean;
78
+ actions: VerifiedAction[];
79
+ arrived: number;
80
+ notArrived: number;
81
+ cannotTell: number;
82
+ gateFailures: number;
83
+ }
84
+
85
+ /** Newer-log slices for one label, dearest first. */
86
+ function slicesForLabel(report: UsageProfileReport, label: string) {
87
+ return report.byLabelAndModel
88
+ .filter((s) => s.label === label && s.breakdown.calls > 0)
89
+ .sort((a, b) => b.breakdown.totalUsd - a.breakdown.totalUsd);
90
+ }
91
+
92
+ function attributionFrom(
93
+ action: PlanAction,
94
+ after: { calls: number; inputPerCallTokens: number; outputPerCallTokens: number } | null,
95
+ ): VerifiedAction['attribution'] {
96
+ const before = action.detail.baseline;
97
+ if (before === undefined || after === null) return null;
98
+ return {
99
+ calls: { before: before.calls, after: after.calls },
100
+ inputPerCallTokens: { before: before.inputPerCallTokens, after: after.inputPerCallTokens },
101
+ outputPerCallTokens: { before: before.outputPerCallTokens, after: after.outputPerCallTokens },
102
+ };
103
+ }
104
+
105
+ function perCall(breakdown: { calls: number; inputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; outputTokens: number }) {
106
+ return {
107
+ calls: breakdown.calls,
108
+ inputPerCallTokens:
109
+ (breakdown.inputTokens + breakdown.cacheReadTokens + breakdown.cacheWriteTokens) / breakdown.calls,
110
+ outputPerCallTokens: breakdown.outputTokens / breakdown.calls,
111
+ };
112
+ }
113
+
114
+ export function verifyPlan(
115
+ plan: PlanDocument & { createdAt?: string },
116
+ report: UsageProfileReport,
117
+ options: { currentPricingLastReviewed: string },
118
+ ): PlanVerification {
119
+ const actions: VerifiedAction[] = [];
120
+
121
+ for (const action of plan.actions) {
122
+ const slices = slicesForLabel(report, action.label);
123
+ const total = slices.reduce((sum, s) => sum + s.breakdown.totalUsd, 0);
124
+ const allCalls = slices.reduce((sum, s) => sum + s.breakdown.calls, 0);
125
+
126
+ /** The label carries no priced traffic any more: nothing can be told. */
127
+ if (slices.length === 0) {
128
+ actions.push({
129
+ action,
130
+ outcome: 'cannot-tell',
131
+ reason: 'workload-vanished',
132
+ observed: {},
133
+ attribution: null,
134
+ gateFailing: false,
135
+ });
136
+ continue;
137
+ }
138
+
139
+ if (action.kind === 'route' || action.kind === 'route+batch') {
140
+ const target = action.detail.routeTo!;
141
+ const dearest = slices[0]!;
142
+ const onTarget = slices.find((s) => s.model === target.id);
143
+ const stillOnOld = slices.find((s) => s.model === action.model);
144
+ const moved = dearest.model === target.id;
145
+ const after = perCall(
146
+ moved ? dearest.breakdown : (stillOnOld ?? dearest).breakdown,
147
+ );
148
+ actions.push({
149
+ action,
150
+ outcome: moved ? 'arrived' : 'not-arrived',
151
+ reason: null,
152
+ observed: {
153
+ dearestModel: dearest.model,
154
+ onTargetUsd: onTarget?.breakdown.totalUsd ?? 0,
155
+ onOldModelUsd: stillOnOld?.breakdown.totalUsd ?? 0,
156
+ labelUsd: total,
157
+ labelCalls: allCalls,
158
+ // The batch half of route+batch cannot be seen in token counts;
159
+ // the rendering names it instead of counting it as arrived.
160
+ ...(action.kind === 'route+batch' ? { batchObservable: 0 } : {}),
161
+ },
162
+ attribution: attributionFrom(action, after),
163
+ gateFailing: !moved,
164
+ });
165
+ continue;
166
+ }
167
+
168
+ if (action.kind === 'batch') {
169
+ // Tokens do not say which tier billed them. Not the team's silence,
170
+ // so it cannot fail the gate — but it is said, never assumed arrived.
171
+ actions.push({
172
+ action,
173
+ outcome: 'cannot-tell',
174
+ reason: 'tier-not-recorded',
175
+ observed: { labelUsd: total, labelCalls: allCalls },
176
+ attribution: null,
177
+ gateFailing: false,
178
+ });
179
+ continue;
180
+ }
181
+
182
+ const slice = slices.find((s) => s.model === action.model);
183
+
184
+ if (action.kind === 'fix-truncation') {
185
+ // The detection needs sessions and timestamps; a log that dropped them
186
+ // reads as "no retries" for the wrong reason, and that must not pass.
187
+ if (!report.hasSessions || report.span === null) {
188
+ actions.push({
189
+ action,
190
+ outcome: 'cannot-tell',
191
+ reason: 'fields-stopped',
192
+ observed: {},
193
+ attribution: attributionFrom(action, slice ? perCall(slice.breakdown) : null),
194
+ gateFailing: true,
195
+ });
196
+ continue;
197
+ }
198
+ const row = report.truncationRetries.find(
199
+ (r) => r.label === action.label && r.model === action.model,
200
+ );
201
+ const newStake = row === undefined ? 0 : row.wastedUsd + row.retryUsd;
202
+ actions.push({
203
+ action,
204
+ outcome: row === undefined ? 'arrived' : 'not-arrived',
205
+ reason: null,
206
+ observed: {
207
+ retryBillUsd: newStake,
208
+ retried: row?.retried ?? 0,
209
+ truncatedCalls: row?.truncatedCalls ?? 0,
210
+ },
211
+ attribution: attributionFrom(action, slice ? perCall(slice.breakdown) : null),
212
+ gateFailing: row !== undefined,
213
+ });
214
+ continue;
215
+ }
216
+
217
+ // fix-caching.
218
+ if (slice === undefined) {
219
+ actions.push({
220
+ action,
221
+ outcome: 'cannot-tell',
222
+ reason: 'workload-vanished',
223
+ observed: {},
224
+ attribution: null,
225
+ gateFailing: false,
226
+ });
227
+ continue;
228
+ }
229
+ const economics = cacheEconomics(slice.breakdown);
230
+ if (economics.verdict === 'lost-money' && economics.worstCaseVerdict === economics.verdict) {
231
+ actions.push({
232
+ action,
233
+ outcome: 'not-arrived',
234
+ reason: null,
235
+ observed: { deltaUsd: economics.deltaUsd, spentUsd: economics.spentUsd },
236
+ attribution: attributionFrom(action, perCall(slice.breakdown)),
237
+ gateFailing: true,
238
+ });
239
+ } else if (economics.worstCaseVerdict !== economics.verdict) {
240
+ // The verdict cannot settle on this log: the fields that would settle
241
+ // it are not there, and an unverifiable fix is not a verified one.
242
+ actions.push({
243
+ action,
244
+ outcome: 'cannot-tell',
245
+ reason: 'fields-stopped',
246
+ observed: {},
247
+ attribution: attributionFrom(action, perCall(slice.breakdown)),
248
+ gateFailing: true,
249
+ });
250
+ } else {
251
+ actions.push({
252
+ action,
253
+ outcome: 'arrived',
254
+ reason: null,
255
+ observed: { deltaUsd: economics.deltaUsd, spentUsd: economics.spentUsd },
256
+ attribution: attributionFrom(action, perCall(slice.breakdown)),
257
+ gateFailing: false,
258
+ });
259
+ }
260
+ }
261
+
262
+ return {
263
+ schemaVersion: 1,
264
+ planCreatedAt: plan.createdAt ?? null,
265
+ planPricing: plan.pricingLastReviewed,
266
+ currentPricing: options.currentPricingLastReviewed,
267
+ pricesChanged: plan.pricingLastReviewed !== options.currentPricingLastReviewed,
268
+ actions,
269
+ arrived: actions.filter((a) => a.outcome === 'arrived').length,
270
+ notArrived: actions.filter((a) => a.outcome === 'not-arrived').length,
271
+ cannotTell: actions.filter((a) => a.outcome === 'cannot-tell').length,
272
+ gateFailures: actions.filter((a) => a.gateFailing).length,
273
+ };
274
+ }