Skip to content

Commit 897e1ff

Browse files
committed
fix(server): prevent stale token attribution and handle db scan failures
1 parent 10d0844 commit 897e1ff

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

‎apps/server/src/provider/Layers/OpenCodeAdapter.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,8 @@ interface OpenCodeSessionContext {
350350
>;
351351
/** Counter for generic token events without a stable id. */
352352
dedupeCounter: number;
353+
/** Persistent map from dedupeKey to the turn that created it, for stale-event detection. */
354+
messageTurnMap: Map<string, TurnId>;
353355
cancellation: OpenCodeCancellation | undefined;
354356
interruptedTurnId: TurnId | undefined;
355357
reconcileIdleStatus: boolean;
@@ -1071,6 +1073,28 @@ export function makeOpenCodeAdapter(
10711073
: "opencode";
10721074
if (id) modelKey = `${prov}/${id}`;
10731075
}
1076+
// Stale-event guard: if this dedupeKey was already seen for a different
1077+
// turn, this is a late event from a prior turn that would otherwise
1078+
// contaminate the new turn's totals.
1079+
if (dedupeKey) {
1080+
const existingTurnId = context.messageTurnMap.get(dedupeKey);
1081+
if (existingTurnId !== undefined) {
1082+
if (existingTurnId !== turnId) {
1083+
yield* emit({
1084+
...(yield* buildEventBase({
1085+
threadId: context.session.threadId,
1086+
turnId,
1087+
raw,
1088+
})),
1089+
type: "thread.token-usage.updated",
1090+
payload: { usage: snapshot },
1091+
});
1092+
return;
1093+
}
1094+
} else {
1095+
context.messageTurnMap.set(dedupeKey, turnId);
1096+
}
1097+
}
10741098
const key = dedupeKey ?? `generic:${context.dedupeCounter++}`;
10751099
context.tokenDedupeMap.set(key, { tokens, cost: costValue, modelKey });
10761100
// Recompute aggregated totals from the dedupe map.
@@ -2788,6 +2812,7 @@ export function makeOpenCodeAdapter(
27882812
modelUsage: new Map(),
27892813
tokenDedupeMap: new Map(),
27902814
dedupeCounter: 0,
2815+
messageTurnMap: new Map(),
27912816
cancellation: undefined,
27922817
interruptedTurnId: undefined,
27932818
reconcileIdleStatus: false,

‎apps/server/src/usage/usageOpenCodeDb.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,8 +163,7 @@ export async function readOpenCodeDbRecords(
163163
// Retain reference to stmt until iteration completes (see comment above).
164164
void stmt;
165165
} catch {
166-
// One table failing shouldn't hide the other; treat as empty for that table.
167-
continue;
166+
return null;
168167
}
169168
}
170169
return records;

0 commit comments

Comments
 (0)