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): serialize quota-burn ledger increments

[._.]/ Adam Eivy1ffb3af1acc8
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
index 090d0d157b..d84f72de51 100644
--- a/server/services/quotaBurn.js
+++ b/server/services/quotaBurn.js
@@ -1,6 +1,7 @@
import { getProviderQuotas } from './providerUsage.js';
import { join } from 'path';
import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { hoursUntilReset, normalizeResetAt } from '../lib/quotaReset.js';
export const QUOTA_BURN_TASK_TYPE = 'quota-burn';
@@ -27,11 +28,23 @@ export async function getQuotaBurnDispatches() {
return loaded && typeof loaded === 'object' ? loaded : {};
}
+// Single-tail queue for the dispatch ledger's read-modify-write. Two quota-burn
+// agents (one per app) can finalize concurrently, and each finalization records a
+// dispatch — unserialized, both would read the same count and write the same
+// increment, losing one burn. An undercounted ledger then lets the window
+// dispatch past `maxDispatchesPerWindow`, which is real quota overspend. This is
+// the "serialize two write paths that mutate the same record" case, not a
+// defense against competing users. It only became reachable when the write moved
+// from generation (sequential, one app at a time) to finalize (#3179).
+const ledgerWriteQueue = createFileWriteQueue();
+
export async function recordQuotaBurnDispatch(key) {
- const ledger = await getQuotaBurnDispatches();
- const next = { ...ledger, [key]: Number(ledger[key] || 0) + 1 };
- await atomicWrite(LEDGER_FILE, next);
- return next;
+ return ledgerWriteQueue(async () => {
+ const ledger = await getQuotaBurnDispatches();
+ const next = { ...ledger, [key]: Number(ledger[key] || 0) + 1 };
+ await atomicWrite(LEDGER_FILE, next);
+ return next;
+ });
}
/**
diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.js
index 3cf7d917d7..8d7623b3e2 100644
--- a/server/services/quotaBurn.test.js
+++ b/server/services/quotaBurn.test.js
@@ -118,3 +118,37 @@ describe('getEffectiveQuotaBurnDispatches', () => {
await expect(getEffectiveQuotaBurnDispatches({ ignoreTaskId: 'sys-finishing' })).resolves.toEqual({ 'grok:1': 1 });
});
});
+
+/**
+ * Two quota-burn agents (one per app) can finalize concurrently, and each
+ * finalization records a dispatch. The ledger update is a read-modify-write, so
+ * without serialization both would read the same count and write the same
+ * increment — losing a burn and letting the window overspend its cap.
+ */
+describe('recordQuotaBurnDispatch serialization', () => {
+ afterEach(() => { vi.doUnmock('../lib/fileUtils.js'); vi.resetModules(); });
+
+ it('does not lose an increment when two completions race', async () => {
+ vi.resetModules();
+ let stored = {};
+ vi.doMock('../lib/fileUtils.js', async (importActual) => ({
+ ...(await importActual()),
+ readJSONFile: async () => ({ ...stored }),
+ // The delay must sit on the WRITE: it holds each read-modify-write open
+ // long enough for the next caller's read to observe the pre-write state.
+ // (A delay on the read instead resolves in a macrotask whose continuation
+ // runs the whole RMW in microtasks, so the cycles never actually overlap
+ // and the test would pass even unserialized.)
+ atomicWrite: async (_file, data) => { await new Promise((r) => setTimeout(r, 5)); stored = { ...data }; },
+ }));
+ const { recordQuotaBurnDispatch, getQuotaBurnDispatches } = await import('./quotaBurn.js');
+
+ await Promise.all([
+ recordQuotaBurnDispatch('grok:1'),
+ recordQuotaBurnDispatch('grok:1'),
+ recordQuotaBurnDispatch('codex:2'),
+ ]);
+
+ await expect(getQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 2, 'codex:2': 1 });
+ });
+});