Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex): bill Codex rollups by cumulative totals, not timestamps

[._.]/ Adam Eivy0a942e2d26fd
diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.js
index 568acae493..4d540a6c90 100644
--- a/server/services/usageReconciler.js
+++ b/server/services/usageReconciler.js
@@ -61,10 +61,11 @@ const WINDOW_SLACK_MS = 60_000;
// but a run that already completed is never reconciled again.
const claimedMessages = new Set();
-// Highest cumulative boundary (epoch ms of the billed end snapshot) already
-// charged per Codex rollout path. Codex bills as a cumulative delta, so a
-// per-snapshot claim can't stop a GROWN rollout from re-including an earlier
-// run's tokens — only a high-water mark can.
+// Cumulative token totals already charged per Codex rollout path. Codex bills as
+// a cumulative delta, so a per-snapshot claim can't stop a GROWN rollout from
+// re-including an earlier run's tokens. Keyed on TOTALS rather than a timestamp
+// because several `token_count` snapshots can share one epoch millisecond — a
+// timestamp boundary would either re-bill them or drop a later one entirely.
const codexHighWater = new Map();
/** Test-only: forget every claim so suites start from a clean ledger. */
@@ -99,8 +100,15 @@ const CODEX_ID = /codex/i;
* "Agree" is tested by resolving both through the rate table — that treats
* `global.anthropic.claude-opus-5[1m]` and `claude-opus-5` as the same model
* (both resolve to `claude-opus-5`) while catching a genuine substitution.
- * A bucket with no model name at all resolves to null so the caller prices it
- * at the provider default.
+ * A model-less bucket (`UNKNOWN_MODEL`) resolves to null so the caller prices it
+ * at the provider default — EXCEPT when it is the run's only bucket, where the
+ * recorded model is used instead. That case is a deliberate choice, not an
+ * oversight: with one bucket and no name in the transcript, PortOS's launch-time
+ * model is real evidence of what ran, while the provider default is a guess that
+ * is often a different model entirely (a Bedrock Opus run defaults to Sonnet
+ * rates — $3/$15 instead of $5/$25, understating the very cost this feature
+ * exists to measure). With SEVERAL buckets the unnamed one can't be pinned to
+ * the recorded model (some other bucket already holds it), so it stays null.
*/
function attributedModel(recordedModel, transcriptModel, singleModel) {
const fromTranscript = transcriptModel === UNKNOWN_MODEL ? null : transcriptModel;
@@ -110,8 +118,13 @@ function attributedModel(recordedModel, transcriptModel, singleModel) {
// A local model can never be an alias of a hosted one — always trust the
// transcript there, or free inference gets billed at the launch model's rate.
if (isFreeModelId(fromTranscript) !== isFreeModelId(recordedModel)) return fromTranscript;
- const sameFamily = resolveModelRates(null, recordedModel).rateModel
- === resolveModelRates(null, fromTranscript).rateModel;
+ const recordedRate = resolveModelRates(null, recordedModel).rateModel;
+ const transcriptRate = resolveModelRates(null, fromTranscript).rateModel;
+ // A null rateModel means "nothing in the table recognized this id", and two
+ // unrecognized ids are NOT thereby the same model — treating null === null as
+ // agreement would keep the launch-time id for a genuine substitution between
+ // two unknown models. Require a resolved family to claim they match.
+ const sameFamily = recordedRate != null && recordedRate === transcriptRate;
return sameFamily ? recordedModel : fromTranscript;
}
@@ -295,25 +308,51 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
// baseline before both runs) re-includes what the first run already
// billed. Track the highest cumulative boundary billed per file and
// re-parse from there, so each run charges only the genuinely new part.
- const billedTo = codexHighWater.get(path);
- // Start strictly AFTER the billed boundary: the window is inclusive, so
- // passing `billedTo` itself would make the already-billed snapshot the
- // window's end state instead of its baseline, and its whole cumulative
- // total would be charged again.
- const windowFrom = billedTo != null ? Math.max(from ?? 0, billedTo + 1) : from;
// Rollouts are filed by date, not cwd — confirm the cwd before folding.
- const parsed = parseCodexRollout(text, { from: windowFrom, to });
+ const parsed = parseCodexRollout(text, { from, to });
if (!cwdMatches(parsed.cwd, workspacePath)) continue;
- if (totalTranscriptTokens(parsed) === 0) continue;
- const boundary = Date.parse(parsed.lastTs || '');
- if (Number.isNaN(boundary)) continue;
- if (billedTo != null && boundary <= billedTo) continue;
- // Advance the high-water mark before the next `await`, for the same
- // reason the Claude claim reserves per file: two overlapping runs must
- // not both read the pre-update boundary.
- codexHighWater.set(path, boundary);
- codexReserved.push([path, billedTo]);
- fold(parsed);
+
+ // Subtract whatever was already billed for this rollout. The high-water
+ // mark is the CUMULATIVE TOTAL charged so far, not a timestamp: several
+ // `token_count` snapshots can share one epoch millisecond, so a
+ // timestamp boundary would either re-bill them or (excluding the whole
+ // millisecond) silently drop a later snapshot's tokens. Subtracting
+ // totals is exact regardless of how the snapshots are stamped.
+ const billed = codexHighWater.get(path);
+ const net = billed
+ ? {
+ ...parsed,
+ messages: Math.max(0, (parsed.messages || 0) - billed.messages),
+ tokensIn: Math.max(0, parsed.tokensIn - billed.tokensIn),
+ tokensOut: Math.max(0, parsed.tokensOut - billed.tokensOut),
+ cacheReadTokens: Math.max(0, parsed.cacheReadTokens - billed.cacheReadTokens),
+ cacheWriteTokens: Math.max(0, parsed.cacheWriteTokens - billed.cacheWriteTokens)
+ }
+ : parsed;
+ if (totalTranscriptTokens(net) === 0) continue;
+
+ // Advance the mark before the next `await`, for the same reason the
+ // Claude claim reserves per file: two overlapping runs must not both
+ // read the pre-update value.
+ codexHighWater.set(path, {
+ messages: (billed?.messages || 0) + (net.messages || 0),
+ tokensIn: (billed?.tokensIn || 0) + net.tokensIn,
+ tokensOut: (billed?.tokensOut || 0) + net.tokensOut,
+ cacheReadTokens: (billed?.cacheReadTokens || 0) + net.cacheReadTokens,
+ cacheWriteTokens: (billed?.cacheWriteTokens || 0) + net.cacheWriteTokens
+ });
+ codexReserved.push([path, billed]);
+ // `byModel` must carry the NET tokens too, or the per-model records the
+ // caller bills from would re-charge the already-billed portion.
+ fold(net.byModel && Object.keys(net.byModel).length === 1
+ ? { ...net, byModel: { [Object.keys(net.byModel)[0]]: {
+ messages: net.messages,
+ tokensIn: net.tokensIn,
+ tokensOut: net.tokensOut,
+ cacheReadTokens: net.cacheReadTokens,
+ cacheWriteTokens: net.cacheWriteTokens
+ } } }
+ : net);
}
}
}
diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.js
index ce71388dac..807a526a0f 100644
--- a/server/services/usageReconciler.test.js
+++ b/server/services/usageReconciler.test.js
@@ -580,3 +580,126 @@ describe('model attribution when the transcript disagrees', () => {
expect(record.tokensOut).toBe(50);
});
});
+
+describe('Codex high-water mark tracks totals, not timestamps', () => {
+ const runA = {
+ providerId: 'codex-tui', model: 'gpt-5.3-codex', workspacePath: WORKSPACE,
+ startTime: '2026-07-01T10:00:00.000Z', endTime: '2026-07-01T10:10:00.000Z'
+ };
+ const runB = { ...runA, startTime: '2026-07-01T10:02:00.000Z', endTime: '2026-07-01T10:12:00.000Z' };
+
+ const rollout = (snaps) => [
+ JSON.stringify({ timestamp: '2026-07-01T10:00:00.000Z', type: 'session_meta', payload: { id: 'rollout-1', cwd: WORKSPACE, model: 'gpt-5.3-codex' } }),
+ ...snaps.map(([timestamp, input, cached, output]) => JSON.stringify({
+ timestamp, type: 'event_msg',
+ payload: { type: 'token_count', info: { total_token_usage: { input_tokens: input, cached_input_tokens: cached, output_tokens: output, total_tokens: input + output } } }
+ }))
+ ].join('\n');
+
+ // Regression: a timestamp-based boundary either re-billed snapshots sharing a
+ // millisecond or, when excluding the whole millisecond, dropped the later
+ // one's tokens outright. Totals are exact regardless of stamping.
+ it('does not lose a delta when two snapshots share an epoch millisecond', async () => {
+ const SAME_MS = '2026-07-01T10:05:00.000Z';
+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', rollout([[SAME_MS, 1000, 0, 100]]));
+ const first = await readMeasuredUsage({ ...runA, family: 'codex', home });
+ expect(first.tokensOut).toBe(100);
+
+ // The rollout grows, and the new snapshot carries the SAME timestamp.
+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', rollout([
+ [SAME_MS, 1000, 0, 100],
+ [SAME_MS, 3000, 0, 250]
+ ]));
+ const second = await readMeasuredUsage({ ...runB, family: 'codex', home });
+
+ // The additional 150 must still be billed — not dropped, not doubled.
+ expect(second?.tokensOut).toBe(150);
+ expect(first.tokensOut + second.tokensOut).toBe(250);
+ });
+
+ it('reports nothing when an unchanged rollout is re-read', async () => {
+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', rollout([
+ ['2026-07-01T10:05:00.000Z', 1000, 0, 100]
+ ]));
+ const first = await readMeasuredUsage({ ...runA, family: 'codex', home });
+ expect(first.tokensOut).toBe(100);
+ expect(await readMeasuredUsage({ ...runB, family: 'codex', home })).toBeNull();
+ });
+
+ it('nets the per-model bucket too, so records never re-charge the billed part', async () => {
+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', rollout([
+ ['2026-07-01T10:05:00.000Z', 1000, 0, 100]
+ ]));
+ await readMeasuredUsage({ ...runA, family: 'codex', home });
+
+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', rollout([
+ ['2026-07-01T10:05:00.000Z', 1000, 0, 100],
+ ['2026-07-01T10:11:00.000Z', 3000, 0, 250]
+ ]));
+ const second = await readMeasuredUsage({ ...runB, family: 'codex', home });
+ // The model bucket must equal the NET, matching the aggregate.
+ expect(second.byModel['gpt-5.3-codex'].tokensOut).toBe(second.tokensOut);
+ expect(second.byModel['gpt-5.3-codex'].tokensOut).toBe(150);
+ });
+});
+
+describe('attributedModel with unrecognized ids', () => {
+ const run = {
+ providerId: 'claude-code-tui', workspacePath: WORKSPACE,
+ startTime: '2026-07-01T10:00:00.000Z', endTime: '2026-07-01T10:10:00.000Z'
+ };
+
+ // Two unknown ids both resolve to rateModel null. Treating null === null as
+ // "same family" kept the launch id for a real substitution.
+ it('defers to the transcript when neither id resolves to a known family', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z', model: 'totally-other-beta' })
+ ]);
+ const [record] = await reconcileRunUsage(
+ { ...run, model: 'some-preview-alpha' }, { tokensIn: 1, tokensOut: 1 }, { home }
+ );
+ expect(record.model).toBe('totally-other-beta');
+ });
+});
+
+describe('model-less bucket attribution (deliberate single-bucket choice)', () => {
+ const run = {
+ providerId: 'claude-code-tui-bedrock',
+ model: 'global.anthropic.claude-opus-5[1m]',
+ workspacePath: WORKSPACE,
+ startTime: '2026-07-01T10:00:00.000Z',
+ endTime: '2026-07-01T10:10:00.000Z'
+ };
+ const unnamed = (id, timestamp, output) => {
+ const line = JSON.parse(claudeAssistant({ id, timestamp, output, cacheRead: 0, cacheWrite: 0, input: 1 }));
+ delete line.message.model;
+ return JSON.stringify(line);
+ };
+
+ // With SEVERAL buckets the unnamed one can't be pinned to the recorded model
+ // (a named bucket already holds it), so it prices at the provider default.
+ it('leaves the unnamed bucket unattributed when another bucket is named', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'named', timestamp: '2026-07-01T10:05:00.000Z', model: 'claude-opus-5', output: 100, cacheRead: 0, cacheWrite: 0, input: 1 }),
+ unnamed('anon', '2026-07-01T10:06:00.000Z', 500)
+ ]);
+
+ const records = await reconcileRunUsage(run, { tokensIn: 1, tokensOut: 1 }, { home });
+ const models = records.map((r) => r.model);
+ expect(models).toContain('claude-opus-5');
+ expect(models).toContain(null);
+ // Critically: nothing is dropped — the unnamed message's tokens are recorded.
+ expect(records.reduce((s, r) => s + r.tokensOut, 0)).toBe(600);
+ });
+
+ // With ONE bucket, PortOS's launch-time model is better evidence than the
+ // provider default (which for a Bedrock Opus run is Sonnet — $3/$15 vs $5/$25,
+ // understating the cost this feature exists to measure).
+ it('uses the recorded model when the unnamed bucket is the only one', async () => {
+ await writeClaudeSession('a.jsonl', [unnamed('anon', '2026-07-01T10:05:00.000Z', 500)]);
+ const records = await reconcileRunUsage(run, { tokensIn: 1, tokensOut: 1 }, { home });
+ expect(records).toHaveLength(1);
+ expect(records[0].model).toBe('global.anthropic.claude-opus-5[1m]');
+ expect(records[0].tokensOut).toBe(500);
+ });
+});