fix(agent-usage): clear Thufir pass-1 findings (5 correctness fixes)

1. Gate unknown-intervals caveat on direct i/o incompleteness
   (isPartialField(inputTokens) || isPartialField(outputTokens)) instead
   of hasUnknownUsage, which ORs total/cost incompleteness too and cannot
   prove an i/o interval claim. Narrow copy to 'Some input/output usage
   could not be counted and is omitted rather than shown as zero.' Fix the
   incorrect deltaReliable comment.

2. deriveDisplayTotal fail-closed: approximate only when BOTH input and
   output are non-null. One-sided i/o returns unknown for the total (the
   independent display fields may still show the known value). Replace
   one-sided approximate tests with fail-closed tests.

3. sumKnownBucketTotals returns a single provenance-bearing DisplayTotal
   instead of parallel {knownTotal, approxTotal, partial}. Exact when
   every report-bearing bucket is exact; approximate (summing
   exact+approx display values) when any bucket is approximate; unknown
   when any report-bearing bucket has no display value. Partial derives
   from the union of each bucket's DisplayTotal.partial (i/o and total
   completeness) — not from total absence. Add mixed-bucket test.

4. Partial provenance end-to-end: AgentUsageSection header consumes the
   single DisplayTotal and derives partial from its .partial field.
   deriveBarState carries dt.partial in the approx bar (new
   'approx-partial' kind) so genuinely incomplete i/o is identified in
   daily bar styling and accessible copy. Approximation alone no longer
   triggers Partial.

5. Behavioral e2e guard: new scenario seeds both i/o + totalTokens:null
   and asserts all four surfaces (overview row, header, daily bar,
   focused total) render '≈'. Fix stale 'in 800' assertion to '≈ 1K'.
   Update the coverage-dates partial-explanation fixture to use
   incomplete i/o fields so the new gate fires correctly.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
This commit is contained in:
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
2026-07-29 16:50:19 -04:00
parent b384fc9a56
commit 031541a301
6 changed files with 270 additions and 92 deletions

View File

@@ -379,22 +379,24 @@ test("deriveDisplayTotal approximate partial=true when either i/o field is incom
assert.equal(dt.partial, true);
});
test("deriveDisplayTotal returns approximate from input alone when output is null", () => {
test("deriveDisplayTotal returns unknown when only input is known and output is null (fail-closed)", () => {
const usage = reportedUsage({
inputTokens: usageField({ value: "500" }),
// outputTokens: null (default)
});
const dt = deriveDisplayTotal(usage);
assert.equal(dt.kind, "approximate");
assert.equal(dt.value, 500n);
assert.equal(dt.kind, "unknown");
assert.equal(dt.value, null);
});
test("deriveDisplayTotal returns approximate from output alone when input is null", () => {
test("deriveDisplayTotal returns unknown when only output is known and input is null (fail-closed)", () => {
const usage = reportedUsage({
outputTokens: usageField({ value: "300" }),
// inputTokens: null (default)
});
const dt = deriveDisplayTotal(usage);
assert.equal(dt.kind, "approximate");
assert.equal(dt.value, 300n);
assert.equal(dt.kind, "unknown");
assert.equal(dt.value, null);
});
test("deriveDisplayTotal returns unknown kind when all fields are null", () => {
@@ -438,6 +440,7 @@ test("sortAgentsByDisplayTotal ranks approximate totals above unknown totals", (
const approxAgent = agentUsage("approx", null, {
usage: reportedUsage({
inputTokens: usageField({ value: "100" }),
outputTokens: usageField({ value: "50" }),
}),
});
const unknownAgent = agentUsage("unknown", null);
@@ -451,12 +454,18 @@ test("sortAgentsByDisplayTotal handles mixed exact/approximate/unknown populatio
agentUsage("u1", null), // unknown
agentUsage("e1", "100"), // exact
agentUsage("a1", null, { // approximate
usage: reportedUsage({ inputTokens: usageField({ value: "500" }) }),
usage: reportedUsage({
inputTokens: usageField({ value: "400" }),
outputTokens: usageField({ value: "100" }),
}),
}),
agentUsage("u2", null), // unknown
agentUsage("e2", "300"), // exact
agentUsage("a2", null, { // approximate
usage: reportedUsage({ inputTokens: usageField({ value: "200" }) }),
usage: reportedUsage({
inputTokens: usageField({ value: "150" }),
outputTokens: usageField({ value: "50" }),
}),
}),
];
const sorted = sortAgentsByDisplayTotal(agents);
@@ -582,8 +591,8 @@ test("sumKnownBucketTotals returns knownTotal null and partial false for an all-
bucket({ reportCount: 0 }),
bucket({ reportCount: 0 }),
]);
assert.equal(result.knownTotal, null);
assert.equal(result.approxTotal, null);
assert.equal(result.kind, "unknown");
assert.equal(result.value, null);
assert.equal(result.partial, false);
});
@@ -598,8 +607,8 @@ test("sumKnownBucketTotals sums all known totals when every bucket is fully know
reportCount: 1,
}),
]);
assert.equal(result.knownTotal, 300n);
assert.equal(result.approxTotal, null); // genuine total is known, no approx needed
assert.equal(result.kind, "exact");
assert.equal(result.value, 300n);
assert.equal(result.partial, false);
});
@@ -616,23 +625,25 @@ test("sumKnownBucketTotals marks partial true when any bucket has an incomplete
reportCount: 1,
}),
]);
assert.equal(result.knownTotal, 300n);
assert.equal(result.kind, "exact");
assert.equal(result.value, 300n);
assert.equal(result.partial, true);
});
test("sumKnownBucketTotals marks partial true when any bucket has reports but null total (activity not fully counted)", () => {
test("sumKnownBucketTotals returns unknown when any report-bearing bucket has no display value", () => {
const result = sumKnownBucketTotals([
bucket({
usage: reportedUsage({ totalTokens: usageField({ value: "100" }) }),
reportCount: 1,
}),
// report-bearing bucket with no total and no i/o — display is unknown
bucket({ usage: reportedUsage(), reportCount: 1, hasUnknownUsage: true }),
]);
assert.equal(result.knownTotal, 100n);
assert.equal(result.partial, true);
assert.equal(result.kind, "unknown");
assert.equal(result.value, null);
});
test("sumKnownBucketTotals returns approxTotal from i/o sum when all bucket totals are null but i/o is known", () => {
test("sumKnownBucketTotals returns approximate from i/o sum when all bucket totals are null but i/o is known", () => {
// Real-world case: no publisher emits totalTokens, but i/o are always present.
const result = sumKnownBucketTotals([
bucket({
@@ -650,18 +661,61 @@ test("sumKnownBucketTotals returns approxTotal from i/o sum when all bucket tota
reportCount: 1,
}),
]);
assert.equal(result.knownTotal, null);
assert.equal(result.approxTotal, 1500n); // (800+200) + (400+100)
assert.equal(result.partial, true); // null totals with reports → partial
assert.equal(result.kind, "approximate");
assert.equal(result.value, 1500n); // (800+200) + (400+100)
assert.equal(result.partial, false); // i/o fields are complete — no PARTIAL badge
});
test("sumKnownBucketTotals returns null approxTotal when even i/o is unavailable", () => {
test("sumKnownBucketTotals marks partial true when any approximate bucket has incomplete i/o", () => {
const result = sumKnownBucketTotals([
bucket({
usage: reportedUsage({
inputTokens: usageField({ value: "800", incomplete: true }),
outputTokens: usageField({ value: "200" }),
}),
reportCount: 1,
}),
bucket({
usage: reportedUsage({
inputTokens: usageField({ value: "400" }),
outputTokens: usageField({ value: "100" }),
}),
reportCount: 1,
}),
]);
assert.equal(result.kind, "approximate");
assert.equal(result.partial, true);
});
test("sumKnownBucketTotals returns unknown when even i/o is unavailable for a report-bearing bucket", () => {
const result = sumKnownBucketTotals([
bucket({ usage: reportedUsage(), reportCount: 1, hasUnknownUsage: true }),
]);
assert.equal(result.knownTotal, null);
assert.equal(result.approxTotal, null);
assert.equal(result.partial, true);
assert.equal(result.kind, "unknown");
assert.equal(result.value, null);
assert.equal(result.partial, false);
});
test("sumKnownBucketTotals returns approximate when mixed exact and approximate buckets exist (mixed provider support)", () => {
// Steady-state once Task B supplies genuine totals for some providers:
// one bucket has an exact total; another has null total but known i/o.
const result = sumKnownBucketTotals([
bucket({
usage: reportedUsage({ totalTokens: usageField({ value: "1000" }) }),
reportCount: 1,
}),
bucket({
usage: reportedUsage({
inputTokens: usageField({ value: "300" }),
outputTokens: usageField({ value: "200" }),
}),
reportCount: 1,
}),
]);
// Any approximate bucket → aggregate is approximate; sums exact+approx display values.
assert.equal(result.kind, "approximate");
assert.equal(result.value, 1500n); // 1000 + (300+200)
assert.equal(result.partial, false);
});
// ── deriveUsageIngressTrailing ────────────────────────────────────────────────

View File

@@ -197,10 +197,11 @@ export function bigintRatio(part: bigint, whole: bigint): number {
*
* - `exact`: `totalTokens.value` is present and parsed. `partial` mirrors the
* wire field's `incomplete` flag.
* - `approximate`: `totalTokens.value` is absent but at least one of
* `inputTokens` / `outputTokens` is known; `value` is their bigint-safe sum.
* `partial` is `inputTokens.incomplete || outputTokens.incomplete`.
* Callers MUST render `≈` to distinguish this from a provider total.
* - `approximate`: `totalTokens.value` is absent and BOTH `inputTokens` and
* `outputTokens` are known; `value` is their bigint-safe sum. `partial` is
* `inputTokens.incomplete || outputTokens.incomplete`. Callers MUST render
* `≈` to distinguish this from a provider total. A missing category is
* unknown, not zero — one-sided i/o yields `unknown`, not `approximate`.
* - `unknown`: no token counts are available at all; `value` is `null`.
*
* This is a *display* value only — it is NEVER written to the wire or stored.
@@ -223,10 +224,10 @@ export function deriveDisplayTotal(usage: {
}
const input = parseTokenCount(usage.inputTokens.value);
const output = parseTokenCount(usage.outputTokens.value);
if (input !== null || output !== null) {
if (input !== null && output !== null) {
return {
kind: "approximate",
value: (input ?? 0n) + (output ?? 0n),
value: input + output,
partial: isPartialField(usage.inputTokens) || isPartialField(usage.outputTokens),
};
}
@@ -366,54 +367,57 @@ export function deriveUsageIngressTrailing(series: AgentUsageSeries): string {
}
/**
* Bigint-safe sum of each bucket's known `totalTokens` across a daily
* series, for the overview/focused-view header total. `partial` is true
* when any bucket has a known-but-incomplete total OR any bucket's total is
* fully unknown (activity happened somewhere in the window that this exact
* sum cannot include) — never silently reported as a complete figure.
* Returns `knownTotal: null` only when every bucket has zero reports (a
* true empty window, not partial data).
* Aggregate the per-bucket display totals across a daily series into a single
* provenance-bearing `DisplayTotal` for the overview/focused-view header.
*
* Also returns `approxTotal`: when `knownTotal` is null but at least one
* bucket has known input/output, this is the sum of all known i/o fields
* (labeled `≈` at the call site). Null when even i/o is unavailable.
* The approximation is a display-only convenience — never stored or wired.
* Aggregation rules:
* - `exact`: every report-bearing bucket has an exact display total.
* - `approximate`: at least one bucket is approximate (sum of all
* exact+approximate display values); a report-bearing bucket that is
* approximate or has no total does NOT force unknown if i/o is available.
* - `unknown`: any report-bearing bucket has no display value at all (neither
* exact nor approximate i/o available).
* - Empty window (no report-bearing buckets): `{ kind: "unknown", value: null, partial: false }`.
*
* `partial` reflects the i/o and total completeness of the contributing
* buckets (union of each bucket's `DisplayTotal.partial`) — it does NOT fire
* from total absence alone. An approximate aggregate with complete i/o carries
* `partial: false` even though no genuine provider total was emitted.
*
* The returned value is a *display* value only — never stored or wired.
*/
export function sumKnownBucketTotals(
buckets: readonly AgentUsageSeriesBucket[],
): {
knownTotal: bigint | null;
approxTotal: bigint | null;
partial: boolean;
} {
let sum = 0n;
let sawKnown = false;
): DisplayTotal {
let sumValue = 0n;
let sawAny = false; // any report-bearing bucket processed
let anyApprox = false; // at least one approximate bucket
let anyUnknown = false; // at least one report-bearing bucket with no display value
let partial = false;
let approxSum = 0n;
let sawApprox = false;
for (const bucket of buckets) {
const total = bucket.usage.totalTokens;
const known = parseTokenCount(total.value);
if (known !== null) {
sum += known;
sawKnown = true;
}
if (isPartialField(total) || (bucket.reportCount > 0 && known === null)) {
partial = true;
}
if (known === null) {
const dt = deriveDisplayTotal(bucket.usage);
if (dt.kind === "approximate") {
approxSum += dt.value;
sawApprox = true;
}
if (bucket.reportCount === 0) continue;
sawAny = true;
const dt = deriveDisplayTotal(bucket.usage);
if (dt.kind === "exact" || dt.kind === "approximate") {
sumValue += dt.value;
if (dt.partial) partial = true;
if (dt.kind === "approximate") anyApprox = true;
} else {
// Report-bearing bucket with no display value → aggregate is unknown.
anyUnknown = true;
}
}
return {
knownTotal: sawKnown ? sum : null,
approxTotal: !sawKnown && sawApprox ? approxSum : null,
partial,
};
if (!sawAny) {
// Truly empty window — no report-bearing buckets at all.
return { kind: "unknown", value: null, partial: false };
}
if (anyUnknown) {
return { kind: "unknown", value: null, partial: false };
}
if (anyApprox) {
return { kind: "approximate", value: sumValue, partial };
}
return { kind: "exact", value: sumValue, partial };
}

View File

@@ -70,8 +70,10 @@ function deriveBarState(bucket: AgentUsageSeriesBucket) {
const dt = deriveDisplayTotal(bucket.usage);
if (dt.kind === "approximate") {
return {
accessibleLabel: `${dateLabel} · ≈ ${formatTokenCountCompact(dt.value)} tokens (approx)`,
kind: "approx" as const,
accessibleLabel: `${dateLabel} · ≈ ${formatTokenCountCompact(dt.value)} tokens${
dt.partial ? " (partial)" : ""
}`,
kind: dt.partial ? ("approx-partial" as const) : ("approx" as const),
knownTokens: dt.value,
};
}
@@ -154,7 +156,7 @@ function DailyBar({
? "—"
: kind === "partial"
? `≥${formatTokenCountCompact(knownTokens ?? 0n)}`
: kind === "approx"
: kind === "approx" || kind === "approx-partial"
? `≈${formatTokenCountCompact(knownTokens ?? 0n)}`
: formatTokenCountCompact(knownTokens ?? 0n);
@@ -180,7 +182,7 @@ function DailyBar({
aria-label={accessibleLabel}
className={cn(
"w-full rounded-t-sm",
kind === "partial"
kind === "partial" || kind === "approx-partial"
? "bg-primary/50"
: kind === "approx"
? "bg-primary/70"

View File

@@ -208,16 +208,19 @@ function AgentUsageFocusedTotals({
const { estimatedCostUsd, inputTokens, outputTokens } =
agent.usage;
const models = sortModelsByDisplayTotal(agent.models);
// `explainPartial` controls the caveat paragraph. Each sentence is gated
// only on the condition that proves it:
// - unknown-intervals sentence: `agent.hasUnknownUsage` — true when
// deltaReliable is false for at least one interval in the window.
// Each caveat sentence is gated only on the condition that proves it:
// - unknown-intervals sentence: direct i/o incompleteness — true when at
// least one input or output field is known but flagged incomplete. This
// is the condition the copy claims ("input/output usage could not be
// counted"). `hasUnknownUsage` is NOT used here because it ORs total
// and cost incompleteness too, which cannot prove an i/o interval claim.
// - invalid-reports sentence: `coverage.invalidReportCount > 0` — true
// when rows were excluded from buckets due to bad timestamps or missing
// session cumulative totals.
// We do NOT trigger on totalTokens.value being null — that's the permanent
// state for all real publishers today, not a data quality problem.
const showUnknownIntervalsCaveat = agent.hasUnknownUsage;
const showUnknownIntervalsCaveat =
isPartialField(inputTokens) || isPartialField(outputTokens);
const showInvalidReportsCaveat = coverage.invalidReportCount > 0;
// Display total for the Total tokens stat.
@@ -304,8 +307,8 @@ function AgentUsageFocusedTotals({
</p>
{showUnknownIntervalsCaveat ? (
<p data-testid="agent-usage-focused-unknown-intervals-caveat">
Some usage could not be counted: unknown intervals are omitted
rather than shown as zero.
Some input/output usage could not be counted and is omitted rather
than shown as zero.
</p>
) : null}
{showInvalidReportsCaveat ? (

View File

@@ -175,14 +175,15 @@ function AgentUsageCard({
<div className="flex items-baseline justify-between gap-2">
<h3 className="text-sm font-medium text-foreground">Daily usage</h3>
<span className="text-sm text-muted-foreground">
{overallTotal.knownTotal !== null
? `${formatTokenCountCompact(overallTotal.knownTotal)} tokens`
: overallTotal.approxTotal !== null
? `≈ ${formatTokenCountCompact(overallTotal.approxTotal)} tokens`
{overallTotal.kind === "exact"
? `${formatTokenCountCompact(overallTotal.value)} tokens`
: overallTotal.kind === "approximate"
? `≈ ${formatTokenCountCompact(overallTotal.value)} tokens`
: hasInvalidOnlyInWindow
? "Usage uncountable"
: "No usage reported"}
{overallTotal.partial || hasInvalidOnlyInWindow ? (
{(overallTotal.kind !== "unknown" && overallTotal.partial) ||
hasInvalidOnlyInWindow ? (
<Badge className="ml-2" variant="outline">
Partial
</Badge>

View File

@@ -775,13 +775,24 @@ test("focused view shows daily bars, coverage dates, and a partial explanation w
{
start: bucketStart,
end: bucketStart + 86_400,
// incomplete=true → triggers partial explanation
usage: reportedUsage({ totalTokens: "500" }),
usage: reportedUsage({
// Incomplete i/o — proves the "input/output usage could not
// be counted" caveat sentence and triggers the gate.
inputTokens: "400",
outputTokens: "100",
totalTokens: "500",
}),
reportCount: 2,
hasUnknownUsage: true,
},
],
usage: reportedUsage({ totalTokens: "500" }),
usage: {
// Incomplete inputTokens → showUnknownIntervalsCaveat fires.
estimatedCostUsd: costField(null),
inputTokens: usageField("400", true), // incomplete
outputTokens: usageField("100", false),
totalTokens: usageField("500"),
},
}),
],
coverage: {
@@ -900,6 +911,109 @@ test("overview and focused view distinguish invalid-only windows from ordinary e
).toHaveCount(0);
});
// ── T1b: Behavioral regression guard — null totalTokens with known i/o renders ≈ ─
//
// This scenario will fail if the approximate display fallback is removed.
// It covers the real-world prod shape where no publisher emits totalTokens
// today — the overview row, header, daily bar, and focused total must all
// visibly render ≈ rather than "No usage reported".
test("overview row, header, daily bar, and focused total all render ≈ when totalTokens is null but i/o is known", async ({
page,
}) => {
await installMockBridge(page);
await openAgentsView(page);
const agentPubkey = await addGenericAgent(page, "general", "Approx Bot");
await page.evaluate(
({ series }) => {
const testWindow = window as Window & {
__BUZZ_E2E__?: { mock?: { agentUsageSeries?: unknown } };
};
testWindow.__BUZZ_E2E__ ??= {};
testWindow.__BUZZ_E2E__.mock ??= {};
testWindow.__BUZZ_E2E__.mock.agentUsageSeries = series;
},
{
series: mockUsageSeries({
agents: [
mockAgentUsage(agentPubkey, {
buckets: [
{
start: 1_700_000_000,
end: 1_700_086_400,
hasUnknownUsage: false,
reportCount: 1,
usage: reportedUsage({
inputTokens: "800",
outputTokens: "200",
totalTokens: null, // real prod shape — no provider total
}),
},
],
usage: reportedUsage({
inputTokens: "800",
outputTokens: "200",
totalTokens: null, // real prod shape — no provider total
}),
}),
],
buckets: [
{
start: 1_700_000_000,
end: 1_700_086_400,
hasUnknownUsage: false,
reportCount: 1,
usage: reportedUsage({
inputTokens: "800",
outputTokens: "200",
totalTokens: null,
}),
},
],
coverage: {
firstArchivedAt: 1_700_000_000,
firstReportedAt: 1_700_000_000,
hasUnknownUsage: false,
invalidReportCount: 0,
lastArchivedAt: 1_700_086_400,
lastReportedAt: 1_700_086_400,
reportCount: 1,
},
}),
},
);
await page.getByTestId("open-agents-view").click();
// Overview row must render ≈ approximate total, not "No usage reported".
const row = page.getByTestId(`agent-usage-row-${agentPubkey}`);
await expect(row).toBeVisible();
await expect(row).toContainText("≈");
await expect(row).not.toContainText("No usage reported");
// Section header must render ≈ total (sumKnownBucketTotals → approximate).
const overallBars = page.getByTestId("agent-usage-overall-bars");
await expect(overallBars).toBeVisible();
await expect(overallBars).toContainText("≈");
// Daily bar must render with a bar (not a hatched unknown baseline) and
// show ≈ trailing label.
const dailyBars = page.getByTestId("agent-usage-daily-bars");
await expect(dailyBars).toBeVisible();
await expect(dailyBars).toContainText("≈");
// Focused total must render ≈ approximate stat.
await row.click();
await expect(page.getByTestId("user-profile-panel")).toBeVisible();
await expect(page.getByTestId("agent-usage-focused-view")).toBeVisible();
const focusedTotals = page.getByTestId("agent-usage-focused-totals");
await expect(focusedTotals).toBeVisible();
await expect(focusedTotals).toContainText("≈");
await expect(focusedTotals).not.toContainText("No usage reported");
});
// ── T2: I/O-incomplete partial behavioral coverage ────────────────────────────
test("overview row shows Partial badge and ingress shows partial marker when I/O fields are incomplete with null total", async ({
@@ -940,10 +1054,10 @@ test("overview row shows Partial badge and ingress shows partial marker when I/O
const row = page.getByTestId(`agent-usage-row-${agentPubkey}`);
await expect(row).toBeVisible();
// Row must show Partial badge — not just the I/O text.
// Row must show Partial badge — the approximate total carries partial provenance.
await expect(row.getByText("Partial", { exact: true })).toBeVisible();
// Row must show the I/O breakdown text.
await expect(row).toContainText("in 800");
// Row must show the ≈ approximate total (both i/o present, null total → approx display).
await expect(row).toContainText("≈ 1K");
// Open the profile panel to reach the Info tab for ingress verification.
await row.click();