Token usage: keep cache/reasoning split, count only recorded steps, cost only when positive; captures fixture, docs and notes
This commit is contained in:
@@ -11,6 +11,7 @@ class TokenUsage {
|
||||
required this.partial,
|
||||
this.input,
|
||||
this.output,
|
||||
this.cacheRead,
|
||||
this.cost,
|
||||
this.costPartial = false,
|
||||
this.stages,
|
||||
@@ -27,7 +28,16 @@ class TokenUsage {
|
||||
final int? input;
|
||||
final int? output;
|
||||
|
||||
/// The reported cost in USD, only when some stage reported one.
|
||||
/// The cache-read share of [total], only when every counted stage reported
|
||||
/// its cache components. Older rows never recorded them, so they have none.
|
||||
final int? cacheRead;
|
||||
|
||||
/// The tokens that were not cache reads, when [cacheRead] is known.
|
||||
int? get fresh => cacheRead == null ? null : total - cacheRead!;
|
||||
|
||||
/// The reported cost in USD, only when a positive cost was reported. Some
|
||||
/// providers (subscription models) report a cost of zero or none at all;
|
||||
/// that is "not reported", never a known zero.
|
||||
final double? cost;
|
||||
|
||||
/// Some stages reported no cost, so [cost] is a lower bound.
|
||||
@@ -51,14 +61,16 @@ TokenUsage? runTokenUsage(JsonMap run) {
|
||||
if (tokenStages <= 0 || total == null) return null;
|
||||
final costStages = _int(raw['cost_known_stages']) ?? 0;
|
||||
final split = raw['split_known'] == true;
|
||||
final cost = costStages > 0 ? _positive(raw['cost_usd']) : null;
|
||||
return TokenUsage(
|
||||
total: total,
|
||||
partial: stages != null && tokenStages < stages,
|
||||
// The server omits a zero in/out, so a known split makes absence zero.
|
||||
input: split ? _int(raw['tokens_in']) ?? 0 : null,
|
||||
output: split ? _int(raw['tokens_out']) ?? 0 : null,
|
||||
cost: costStages > 0 ? _double(raw['cost_usd']) ?? 0 : null,
|
||||
costPartial: costStages > 0 && stages != null && costStages < stages,
|
||||
cacheRead: _cacheRead(raw, total),
|
||||
cost: cost,
|
||||
costPartial: cost != null && stages != null && costStages < stages,
|
||||
stages: stages,
|
||||
tokenStages: tokenStages,
|
||||
);
|
||||
@@ -77,7 +89,8 @@ TokenUsage? stageTokenUsage(JsonMap step) {
|
||||
partial: false,
|
||||
input: split ? _int(raw['tokens_in']) ?? 0 : null,
|
||||
output: split ? _int(raw['tokens_out']) ?? 0 : null,
|
||||
cost: raw['cost_known'] == true ? _double(raw['cost_usd']) ?? 0 : null,
|
||||
cacheRead: _cacheRead(raw, total),
|
||||
cost: raw['cost_known'] == true ? _positive(raw['cost_usd']) : null,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -109,37 +122,46 @@ String formatTokenCount(int tokens) {
|
||||
String tokenUsageLabel(TokenUsage usage) =>
|
||||
'${usage.partial ? '≥' : ''}${formatTokenCount(usage.total)} tokens';
|
||||
|
||||
/// The detail's token value: the compact total, the in/out split when
|
||||
/// The detail's token value: the compact total, then fresh versus cached
|
||||
/// when every stage reported its cache components, the in/out split when
|
||||
/// reported, and how many stages reported when the total is partial.
|
||||
/// `22.4M (20M in, 2.4M out)`, `≥9 · 1 of 2 stages reported`.
|
||||
String tokenUsageDetail(TokenUsage usage) {
|
||||
final parts = <String>[
|
||||
[
|
||||
'${usage.partial ? '≥' : ''}${formatTokenCount(usage.total)}',
|
||||
if (usage.input != null && usage.output != null)
|
||||
'(${formatTokenCount(usage.input!)} in, '
|
||||
'${formatTokenCount(usage.output!)} out)',
|
||||
].join(' '),
|
||||
if (usage.partial && usage.stages != null)
|
||||
'${usage.tokenStages} of ${usage.stages} stages reported',
|
||||
];
|
||||
return parts.join(' · ');
|
||||
}
|
||||
/// `22.4M · 1.1M fresh, 21.3M cached · 900K in, 150K out`,
|
||||
/// `≥9 · 1 of 2 stages reported`.
|
||||
String tokenUsageDetail(TokenUsage usage) => [
|
||||
'${usage.partial ? '≥' : ''}${formatTokenCount(usage.total)}',
|
||||
if (usage.fresh != null)
|
||||
'${formatTokenCount(usage.fresh!)} fresh, '
|
||||
'${formatTokenCount(usage.cacheRead!)} cached',
|
||||
if (usage.input != null && usage.output != null)
|
||||
'${formatTokenCount(usage.input!)} in, '
|
||||
'${formatTokenCount(usage.output!)} out',
|
||||
if (usage.partial && usage.stages != null)
|
||||
'${usage.tokenStages} of ${usage.stages} stages reported',
|
||||
].join(' · ');
|
||||
|
||||
/// The reported cost, or null when no stage reported one: `$1.75`, `$0.10`,
|
||||
/// `$0.0042` (four places below a cent),
|
||||
/// `≥$0.10` when some stages reported no cost.
|
||||
String? tokenUsageCost(TokenUsage usage) {
|
||||
/// The wording for a cost no stage reported as a positive amount.
|
||||
const costNotReported = 'Not reported';
|
||||
|
||||
/// The reported cost: `$1.75`, `$0.10`, `$0.0042` (four places below a cent),
|
||||
/// `≥$0.10` when some stages reported no cost, and [costNotReported] when no
|
||||
/// positive cost was reported.
|
||||
String tokenUsageCost(TokenUsage usage) {
|
||||
final cost = usage.cost;
|
||||
if (cost == null) return null;
|
||||
final text = cost >= 0.01 || cost == 0
|
||||
? cost.toStringAsFixed(2)
|
||||
: cost.toStringAsFixed(4);
|
||||
if (cost == null) return costNotReported;
|
||||
final text = cost >= 0.01 ? cost.toStringAsFixed(2) : cost.toStringAsFixed(4);
|
||||
return '${usage.costPartial ? '≥' : ''}\$$text';
|
||||
}
|
||||
|
||||
int? _int(dynamic value) =>
|
||||
value is num && value.isFinite && value >= 0 ? value.round() : null;
|
||||
|
||||
double? _double(dynamic value) =>
|
||||
value is num && value.isFinite && value >= 0 ? value.toDouble() : null;
|
||||
double? _positive(dynamic value) =>
|
||||
value is num && value.isFinite && value > 0 ? value.toDouble() : null;
|
||||
|
||||
/// The cache reads, only when the server marked the cache split complete and
|
||||
/// the count fits inside the total.
|
||||
int? _cacheRead(Map raw, int total) {
|
||||
if (raw['cache_known'] != true) return null;
|
||||
final read = _int(raw['cache_read']) ?? 0;
|
||||
return read <= total ? read : null;
|
||||
}
|
||||
|
||||
@@ -76,6 +76,7 @@ List<DetailMetric> detailUsageMetrics(dynamic raw) {
|
||||
final tokenStages = _int(usage['tokens_known_stages']) ?? 0;
|
||||
final costStages = _int(usage['cost_known_stages']) ?? 0;
|
||||
final totalTokens = _int(usage['tokens_total']);
|
||||
final cost = usage['cost_usd'] is num ? usage['cost_usd'] as num : null;
|
||||
final splitKnown = usage['split_known'] == true && tokenStages > 0;
|
||||
final rows = <DetailMetric>[
|
||||
if (stages != null) (label: 'Stages', value: '$stages'),
|
||||
@@ -95,11 +96,11 @@ List<DetailMetric> detailUsageMetrics(dynamic raw) {
|
||||
),
|
||||
(
|
||||
label: 'Reported cost',
|
||||
// cost_usd is omitted by the server when zero, so a known stage count
|
||||
// makes an absent value a real $0.000000 rather than an unknown cost.
|
||||
value: costStages == 0
|
||||
? 'Unavailable'
|
||||
: '\$${((usage['cost_usd'] as num?) ?? 0).toStringAsFixed(6)}',
|
||||
// A cost of zero (or none) is what subscription models report even
|
||||
// with a "known" cost: it is not reported, never a measured zero.
|
||||
value: costStages == 0 || cost == null || cost <= 0
|
||||
? 'Not reported'
|
||||
: '\$${cost.toStringAsFixed(6)}',
|
||||
),
|
||||
];
|
||||
if (stages != null && tokenStages < stages) {
|
||||
|
||||
@@ -84,8 +84,7 @@ List<VisitFact> detailVisitFacts(JsonMap step) {
|
||||
final usage = stageTokenUsage(step);
|
||||
if (usage != null) {
|
||||
facts.add((label: 'Tokens', value: tokenUsageDetail(usage)));
|
||||
final cost = tokenUsageCost(usage);
|
||||
if (cost != null) facts.add((label: 'Cost', value: cost));
|
||||
facts.add((label: 'Cost', value: tokenUsageCost(usage)));
|
||||
}
|
||||
final target = _text(step['target']);
|
||||
if (target != null) facts.add((label: 'Target', value: target));
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Run token usage beside size
|
||||
|
||||
Runs that spend 20M+ tokens now show it the way they show disk size.
|
||||
|
||||
## Server (payload)
|
||||
|
||||
- `RunSummary.usage` (`protocol.RunUsage`) moved up from `RunDetail`, so
|
||||
`list_runs` rows carry the run total too. `get_run` still sends `usage` at
|
||||
the same JSON key, now through the embedded summary.
|
||||
- The list fills it with one grouped `step_usage` aggregate per 100-run batch
|
||||
(`internal/pipeline/run_usage.go`), using the same column sums as the
|
||||
history-wide stats (`usageSumColumns` in `stats.go`). It is joined to
|
||||
`run_steps`, so orphaned usage rows (reported: about 650 rows, 1.47B tokens,
|
||||
left by an Oct 19 history wipe) no longer count in stats or per-run totals.
|
||||
The rows are not deleted. If a wiped run id was reused, an orphan row that
|
||||
matches a new run's (run_id, sequence) still cannot be told apart.
|
||||
- `StageUsage` now keeps `tokens_reasoning`, `cache_read` and `cache_write`
|
||||
with `cache_known` (the runner dropped them before). They are JSON keys in
|
||||
`usage_json`, so old rows need no migration: they lack `cache_known`, so
|
||||
their cache share is unknown, not zero. Run totals add `cache_known_stages`
|
||||
and `cache_known` (every token-reporting stage recorded the split).
|
||||
|
||||
## App
|
||||
|
||||
- `lib/features/runs/domain/run_tokens.dart`: parsing and formatting.
|
||||
`22.4M tokens`, `≥9.1M tokens` when `tokens_known_stages < stages`. Nothing
|
||||
is estimated, and a row without `usage` (an older server) shows nothing.
|
||||
- List row: tokens after the size, in both the full and the compact subtitle.
|
||||
- Sort: `Most tokens` (`most_tokens`) after `Largest first`, flat like it.
|
||||
Runs without a reported total sort last.
|
||||
- Summary: `Size on disk`, `Tokens` (`22.4M · 2.1M fresh, 20.3M cached ·
|
||||
1.8M in, 240K out`; fresh is total minus cache reads, shown only when
|
||||
`cache_known`) and `Cost`.
|
||||
- Stage rows: the Timeline row subtitle adds `· 20.1M tokens`. The visit facts
|
||||
add `Tokens` and `Cost`.
|
||||
- Cost is shown only when a positive `cost_usd` was reported. Subscription
|
||||
models report `cost_known` with no amount, which shows as `Not reported`.
|
||||
The stats page's `Reported cost` uses the same rule.
|
||||
- `usage` is no longer treated as detail-only in
|
||||
`RunsController.acceptRunDetail`, so opening a run refreshes its row's total.
|
||||
|
||||
## Evidence
|
||||
|
||||
Fixture: `tool/probe_usage_fixture.dart`, opt-in `?usage=1` on the capture
|
||||
entry (run 7: 340 MB, 22.4M tokens, mostly cached, $1.42; run 6: partial
|
||||
≥9.1M). Captures were taken with `tool/capture` at 560x1000 and 1400x900:
|
||||
the list, the sort sheet, Most tokens, the run 7 Summary and Timeline, the
|
||||
build and plan visits, and the no-usage (old-server) list and Summary.
|
||||
@@ -82,14 +82,17 @@ void main() {
|
||||
),
|
||||
),
|
||||
)!;
|
||||
expect(tokenUsageDetail(usage), '22.4M (20M in, 2.4M out)');
|
||||
expect(tokenUsageDetail(usage), '22.4M · 20M in, 2.4M out');
|
||||
expect(tokenUsageCost(usage), '\$1.75');
|
||||
|
||||
final partialCost = runTokenUsage(
|
||||
_run(1, usage: _usage(9, stages: 2, costStages: 1, cost: 0.1)),
|
||||
)!;
|
||||
expect(tokenUsageCost(partialCost), '≥\$0.10');
|
||||
expect(tokenUsageCost(runTokenUsage(_run(1, usage: _usage(9)))!), isNull);
|
||||
expect(
|
||||
tokenUsageCost(runTokenUsage(_run(1, usage: _usage(9)))!),
|
||||
'Not reported',
|
||||
);
|
||||
expect(
|
||||
tokenUsageCost(
|
||||
runTokenUsage(_run(1, usage: _usage(9, costStages: 1, cost: 0.0042)))!,
|
||||
@@ -98,6 +101,52 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
test('the detail splits fresh from cached when every stage reported it', () {
|
||||
final usage = runTokenUsage(
|
||||
_run(
|
||||
1,
|
||||
usage: {
|
||||
..._usage(22400000, split: true, input: 900000, output: 150000),
|
||||
'cache_known': true,
|
||||
'cache_read': 21300000,
|
||||
'cache_write': 50000,
|
||||
},
|
||||
),
|
||||
)!;
|
||||
expect(tokenUsageLabel(usage), '22.4M tokens');
|
||||
expect(usage.fresh, 1100000);
|
||||
expect(
|
||||
tokenUsageDetail(usage),
|
||||
'22.4M · 1.1M fresh, 21.3M cached · 900K in, 150K out',
|
||||
);
|
||||
// An older row (or a partial cache split) has no cache figure: just the
|
||||
// total and what else it reported.
|
||||
final old = runTokenUsage(
|
||||
_run(
|
||||
1,
|
||||
usage: _usage(22400000, split: true, input: 900000, output: 150000),
|
||||
),
|
||||
)!;
|
||||
expect(old.fresh, isNull);
|
||||
expect(tokenUsageDetail(old), '22.4M · 900K in, 150K out');
|
||||
});
|
||||
|
||||
test('a zero or missing "known" cost is not reported, never \$0', () {
|
||||
// Subscription models report cost_known with no positive cost_usd.
|
||||
for (final usage in [
|
||||
_usage(9, costStages: 1),
|
||||
_usage(9, costStages: 1, cost: 0),
|
||||
]) {
|
||||
final tokens = runTokenUsage(_run(1, usage: usage))!;
|
||||
expect(tokens.cost, isNull);
|
||||
expect(tokenUsageCost(tokens), 'Not reported');
|
||||
}
|
||||
final stage = stageTokenUsage({
|
||||
'usage': {'tokens_total': 9, 'tokens_known': true, 'cost_known': true},
|
||||
})!;
|
||||
expect(tokenUsageCost(stage), 'Not reported');
|
||||
});
|
||||
|
||||
test('a stage reports its own tokens only when it counted them', () {
|
||||
final stage = stageTokenUsage({
|
||||
'usage': {
|
||||
@@ -110,7 +159,7 @@ void main() {
|
||||
'cost_usd': 0.02,
|
||||
},
|
||||
})!;
|
||||
expect(tokenUsageDetail(stage), '1.5K (1.2K in, 300 out)');
|
||||
expect(tokenUsageDetail(stage), '1.5K · 1.2K in, 300 out');
|
||||
expect(tokenUsageCost(stage), '\$0.02');
|
||||
expect(
|
||||
stageTokenUsage({
|
||||
|
||||
@@ -98,7 +98,7 @@ void main() {
|
||||
expect(rows.firstWhere((row) => row.label == 'Size on disk').value, '5 MB');
|
||||
expect(
|
||||
rows.firstWhere((row) => row.label == 'Tokens').value,
|
||||
'123 (100 in, 23 out)',
|
||||
'123 · 100 in, 23 out',
|
||||
);
|
||||
expect(rows.firstWhere((row) => row.label == 'Cost').value, '\$0.50');
|
||||
expect(rows.firstWhere((row) => row.label == 'Retry of').value, 'run 12');
|
||||
|
||||
@@ -30,7 +30,7 @@ void main() {
|
||||
final facts = detailVisitFacts(_reported);
|
||||
expect(
|
||||
facts,
|
||||
contains((label: 'Tokens', value: '1.5M (1.2M in, 300K out)')),
|
||||
contains((label: 'Tokens', value: '1.5M · 1.2M in, 300K out')),
|
||||
);
|
||||
expect(facts, contains((label: 'Cost', value: '\$0.42')));
|
||||
final none = detailVisitFacts(_unreported);
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
|
||||
/// Opt-in (`?usage=1`) size and reported token usage for the capture
|
||||
/// fixture's runs, shaped exactly as the server sends them: a run-level
|
||||
/// `usage` total (list and detail) and a per-step `usage`. Without the
|
||||
/// parameter the fixture keeps the old-server shape with neither.
|
||||
bool probeUsage = false;
|
||||
|
||||
/// Per-step usage of run 7, by recorded sequence. The build visit is mostly
|
||||
/// cache reads, as a caching harness reports; plan 1 predates the cache split.
|
||||
const _stepUsage = <int, JsonMap>{
|
||||
5: {
|
||||
'tokens_total': 1200000,
|
||||
'tokens_known': true,
|
||||
'split_known': true,
|
||||
'tokens_in': 300000,
|
||||
'tokens_out': 60000,
|
||||
'tokens_reasoning': 40000,
|
||||
'cache_read': 780000,
|
||||
'cache_write': 20000,
|
||||
'cache_known': true,
|
||||
'cost_known': true,
|
||||
},
|
||||
2: {
|
||||
'tokens_total': 20100000,
|
||||
'tokens_known': true,
|
||||
'split_known': true,
|
||||
'tokens_in': 500000,
|
||||
'tokens_out': 80000,
|
||||
'tokens_reasoning': 20000,
|
||||
'cache_read': 19480000,
|
||||
'cache_write': 20000,
|
||||
'cache_known': true,
|
||||
'cost_usd': 1.42,
|
||||
'cost_known': true,
|
||||
},
|
||||
1: {
|
||||
'tokens_total': 1100000,
|
||||
'tokens_known': true,
|
||||
'split_known': true,
|
||||
'tokens_in': 1000000,
|
||||
'tokens_out': 100000,
|
||||
'cache_known': true,
|
||||
'cache_read': 0,
|
||||
'cost_known': true,
|
||||
},
|
||||
};
|
||||
|
||||
/// Run 7's total over [_stepUsage], as the server's aggregate sums it.
|
||||
const _run7Usage = <String, dynamic>{
|
||||
'stages': 3,
|
||||
'tokens_total': 22400000,
|
||||
'tokens_known_stages': 3,
|
||||
'split_known': true,
|
||||
'tokens_in': 1800000,
|
||||
'tokens_out': 240000,
|
||||
'tokens_reasoning': 60000,
|
||||
'cache_read': 20260000,
|
||||
'cache_write': 40000,
|
||||
'cache_known': true,
|
||||
'cache_known_stages': 3,
|
||||
'cost_usd': 1.42,
|
||||
'cost_known_stages': 3,
|
||||
};
|
||||
|
||||
/// Run 6: one of its two stages reported no token count, so its total is a
|
||||
/// lower bound; no stage reported a positive cost.
|
||||
const _run6Usage = <String, dynamic>{
|
||||
'stages': 2,
|
||||
'tokens_total': 9100000,
|
||||
'tokens_known_stages': 1,
|
||||
'split_known': false,
|
||||
'split_unknown_stages': 1,
|
||||
'cost_known_stages': 1,
|
||||
'cost_unknown_stages': 1,
|
||||
};
|
||||
|
||||
/// Adds the run's size and usage to a list row or detail when enabled.
|
||||
JsonMap withProbeUsage(JsonMap run) {
|
||||
if (!probeUsage) return run;
|
||||
return switch (run['id']) {
|
||||
7 => {...run, 'size_bytes': 340 * 1024 * 1024, 'usage': _run7Usage},
|
||||
6 => {...run, 'size_bytes': 4404019, 'usage': _run6Usage},
|
||||
_ => run,
|
||||
};
|
||||
}
|
||||
|
||||
/// Adds the recorded per-step usage to run 7's steps when enabled.
|
||||
JsonMap withProbeStepUsage(JsonMap step) {
|
||||
final usage = _stepUsage[step['sequence']];
|
||||
return probeUsage && usage != null ? {...step, 'usage': usage} : step;
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import 'perf/chat_search_fixture.dart';
|
||||
import 'perf/chat_scroll_fixture.dart';
|
||||
import 'perf/perf_fixture.dart';
|
||||
import 'probe_folder_fixture.dart';
|
||||
import 'probe_usage_fixture.dart';
|
||||
|
||||
/// The run every run-scoped hit names. Its recorded sequences are deliberately
|
||||
/// not its row indexes (plan 5, build 2, plan 1), exactly like the unit
|
||||
@@ -414,12 +415,28 @@ JsonMap? probeReply(JsonMap request) {
|
||||
'time': '2026-10-20T09:00:00Z',
|
||||
};
|
||||
case 'list_runs':
|
||||
return {'id': id, 'type': 'runs', 'runs': probeRuns(), 'usage': null};
|
||||
return {
|
||||
'id': id,
|
||||
'type': 'runs',
|
||||
'runs': probeRuns().map(withProbeUsage).toList(),
|
||||
'usage': null,
|
||||
};
|
||||
case 'get_run':
|
||||
if (request['run_id'] != 7) {
|
||||
return error('Fixture run ${request['run_id']} is unavailable');
|
||||
}
|
||||
return {'id': id, 'type': 'run', 'run_detail': probeRunDetail()};
|
||||
final detail = withProbeUsage(probeRunDetail());
|
||||
return {
|
||||
'id': id,
|
||||
'type': 'run',
|
||||
'run_detail': {
|
||||
...detail,
|
||||
'steps': [
|
||||
for (final step in detail['steps'] as List)
|
||||
withProbeStepUsage(step as JsonMap),
|
||||
],
|
||||
},
|
||||
};
|
||||
case 'list_pipelines':
|
||||
return {'id': id, 'type': 'pipelines', 'pipelines': probePipelines()};
|
||||
case 'get_pipeline':
|
||||
@@ -606,6 +623,7 @@ void main() {
|
||||
configurePerfFixture(params);
|
||||
_fillerRunCount = int.tryParse(params['runs'] ?? '') ?? 0;
|
||||
_fillerStepCount = int.tryParse(params['steps'] ?? '') ?? 0;
|
||||
probeUsage = params['usage'] == '1';
|
||||
final cupertino = params['platform'] == 'cupertino';
|
||||
final route = params['route'];
|
||||
final opensRoute = route != null && route.startsWith('/');
|
||||
|
||||
Reference in New Issue
Block a user