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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (self): share the usage-claim ledger across the backfill worker thread
[._.]/ Adam Eivyd6b2ff42745e
diff --git a/server/services/usageBackfill.js b/server/services/usageBackfill.jsindex 26a504255a..2219086e28 100644--- a/server/services/usageBackfill.js+++ b/server/services/usageBackfill.js@@ -5,6 +5,7 @@ import {applyHistoricalUsageCorrections,getReconciledUsageRunIds} from './usage.js';+import { mergeUsageClaims, snapshotUsageClaims } from './usageReconciler.js';let job = {status: 'idle',@@ -59,7 +60,12 @@ export function startHistoricalUsageBackfill({workerData: {runsDir,home,- reconciledRunIds: getReconciledUsageRunIds()+ reconciledRunIds: getReconciledUsageRunIds(),+ // The worker gets its own empty copy of usageReconciler.js's claim+ // ledger (a separate module instance) — seed it from this thread's+ // ledger so a message the live completion path already billed isn't+ // billed again by the backfill scan.+ claimsSeed: snapshotUsageClaims()}});@@ -76,6 +82,7 @@ export function startHistoricalUsageBackfill({}if (message?.type !== 'complete') return;const result = message.result || {};+ if (result.claimsSnapshot) mergeUsageClaims(result.claimsSnapshot);const applied = await applyHistoricalUsageCorrections(result.corrections || []);const appliedCorrections = (result.corrections || []).filter((correction) => applied.correctedRunIds.includes(correction.runId));diff --git a/server/services/usageBackfillWorker.js b/server/services/usageBackfillWorker.jsindex b17dd43b25..9cf0ff3ffb 100644--- a/server/services/usageBackfillWorker.js+++ b/server/services/usageBackfillWorker.js@@ -3,7 +3,7 @@ import { join } from 'path';import { readdir } from 'fs/promises';import { estimateTokens, estimateTokensFromChars } from '../lib/contextBudget.js';import { readJSONFile, tryReadFile } from '../lib/fileUtils.js';-import { reconcileRunUsage, transcriptFamily } from './usageReconciler.js';+import { mergeUsageClaims, reconcileRunUsage, snapshotUsageClaims, transcriptFamily } from './usageReconciler.js';const listRunIds = async (runsDir) => readdir(runsDir, { withFileTypes: true }).then((entries) => entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name))@@ -21,8 +21,16 @@ export async function scanHistoricalUsage({runsDir,home,reconciledRunIds = [],+ claimsSeed = null,onProgress = () => {}}) {+ // This function runs inside a worker thread, which gets its own empty copy+ // of usageReconciler.js's module-level claim ledger — seed it from the main+ // thread's ledger so a message the live completion path already billed is+ // not billed again here. The caller merges this scan's final ledger state+ // back into the main thread's ledger once this resolves (see `home`'s+ // sibling `claimsSnapshot` in the return value).+ if (claimsSeed) mergeUsageClaims(claimsSeed);const reconciled = new Set(reconciledRunIds);const candidates = [];@@ -66,7 +74,7 @@ export async function scanHistoricalUsage({onProgress({ processed, total: candidates.length, found: corrections.length });}- return { corrections, processed, total: candidates.length };+ return { corrections, processed, total: candidates.length, claimsSnapshot: snapshotUsageClaims() };}if (!isMainThread) {diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.jsindex c2d95932a4..d2f7f12229 100644--- a/server/services/usageReconciler.js+++ b/server/services/usageReconciler.js@@ -56,9 +56,12 @@ const WINDOW_SLACK_MS = 60_000;// A transcript message must be counted exactly ONCE across every run that can// see it: without this, two concurrent runs in the same cwd (or one run whose// window overlaps a neighbour's through WINDOW_SLACK_MS) each fold the same-// tokens and the cost report doubles. Process-local by design — it guards the-// live completion path, which is the only writer; a restart loses the ledger,-// but a run that already completed is never reconciled again.+// tokens and the cost report doubles. Module-instance-local by design — the+// live completion path (this module, in the main thread) and the historical+// backfill worker (a SEPARATE module instance in a worker thread) each get+// their own copy of this Set, so `snapshotUsageClaims`/`mergeUsageClaims`+// hand claims across that boundary; see `usageBackfill.js`. A restart loses+// the ledger, but a run that already completed is never reconciled again.const claimedMessages = new Set();// The ABSOLUTE cumulative position of each Codex rollout that has already been@@ -76,6 +79,37 @@ export function __resetUsageClaims() {codexHighWater.clear();}+/**+ * Snapshot the current ledger so it can be handed to a worker thread — which+ * gets its own empty copy of this module's state — and merged back once the+ * worker finishes. Without this, the historical-usage backfill worker+ * (`usageBackfillWorker.js`) and the live completion path (this module, run+ * in the main thread) never see each other's claims, so a transcript message+ * whose window overlaps a live run and a backfilled historical run could be+ * billed by both.+ */+export function snapshotUsageClaims() {+ return {+ claimedMessages: [...claimedMessages],+ codexHighWater: [...codexHighWater.entries()]+ };+}++/** Merge claims made elsewhere (a worker thread's ledger) into this one. */+export function mergeUsageClaims({ claimedMessages: claimed = [], codexHighWater: highWater = [] } = {}) {+ for (const key of claimed) claimedMessages.add(key);+ for (const [path, value] of highWater) {+ const existing = codexHighWater.get(path);+ codexHighWater.set(path, existing ? {+ messages: Math.max(existing.messages || 0, value.messages || 0),+ tokensIn: Math.max(existing.tokensIn || 0, value.tokensIn || 0),+ tokensOut: Math.max(existing.tokensOut || 0, value.tokensOut || 0),+ cacheReadTokens: Math.max(existing.cacheReadTokens || 0, value.cacheReadTokens || 0),+ cacheWriteTokens: Math.max(existing.cacheWriteTokens || 0, value.cacheWriteTokens || 0)+ } : value);+ }+}+// A run is attributed only to transcripts whose cwd matches. A CoS agent works// in a git worktree under the install's data dir, so the worktree path — not the// install root — is what the CLI records; matching is therefore exact on the