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

fix: charge the quota-burn cap and run-once ledger only when a burn is accepted (#6379)

[._.]/ Adam Eivy7eae35abb873
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
index 0ce6ba7628..7c1a5af2c2 100644
--- a/docs/QUOTA-BURN.md
+++ b/docs/QUOTA-BURN.md
@@ -23,8 +23,19 @@ Every `checkIntervalMinutes` (default 30, bounded 5–720) the runner:
plan that reports pending work** — at most one dispatch per cycle. The step
is dispatched through the referenced task's own invocation path, so the run
is indistinguishable from the same task started by hand.
-5. Charges the window in `data/cos/quota-burn-dispatches.json` and appends the
- outcome (including skips, with reasons) to `data/cos/quota-burn-runs.json`.
+5. Accounts for it **when the work is accepted, not when it is asked for**, and
+ appends the outcome (including skips, with reasons) to
+ `data/cos/quota-burn-runs.json`. The two synchronous lanes — a programmatic
+ handler, which runs inline, and a custom app job, which `addTask` queues in
+ the same call — are accepted on return and charge
+ `data/cos/quota-burn-dispatches.json` immediately. A built-in task goes out as
+ an on-demand REQUEST an engine may still refuse, so it takes a reservation in
+ `data/cos/quota-burn-pending.json` instead: the reservation counts against
+ `maxDispatchesPerWindow` and blocks a second burn of the same step, and the
+ next cycle joins the request to the task it produced (by the
+ `quotaBurnRequestId` stamped on that task) to charge it exactly once — or
+ releases it uncharged if nothing was generated. See "Charging exactly once"
+ below.
Everything fails closed: an unknown reset time, an unsupported provider, a
quota-read error, a card that declares itself unburnable (`burnable: false`, e.g.
@@ -423,6 +434,63 @@ Every numeric bound (windows, reserve, caps, field lengths) lives in
(which clamps an older on-disk plan) and by the Zod schemas (which reject a bad
request), so raising a cap in one place cannot 400 a plan the other would accept.
+## Charging exactly once
+
+A burn's accounting hangs off **acceptance**, never off "we asked". The
+distinction only exists because one of the three invocation lanes is
+asynchronous:
+
+| Lane | Accepted when | Accounting |
+| --- | --- | --- |
+| Programmatic handler | it returns — PortOS did the work inline | charged immediately |
+| Custom app job | `addTask` returns a persisted, non-duplicate task | charged immediately |
+| Built-in scheduled task | an on-demand engine generates the task, later | **reserved**, then settled |
+
+A built-in step goes out as an on-demand request. One of the two engines
+(`cos.js#spawnDequeuePriority0OnDemand`, `cosTaskGenerator.js#spawnPriority0OnDemand`)
+drains it on a later cycle and may refuse it outright — improvement switched off,
+the task type disabled since queuing, a managed app that has gone away, a
+generator that produced nothing, an identical twin already queued. Charging at
+the request would spend the window (and retire a `runOnce` step) for work that
+never started: the same undercount #3179 fixed one hop further down.
+
+So the runner takes a **reservation** in `data/cos/quota-burn-pending.json`
+instead, keyed `<familyId>::<stepId>`, carrying the terms the dispatch was made
+under (which window to charge, whether it charges at all, whether the step is
+`runOnce`) and the request id. While it is held:
+
+- it counts against `maxDispatchesPerWindow` exactly as a charge would, so the
+ cap is honest for the whole in-flight window and the page's `N/M used` does not
+ under-report;
+- the step is skipped by any later cycle, so a duplicate scheduled or burn
+ invocation cannot queue the same work twice.
+
+Every cycle then settles what the last one asked for (`quotaBurnAcceptance.js`),
+before deciding what to ask for next. A reservation whose request is still on the
+schedule is left alone. One whose request has drained is **joined to the task the
+engine produced**, by the `quotaBurnRequestId` that request stamped onto it
+(`lib/quotaBurnOrigin.js`):
+
+- **a task exists** → charge the window once, mark a `runOnce` step spent, patch
+ the run-log row in place with the accepted task id, release the reservation;
+- **no task exists** → release the reservation, charge nothing, and say so on the
+ run-log row.
+
+Because the join runs off persisted state — the reservation, the request and the
+task are all on disk — a restart mid-flight reaches the same verdict a reconcile
+a second later would have. The charge is claimed on the reservation *before* the
+ledger write it authorizes, so a process killed between the two cannot charge
+twice on the next pass. And an ordinary clock-driven run of the very same
+scheduled task changes nothing here: it carries no burn provenance, so no
+reservation ever names it, and neither the cap nor the step's one-shot state
+moves.
+
+Reads fail closed. An unreadable reservation file skips the cycle (reading it as
+"nothing pending" would re-queue a step already in flight and re-open its cap
+slot), and an unreadable schedule or task queue defers every reservation rather
+than calling a running burn refused. The status page reads reservations but never
+settles one — a probe read performs no ledger write.
+
## Manual runs
- **Evaluate now** runs a full cycle immediately, ignoring the master switch but
@@ -442,7 +510,7 @@ request), so raising a cap in one place cannot 400 a plan the other would accept
## Storage
-Six files under `data/cos/`, all machine-local and intentionally **not federated**: the plan (`quota-burn.json` — ordered steps, each a scheduled-task reference plus its overrides; the referenced tasks themselves live in `data/cos/task-schedule.json` and the app job store, and a burn never writes to either), the per-window dispatch ledger (`quota-burn-dispatches.json`), the run log (`quota-burn-runs.json`), the in-flight set (`quota-burn-inflight.json` — entries a job enqueued whose renders have not landed yet, so the next cycle does not re-queue them; 6-hour TTL), the denial ledger (`quota-burn-denials.json` — per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL), and the `run once` completion ledger (`quota-burn-completions.json` — which one-shot steps have had their dispatch, cleared by Re-arm). They are not federated: quota belongs to a
+Seven files under `data/cos/`, all machine-local and intentionally **not federated**: the plan (`quota-burn.json` — ordered steps, each a scheduled-task reference plus its overrides; the referenced tasks themselves live in `data/cos/task-schedule.json` and the app job store, and a burn never writes to either), the per-window dispatch ledger (`quota-burn-dispatches.json`), the run log (`quota-burn-runs.json`), the in-flight set (`quota-burn-inflight.json` — entries a job enqueued whose renders have not landed yet, so the next cycle does not re-queue them; 6-hour TTL), the denial ledger (`quota-burn-denials.json` — per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL), the `run once` completion ledger (`quota-burn-completions.json` — which one-shot steps have had their dispatch, cleared by Re-arm), and the pending-acceptance reservations (`quota-burn-pending.json` — `<familyId>::<stepId>` → the request a burn is waiting on, released when it is accepted or refused; 6-hour TTL). None of them ships a `data.reference/` seed, because an absent file already means "nothing recorded". They are not federated: quota belongs to a
particular machine and provider account, and the "which managed app" targets
differ per machine.
@@ -481,7 +549,8 @@ inference.
| `server/lib/universeBibleCompleteness.js` | What "described" means per kind + depth — the field vocabulary the describe task scans with |
| `server/lib/quotaWindows.js` | Classifies a window by period — target (broadest) vs limiting (narrowest) |
| `server/services/quotaBurnInvoke.js` | The shared invocation path: builds the task catalog, resolves a step, layers its overrides, enforces the schedule's own gates, and dispatches |
-| `server/services/quotaBurnStore.js` | `data/cos/quota-burn.json` + the run log |
+| `server/services/quotaBurnAcceptance.js` | Reservations for an asynchronous acceptance, and the settlement that charges each accepted burn exactly once |
+| `server/services/quotaBurnStore.js` | `data/cos/quota-burn.json`, the run log, and the pending-acceptance reservations |
| `server/services/quotaBurn.js` | `evaluateFamily` — the one gate ladder both selection and the page's skip reasons read — plus the dispatch ledger |
| `server/services/quotaBurnCompletions.js` | The `run once` completion ledger and its re-arm |
| `server/services/quotaBurnDenials.js` | The observed-refusal ledger and its `agent:completed` subscriber |
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
index 7ebb24d090..2c06929d84 100644
--- a/server/services/quotaBurn.js
+++ b/server/services/quotaBurn.js
@@ -85,6 +85,32 @@ export async function recordQuotaBurnDispatch(key, { now = Date.now() } = {}) {
});
}
+/**
+ * The ledger the gate ladder should actually read: what this window has been
+ * CHARGED, plus every burn that has been requested and not yet accepted.
+ *
+ * A reference burn's acceptance is asynchronous (`quotaBurnAcceptance.js`), so
+ * without this the cap would read one short for the whole in-flight window —
+ * long enough for the next cycle, or the completion continuation, to walk past
+ * `maxDispatchesPerWindow` and spend quota the plan had already committed. A
+ * reservation whose charge has been CLAIMED (`chargedAt`) is skipped: the ledger
+ * write it authorized already counts it, and counting both is the double
+ * accounting the reservation exists to prevent.
+ *
+ * Pure, and non-destructive: `reservations` of `null` (unreadable) returns the
+ * ledger untouched, and it is the caller that decides whether an unreadable
+ * reservation file may run a cycle at all.
+ */
+export function withPendingDispatches(ledger, reservations) {
+ if (!isPlainObject(reservations)) return ledger;
+ const next = { ...ledger };
+ for (const record of Object.values(reservations)) {
+ if (!record?.charge || !record.dispatchKey || record.chargedAt) continue;
+ next[record.dispatchKey] = Number(next[record.dispatchKey] || 0) + 1;
+ }
+ return next;
+}
+
/**
* The verdict for a plan whose every enabled step is a spent `run once`.
*
diff --git a/server/services/quotaBurnAcceptance.js b/server/services/quotaBurnAcceptance.js
new file mode 100644
index 0000000000..219383dd73
--- /dev/null
+++ b/server/services/quotaBurnAcceptance.js
@@ -0,0 +1,200 @@
+/**
+ * Exactly-once accounting for a burn whose acceptance is ASYNCHRONOUS.
+ *
+ * A reference burn no longer queues its own task: it asks the schedule to run a
+ * task the user already owns (`quotaBurnInvoke.js` →
+ * `taskSchedule.triggerOnDemandTask`). The request lands on the schedule now and
+ * one of the two on-demand engines (`cos.js#spawnDequeuePriority0OnDemand`,
+ * `cosTaskGenerator.js#spawnPriority0OnDemand`) generates the task later — or
+ * refuses it: improvement switched off, the task type disabled since queuing, an
+ * app that has gone away, a generator that produced nothing, an identical twin
+ * already queued. So "we recorded a request" is NOT "work started", and charging
+ * the window cap and the `runOnce` ledger at the request is the same
+ * undercount-then-overspend bug #3179 fixed in the dispatch ledger.
+ *
+ * The fix is a RESERVATION, settled against the outcome:
+ *
+ * 1. `reserveQuotaBurnDispatch` — the request goes out and the step's place is
+ * held in `data/cos/quota-burn-pending.json`. Nothing is charged yet, but
+ * the reservation counts against `maxDispatchesPerWindow` exactly like a
+ * charge would (`pendingDispatchCounts` in `quotaBurn.js`), so the cap is
+ * honest for the whole in-flight window, and it blocks a second cycle from
+ * queuing the same step.
+ * 2. `reconcileQuotaBurnReservations` — every cycle, each reservation whose
+ * request has left the queue is JOINED to the task the engine produced, by
+ * the `quotaBurnRequestId` the request stamps onto it
+ * (`lib/quotaBurnOrigin.js`). A task means accepted: charge once, mark a
+ * `runOnce` step spent, and settle the run-log row with the task id. No
+ * task means refused: release the reservation, charge nothing.
+ *
+ * The join is what makes this survive a restart — the reservation, the request
+ * and the task are all on disk, so a reconcile after a crash reaches the same
+ * verdict a reconcile a second later would have. It is also why an ordinary
+ * clock-driven run of the very same scheduled task changes nothing here: it
+ * carries no burn provenance, so no reservation ever names it.
+ *
+ * Everything fails CLOSED. An unreadable reservation file, an unreadable
+ * schedule, or an unreadable task queue all DEFER — releasing a reservation we
+ * cannot judge would either re-open the cap for work that is running or spend a
+ * charge on work that never started.
+ *
+ * The synchronous lanes do not come through here at all: a programmatic handler
+ * runs inline and a custom job is queued by `addTask` in the same call, so both
+ * are accepted the moment they return and the runner charges them directly.
+ */
+
+import { quotaBurnProvenance } from '../lib/quotaBurnOrigin.js';
+import { recordQuotaBurnDispatch } from './quotaBurn.js';
+import { recordQuotaBurnJobCompletion } from './quotaBurnCompletions.js';
+import {
+ getQuotaBurnReservations,
+ markQuotaBurnReservationCharged,
+ quotaBurnReservationKey,
+ releaseQuotaBurnStep,
+ reserveQuotaBurnStep,
+ settleQuotaBurnRun,
+} from './quotaBurnStore.js';
+
+/**
+ * Hold a step's place while its on-demand request waits to be accepted.
+ *
+ * `charge` and `runOnce` are captured HERE, from the candidate and the step the
+ * cycle actually picked, rather than re-derived at settlement: the plan can be
+ * edited (or the family forced) between the request and the drain, and a burn
+ * must settle on the terms it was dispatched under. Returns false when the
+ * reservation could not be taken — an unreadable file, or a step already
+ * reserved — which the caller reports rather than treating as a silent success.
+ */
+export async function reserveQuotaBurnDispatch({ familyId, stepId, dispatchKey, charge, runOnce, requestId }, { now = Date.now() } = {}) {
+ if (!familyId || !stepId || !requestId) return false;
+ const written = await reserveQuotaBurnStep({
+ familyId, stepId, dispatchKey: dispatchKey || null, charge: Boolean(charge), runOnce: Boolean(runOnce), requestId,
+ }, { now });
+ return Boolean(written);
+}
+
+/** The request ids still waiting on the schedule, or null when it can't be read. */
+async function queuedRequestIds() {
+ const { getOnDemandRequests } = await import('./taskSchedule.js');
+ return getOnDemandRequests()
+ .then((requests) => new Set((requests || []).map((request) => request?.id).filter(Boolean)))
+ .catch((err) => {
+ console.error(`❌ Quota-burn could not read the on-demand request queue: ${err.message}`);
+ return null;
+ });
+}
+
+/**
+ * Every task carrying burn provenance, keyed by the request that produced it.
+ *
+ * Read through `quotaBurnProvenance` rather than `metadata.quotaBurnRequestId`
+ * directly: a task round-trips through COS-TASKS.md, which hands every scalar
+ * back as a string, and that reader is the one place that coercion lives.
+ */
+async function burnTasksByRequestId() {
+ const { getAllTasks } = await import('./cosTaskStore.js');
+ return getAllTasks()
+ .then(({ user, cos }) => {
+ const byRequest = new Map();
+ for (const task of [...(cos?.tasks || []), ...(user?.tasks || [])]) {
+ const { requestId } = quotaBurnProvenance(task?.metadata);
+ if (requestId && !byRequest.has(requestId)) byRequest.set(requestId, task);
+ }
+ return byRequest;
+ })
+ .catch((err) => {
+ console.error(`❌ Quota-burn could not read the task queue to settle its reservations: ${err.message}`);
+ return null;
+ });
+}
+
+/**
+ * Charge one accepted burn, then let its reservation go.
+ *
+ * The claim/charge/release order is what keeps this exactly-once across a crash
+ * — see `markQuotaBurnReservationCharged`. A ledger that cannot be written keeps
+ * the reservation (and un-claims the charge), so the next cycle retries instead
+ * of releasing a burn the window was never debited for. The `runOnce` write is
+ * idempotent on its key, so a retry re-stamps rather than double-counting.
+ */
+async function settleAccepted(key, record, task, now) {
+ if (record.charge && !record.chargedAt) {
+ await markQuotaBurnReservationCharged(key, now, { now });
+ const ledger = await recordQuotaBurnDispatch(record.dispatchKey, { now });
+ if (!ledger) {
+ await markQuotaBurnReservationCharged(key, null, { now });
+ console.error(`⚠️ Quota-burn could not charge ${record.familyId}/${record.stepId} — retrying next cycle`);
+ return false;
+ }
+ }
+ if (record.runOnce) {
+ await recordQuotaBurnJobCompletion(record.familyId, record.stepId, { now })
+ // A ledger failure must not fail an acceptance that already happened — the
+ // worst case is the step running one extra time, the pre-`runOnce` behavior.
+ .catch((err) => console.error(`⚠️ Quota-burn run-once ledger for ${record.familyId}/${record.stepId}: ${err.message}`));
+ }
+ await settleQuotaBurnRun(record.requestId, {
+ pending: false, accepted: true, taskId: task.id, charged: Boolean(record.charge),
+ });
+ await releaseQuotaBurnStep(key, { now });
+ console.log(`🔥 Quota-burn ${record.familyId}/${record.stepId} accepted as task ${task.id}`);
+ return true;
+}
+
+/**
+ * Let a refused burn's reservation go, charging nothing.
+ *
+ * The row keeps `dispatched: true` — the burn WAS dispatched, and that flag is
+ * also the rotation cursor `lastDispatchedJobByFamily` reads. Clearing it would
+ * rewind the walk onto the step that just failed and re-request it every cycle,
+ * which is the perpetual loop this whole change is meant to rule out. The
+ * `summary` carries the outcome instead, so the page's "Recent runs" line stops
+ * claiming work that never started.
+ */
+async function settleRefused(key, record, reason, now) {
+ await settleQuotaBurnRun(record.requestId, {
+ pending: false, accepted: false, settledReason: reason, summary: `Requested, but not accepted — ${reason}`,
+ });
+ await releaseQuotaBurnStep(key, { now });
+ console.log(`💤 Quota-burn ${record.familyId}/${record.stepId} was not accepted — ${reason}`);
+}
+
+/**
+ * Settle every reservation whose request has left the queue. Returns a summary
+ * for the caller's log, or a `deferred` verdict when a read it depends on failed.
+ *
+ * Deliberately called only from the CYCLE, never from the status page: this
+ * writes ledgers, and a probe read that charged quota would make opening the
+ * page a spend (AGENTS.md — a status read performs no ledger write).
+ */
+export async function reconcileQuotaBurnReservations({ now = Date.now() } = {}) {
+ const reservations = await getQuotaBurnReservations({ now });
+ if (!reservations) {
+ console.error('❌ Quota-burn could not read its pending reservations — leaving them for the next cycle');
+ return { deferred: 'reservations unreadable', accepted: 0, refused: 0 };
+ }
+ const keys = Object.keys(reservations);
+ if (!keys.length) return { accepted: 0, refused: 0 };
+
+ const [queued, tasksByRequest] = await Promise.all([queuedRequestIds(), burnTasksByRequestId()]);
+ // Either read failing means we cannot tell "still waiting" from "accepted"
+ // from "refused". Leave every reservation exactly where it is.
+ if (!queued || !tasksByRequest) return { deferred: 'schedule or task queue unreadable', accepted: 0, refused: 0 };
+
+ let accepted = 0;
+ let refused = 0;
+ for (const key of keys) {
+ const record = reservations[key];
+ // Still on the schedule: the engines have not drained it yet. The cap keeps
+ // counting it, and the step stays blocked from a second dispatch.
+ if (queued.has(record.requestId)) continue;
+ const task = tasksByRequest.get(record.requestId);
+ if (task) {
+ if (await settleAccepted(key, record, task, now)) accepted += 1;
+ continue;
+ }
+ await settleRefused(key, record, 'the on-demand request produced no task', now);
+ refused += 1;
+ }
+ return { accepted, refused };
+}
diff --git a/server/services/quotaBurnAcceptance.test.js b/server/services/quotaBurnAcceptance.test.js
new file mode 100644
index 0000000000..af7d1b0cc9
--- /dev/null
+++ b/server/services/quotaBurnAcceptance.test.js
@@ -0,0 +1,222 @@
+/**
+ * Exactly-once burn accounting across an ASYNCHRONOUS acceptance.
+ *
+ * A workflow test against the real `data/cos/` stores (re-rooted at a temp
+ * tree), not a mock-called-a-mock check: the whole point of the reservation is
+ * that it survives a persistence round trip and a process restart, which only a
+ * suite that actually writes the files can observe. The two things a reservation
+ * is settled AGAINST — whether the request is still queued, and whether it
+ * produced a task — are the only doubles here, because they are the parts of the
+ * world this module reads rather than owns.
+ *
+ * Each case names the double-accounting it uniquely catches; between them they
+ * cover the ledger half of #6379's acceptance criteria (the runner's own
+ * reserve-vs-charge contract, and the duplicate-invocation skip, are pinned in
+ * `quotaBurnRunner.test.js`).
+ */
+
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'quota-burn-acceptance-'));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
+
+// The async world this module reads: what is still waiting on the schedule, and
+// what the on-demand engines actually produced.
+const world = { requests: [], tasks: [], requestsThrow: false, tasksThrow: false };
+
+vi.mock('./taskSchedule.js', () => ({
+ getOnDemandRequests: vi.fn(async () => {
+ if (world.requestsThrow) throw new Error('schedule unreadable');
+ return world.requests;
+ }),
+}));
+
+vi.mock('./cosTaskStore.js', () => ({
+ getAllTasks: vi.fn(async () => {
+ if (world.tasksThrow) throw new Error('COS-TASKS.md unreadable');
+ return { cos: { tasks: world.tasks }, user: { tasks: [] } };
+ }),
+}));
+
+const { getQuotaBurnDispatches } = await import('./quotaBurn.js');
+const { getQuotaBurnCompletions } = await import('./quotaBurnCompletions.js');
+const {
+ getQuotaBurnReservations,
+ getQuotaBurnRuns,
+ quotaBurnReservationKey,
+ recordQuotaBurnRun,
+} = await import('./quotaBurnStore.js');
+const { reconcileQuotaBurnReservations, reserveQuotaBurnDispatch } = await import('./quotaBurnAcceptance.js');
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+// A LIVE window key. The dispatch ledger prunes keys older than its 30-day
+// retention on every write, so a hardcoded past epoch would silently re-collapse
+// to 1 on a second charge and make every 'exactly once' assertion here vacuous.
+const DISPATCH_KEY = `grok:${Math.round(Date.now() / 3600_000) * 3600_000}`;
+const REQUEST_ID = 'demand-1';
+
+const reservation = (overrides = {}) => ({
+ familyId: 'grok',
+ stepId: 'step-a',
+ dispatchKey: DISPATCH_KEY,
+ charge: true,
+ runOnce: false,
+ requestId: REQUEST_ID,
+ ...overrides,
+});
+
+/** The step's row as the runner writes it at dispatch, before acceptance. */
+const pendingRunRow = async (requestId = REQUEST_ID) => recordQuotaBurnRun({
+ dispatched: true, familyId: 'grok', jobId: 'step-a', requestId, pending: true, taskId: null, charged: false,
+});
+
+const burnTask = (id, requestId = REQUEST_ID) => ({
+ id,
+ metadata: { quotaBurnFamily: 'grok', quotaBurnStepId: 'step-a', quotaBurnRequestId: requestId },
+});
+
+beforeEach(async () => {
+ rmSync(join(TEST_DATA_ROOT, 'cos'), { recursive: true, force: true });
+ world.requests = [];
+ world.tasks = [];
+ world.requestsThrow = false;
+ world.tasksThrow = false;
+ vi.clearAllMocks();
+});
+
+describe('reserving a burn whose acceptance is asynchronous', () => {
+ it('holds the step without charging, so a request that may still be refused costs nothing', async () => {
+ expect(await reserveQuotaBurnDispatch(reservation())).toBe(true);
+
+ expect(await getQuotaBurnReservations()).toHaveProperty(quotaBurnReservationKey('grok', 'step-a'));
+ // The whole regression: charging here is what #3179 fixed in the dispatch
+ // ledger, and the reference path reintroduced it one hop earlier.
+ expect(await getQuotaBurnDispatches()).toEqual({});
+ expect(await getQuotaBurnCompletions()).toEqual({});
+ });
+
+ it('refuses a second reservation for the same step', async () => {
+ await reserveQuotaBurnDispatch(reservation());
+ expect(await reserveQuotaBurnDispatch(reservation({ requestId: 'demand-2' }))).toBe(false);
+ expect(Object.keys(await getQuotaBurnReservations())).toHaveLength(1);
+ });
+});
+
+describe('settling a reservation against what the request produced', () => {
+ it('charges an accepted burn exactly once and records the task id on its run-log row', async () => {
+ await pendingRunRow();
+ await reserveQuotaBurnDispatch(reservation({ runOnce: true }));
+ world.tasks = [burnTask('cos-42')];
+
+ expect(await reconcileQuotaBurnReservations()).toMatchObject({ accepted: 1, refused: 0 });
+
+ expect(await getQuotaBurnDispatches()).toEqual({ [DISPATCH_KEY]: 1 });
+ expect(await getQuotaBurnCompletions()).toHaveProperty('grok:step-a');
+ expect(await getQuotaBurnReservations()).toEqual({});
+ // #6379's run-log criterion: the accepted TASK, not just the request.
+ expect((await getQuotaBurnRuns())[0]).toMatchObject({
+ requestId: REQUEST_ID, pending: false, accepted: true, taskId: 'cos-42', charged: true,
+ });
+ });
+
+ it('releases a refused request without touching the cap or the run-once ledger', async () => {
+ await pendingRunRow();
+ await reserveQuotaBurnDispatch(reservation({ runOnce: true }));
+ // The request drained and the engine refused it (improvement off, task type
+ // disabled since queuing, app gone, generator produced nothing…): the
+ // request is no longer queued and no task carries its id.
+ world.requests = [];
+ world.tasks = [];
+
+ expect(await reconcileQuotaBurnReservations()).toMatchObject({ accepted: 0, refused: 1 });
+
+ expect(await getQuotaBurnDispatches()).toEqual({});
+ expect(await getQuotaBurnCompletions()).toEqual({});
+ expect(await getQuotaBurnReservations()).toEqual({});
+ expect((await getQuotaBurnRuns())[0]).toMatchObject({ pending: false, accepted: false });
+ });
+
+ it('leaves a still-queued request alone, so the step stays held across a restart', async () => {
+ await reserveQuotaBurnDispatch(reservation());
+ world.requests = [{ id: REQUEST_ID, taskType: 'ux', origin: 'quota-burn' }];
+
+ expect(await reconcileQuotaBurnReservations()).toMatchObject({ accepted: 0, refused: 0 });
+ expect(await getQuotaBurnReservations()).toHaveProperty(quotaBurnReservationKey('grok', 'step-a'));
+ expect(await getQuotaBurnDispatches()).toEqual({});
+
+ // The engine drains it after the restart; the reservation read back off disk
+ // still carries the terms the dispatch was made under.
+ world.requests = [];
+ world.tasks = [burnTask('cos-77')];
+ await reconcileQuotaBurnReservations();
+ expect(await getQuotaBurnDispatches()).toEqual({ [DISPATCH_KEY]: 1 });
+ });
+
+ it('marks a forced burn spent without charging the automatic budget', async () => {
+ await reserveQuotaBurnDispatch(reservation({ charge: false, runOnce: true }));
+ world.tasks = [burnTask('cos-9')];
+
+ await reconcileQuotaBurnReservations();
+
+ // `charge` and `runOnce` answer different questions — the window's budget
+ // versus "this work only needed doing once".
+ expect(await getQuotaBurnDispatches()).toEqual({});
+ expect(await getQuotaBurnCompletions()).toHaveProperty('grok:step-a');
+ });
+
+ it('does not credit a burn to an ordinary clock-driven run of the same task', async () => {
+ await reserveQuotaBurnDispatch(reservation({ runOnce: true }));
+ // Same task type, fired by its own schedule: no burn provenance, so nothing
+ // joins it to the reservation and it must leave both ledgers untouched.
+ world.tasks = [{ id: 'cos-cron', metadata: { onDemand: true, onDemandOrigin: 'user' } }];
+
+ await reconcileQuotaBurnReservations();
+
+ expect(await getQuotaBurnDispatches()).toEqual({});
+ expect(await getQuotaBurnCompletions()).toEqual({});
+ });
+
+ it('honors a charge already claimed before a crash instead of charging twice', async () => {
+ await reserveQuotaBurnDispatch(reservation());
+ // What a process killed between the ledger write and the release leaves
+ // behind: the claim is on disk, and the ledger it authorized already landed.
+ const { markQuotaBurnReservationCharged } = await import('./quotaBurnStore.js');
+ const { recordQuotaBurnDispatch } = await import('./quotaBurn.js');
+ await markQuotaBurnReservationCharged(quotaBurnReservationKey('grok', 'step-a'), Date.now());
+ await recordQuotaBurnDispatch(DISPATCH_KEY);
+ world.tasks = [burnTask('cos-11')];
+
+ await reconcileQuotaBurnReservations();
+
+ expect(await getQuotaBurnDispatches()).toEqual({ [DISPATCH_KEY]: 1 });
+ expect(await getQuotaBurnReservations()).toEqual({});
+ });
+});
+
+describe('reads it cannot trust', () => {
+ it('defers every reservation when the schedule cannot be read', async () => {
+ await reserveQuotaBurnDispatch(reservation());
+ world.requestsThrow = true;
+
+ expect(await reconcileQuotaBurnReservations()).toMatchObject({ deferred: expect.any(String) });
+ expect(await getQuotaBurnReservations()).toHaveProperty(quotaBurnReservationKey('grok', 'step-a'));
+ });
+
+ it('defers rather than calling a burn refused when the task queue cannot be read', async () => {
+ await reserveQuotaBurnDispatch(reservation());
+ world.tasksThrow = true;
+
+ // Reading "no task" out of a failed read would release the reservation,
+ // re-open the cap, and lose the charge for work that IS running.
+ expect(await reconcileQuotaBurnReservations()).toMatchObject({ deferred: expect.any(String) });
+ expect(await getQuotaBurnReservations()).toHaveProperty(quotaBurnReservationKey('grok', 'step-a'));
+ expect(await getQuotaBurnDispatches()).toEqual({});
+ });
+});
diff --git a/server/services/quotaBurnInvoke.js b/server/services/quotaBurnInvoke.js
index be883558c8..df2b278256 100644
--- a/server/services/quotaBurnInvoke.js
+++ b/server/services/quotaBurnInvoke.js
@@ -376,11 +376,14 @@ async function queuedOnDemandReason(queued, taskType, appId) {
/**
* Invoke one burn step. Returns the registry's dispatch shape —
- * `{ dispatched, summary?, reason?, detail? }` — so the runner's accounting,
- * run log and skip reporting read identically whichever reference shape ran.
+ * `{ dispatched, summary?, reason?, detail?, awaiting? }` — so the runner's
+ * accounting, run log and skip reporting read identically whichever reference
+ * shape ran.
*
* A decline is reported, never thrown: work that failed to start must not
- * charge the window's cap.
+ * charge the window's cap. `awaiting` says the opposite thing about a dispatch
+ * that DID go out: the work is not accepted yet, so the runner reserves the
+ * step's place instead of charging it (see `quotaBurnAcceptance.js`).
*
* The master Improve switch is refused HERE, in the shared resolution, for all
* three lanes: the catalog carries the switch, so the page reports it on the
@@ -460,6 +463,13 @@ async function runBuiltinTaskStep({ resolved, step, family, candidate }) {
console.log(`🔥 Quota-burn requested scheduled task ${resolved.ref.taskType} for ${family.id} (${request.id})`);
return {
dispatched: true,
+ // The ONLY lane whose acceptance is asynchronous: the request is recorded
+ // now and an on-demand engine generates the task later — or refuses it. The
+ // runner reserves against this instead of charging, and settles the charge
+ // when the request is joined to the task it produced
+ // (`quotaBurnAcceptance.js`). The two synchronous lanes below return no
+ // `awaiting`, because their work is accepted the moment they return.
+ awaiting: { requestId: request.id },
summary: `Requested "${resolved.ref.taskType}"${resolved.ref.appId ? ` for ${resolved.ref.appId}` : ''}`,
detail: {
requestId: request.id,
diff --git a/server/services/quotaBurnInvoke.test.js b/server/services/quotaBurnInvoke.test.js
index 9fef1081e7..4009a5a039 100644
--- a/server/services/quotaBurnInvoke.test.js
+++ b/server/services/quotaBurnInvoke.test.js
@@ -385,6 +385,14 @@ describe('built-in agent task invocation', () => {
const result = await invokeQuotaBurnStep({ step: uxStep(), family: grok, candidate });
expect(result).toEqual({ dispatched: false, reason: state.triggerResult.error });
});
+
+ // #6379. This is the ONLY lane whose acceptance is asynchronous — an engine
+ // may still refuse the request — so it has to say so, or the runner charges
+ // the window for work that never starts.
+ it('names the request it is awaiting, so the runner reserves instead of charging', async () => {
+ const result = await invokeQuotaBurnStep({ step: uxStep(), family: grok, candidate });
+ expect(result.awaiting).toEqual({ requestId: 'demand-1' });
+ });
});
describe('custom app job invocation', () => {
@@ -409,6 +417,10 @@ describe('custom app job invocation', () => {
quotaBurnStepId: 'step-1',
quotaBurnLimitingResetAt: candidate.limitingResetAt,
});
+ // Accepted on return — the task is queued right here — so there is nothing
+ // for the runner to wait on and it charges the window directly (#6379).
+ expect(result.awaiting).toBeUndefined();
+ expect(result.detail.taskId).toBe('sys-1');
});
it('does NOT inherit the manual endpoint\'s approval bypass, force-spawn or revive', async () => {
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index f3718ea5a2..47deed2afc 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -34,13 +34,23 @@
* Everything fails CLOSED and nothing here throws into the timer: a probe that
* errors, a job that declines, or an unreadable config all end the cycle with a
* logged reason instead of charging a dispatch or crashing the process.
+ *
+ * ACCOUNTING happens on acceptance, not on dispatch. The two synchronous lanes
+ * (a programmatic handler, a custom job) are accepted the moment they return, so
+ * this file charges them itself. A reference step goes out as an on-demand
+ * REQUEST an engine may still refuse, so it takes a reservation instead — which
+ * counts against the window cap and blocks a second dispatch of the same step
+ * until `quotaBurnAcceptance.js` settles it into exactly one charge, or releases
+ * it uncharged. Each cycle settles the previous one's requests before deciding
+ * what to ask for next.
*/
import { getProviderQuotas } from './providerUsage.js';
-import { getQuotaBurnDispatches, evaluateFamilies, PLAN_COMPLETE_SKIP_REASON, recordQuotaBurnDispatch, selectBurnCandidates } from './quotaBurn.js';
+import { getQuotaBurnDispatches, evaluateFamilies, PLAN_COMPLETE_SKIP_REASON, recordQuotaBurnDispatch, selectBurnCandidates, withPendingDispatches } from './quotaBurn.js';
+import { reconcileQuotaBurnReservations, reserveQuotaBurnDispatch } from './quotaBurnAcceptance.js';
import { getQuotaBurnCompletions, recordQuotaBurnJobCompletion } from './quotaBurnCompletions.js';
import { getActiveQuotaBurnBlocks, recordBurnAgentCompletion } from './quotaBurnDenials.js';
-import { getQuotaBurnConfig, getQuotaBurnRuns, recordQuotaBurnRun } from './quotaBurnStore.js';
+import { getQuotaBurnConfig, getQuotaBurnReservations, getQuotaBurnRuns, quotaBurnReservationKey, recordQuotaBurnRun } from './quotaBurnStore.js';
import { countJobPending, runBurnJob } from './quotaBurnJobs/index.js';
import { countQuotaBurnStepPending, getQuotaBurnTaskCatalog, invokeQuotaBurnStep } from './quotaBurnInvoke.js';
import { familyHasRunnableJobs, familyIsConfigured, jobIsSpent, quotaBurnJobKey } from '../lib/quotaBurnConfig.js';
@@ -172,7 +182,7 @@ async function lastDispatchedJobByFamily() {
* and `run` needs the very same scan to know what to render. Without the
* passthrough that multi-megabyte read happened twice per dispatch.
*/
-async function dispatchFromCandidate(candidate, { jobId = null, force = false, afterJobId = null, completions = {}, catalog = {} } = {}) {
+async function dispatchFromCandidate(candidate, { jobId = null, force = false, afterJobId = null, completions = {}, catalog = {}, reserved = new Set() } = {}) {
const attempts = [];
// A forced run of a NAMED job skips the pending probe entirely and calls the
// job directly. The probe exists to pick which job in the plan to run; when
@@ -184,6 +194,15 @@ async function dispatchFromCandidate(candidate, { jobId = null, force = false, a
// its own cooldown too.
const targeted = force && jobId;
for (const job of rotatePlanAfter(selectJobs(candidate.family, { jobId, force, completions }), afterJobId)) {
+ // A burn of this step is already out and not yet accepted. Re-dispatching it
+ // would queue the same work twice and charge the window twice for one unit —
+ // the case `quotaBurnAcceptance.js` exists to close — so the walk moves on to
+ // the next step instead. Not bypassable by `force`: a duplicate is not a
+ // quota gate, it is the same work twice (see quotaBurnInvoke.js's header).
+ if (reserved.has(quotaBurnReservationKey(candidate.family.id, job.id))) {
+ attempts.push({ jobId: job.id, ...stepIdentity(job), skipped: 'a burn of this step is already awaiting acceptance' });
+ continue;
+ }
const pending = targeted ? null : await probeStep({ job, family: candidate.family, catalog });
if (pending && !(pending.count > 0)) {
attempts.push({ jobId: job.id, ...stepIdentity(job), skipped: pending.detail || 'no pending work' });
@@ -282,6 +301,16 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
// allowlist of automatic triggers so a trigger added later fails CLOSED.
if (!config.enabled && trigger !== 'manual') return { skipped: 'disabled' };
+ // Settle what the LAST dispatch asked for before deciding what this cycle may
+ // ask for. A reference burn's acceptance is asynchronous, so this is where a
+ // request that produced a task is charged and one that was refused releases
+ // its reservation — both of which change the ladder's answers below. Ahead of
+ // the run-once read for the same reason: a step accepted here is spent now.
+ const settlement = await reconcileQuotaBurnReservations();
+ if (settlement.accepted || settlement.refused) {
+ console.log(`🧾 Quota-burn settled ${settlement.accepted} accepted and ${settlement.refused} refused burn${settlement.accepted + settlement.refused === 1 ? '' : 's'}`);
+ }
+
// Read once per cycle and threaded through selection, the gate ladder, and the
// dispatch record, so a job spent mid-cycle can't be re-picked by a later
// family's walk.
@@ -333,11 +362,21 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
});
if (!quotas) return finish({ dispatched: false, reason: 'provider quota read failed' });
- const [dispatches, blocks] = await Promise.all([getQuotaBurnDispatches(), getActiveQuotaBurnBlocks()]);
+ const [charged, blocks, reservations] = await Promise.all([
+ getQuotaBurnDispatches(), getActiveQuotaBurnBlocks(), getQuotaBurnReservations(),
+ ]);
// An unreadable dispatch ledger reads as "0 used this window", which would
// walk straight past `maxDispatchesPerWindow` and spend quota the user already
// spent (#4115). Same posture as the provider-quota read above: skip the cycle.
- if (!dispatches) return finish({ dispatched: false, reason: 'dispatch ledger read failed' });
+ if (!charged) return finish({ dispatched: false, reason: 'dispatch ledger read failed' });
+ // And the same posture for the reservations: reading them as "nothing pending"
+ // would both re-queue a step already awaiting acceptance and re-open the share
+ // of the cap that step is holding.
+ if (!reservations) return finish({ dispatched: false, reason: 'pending reservations read failed' });
+ // What the ladder gates on: charges plus the burns already committed to this
+ // window and not yet accepted.
+ const dispatches = withPendingDispatches(charged, reservations);
+ const reserved = new Set(Object.keys(reservations));
// `force` is the page's explicit family/job "Run now" — the
// window/reserve/cap/denial gates that bound UNATTENDED burns don't apply to a
// run the user just asked for. It goes through the same selection, so the
@@ -378,38 +417,64 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
// provider's window.
for (const candidate of candidates) {
const outcome = await dispatchFromCandidate(candidate, {
- jobId, force, completions, catalog, afterJobId: cursors.get(candidate.family.id) || null,
+ jobId, force, completions, catalog, reserved, afterJobId: cursors.get(candidate.family.id) || null,
});
attempts.push(...outcome.attempts.map((entry) => ({ familyId: candidate.family.id, ...entry })));
if (!outcome.dispatched) continue;
- // Charge the window only once work actually started. `runBurnJob` reports a
- // decline rather than throwing, and a declined job never reaches here — so
- // the cap bounds real burns, not attempts. `charge` is false for a forced
- // run, which the user asked for outside the automatic budget.
- if (candidate.charge) await recordQuotaBurnDispatch(candidate.dispatchKey);
- // A `run once` job records its one dispatch even when the run was FORCED
- // and therefore uncharged. The two ledgers answer different questions:
- // `charge` is about this window's automatic budget, while `runOnce` is a
- // statement about the WORK ("this only needs doing once") — and the work
- // just happened, however it was triggered. The ▶ on the row stays the way
- // back, since a forced run bypasses this gate too.
- if (outcome.job.runOnce) {
- await recordQuotaBurnJobCompletion(candidate.family.id, outcome.job.id)
- // A ledger failure must not fail a dispatch that already happened —
- // the worst case is the job running one extra time next cycle, which
- // is the pre-`runOnce` behavior.
- .catch((err) => console.error(`⚠️ Quota-burn run-once ledger for ${candidate.family.id}/${outcome.job.id}: ${err.message}`));
+ // Charge the window only once work is actually ACCEPTED. A declined step
+ // reports rather than throwing and never reaches here, so the cap bounds
+ // real burns and not attempts — but a step whose lane accepts
+ // asynchronously (`awaiting`) is not accepted yet either. That one holds a
+ // reservation instead, which counts against the cap for the whole in-flight
+ // window and converts to exactly one charge when the request is joined to
+ // the task it produced (`quotaBurnAcceptance.js`). `charge` is false for a
+ // forced run, which the user asked for outside the automatic budget.
+ const requestId = outcome.result.awaiting?.requestId || null;
+ if (requestId) {
+ const held = await reserveQuotaBurnDispatch({
+ familyId: candidate.family.id,
+ stepId: outcome.job.id,
+ dispatchKey: candidate.dispatchKey,
+ charge: candidate.charge,
+ runOnce: outcome.job.runOnce === true,
+ requestId,
+ });
+ // The request is already on the schedule and cannot be recalled, so this
+ // is a warning rather than a failure: the burn will run, it just will not
+ // be charged. Better an uncharged burn than a charge for work that may
+ // still be refused.
+ if (!held) console.error(`⚠️ Quota-burn could not reserve ${candidate.family.id}/${outcome.job.id} for request ${requestId} — this burn will go uncharged`);
+ } else {
+ if (candidate.charge) await recordQuotaBurnDispatch(candidate.dispatchKey);
+ // A `run once` job records its one dispatch even when the run was FORCED
+ // and therefore uncharged. The two ledgers answer different questions:
+ // `charge` is about this window's automatic budget, while `runOnce` is a
+ // statement about the WORK ("this only needs doing once") — and the work
+ // just happened, however it was triggered. The ▶ on the row stays the way
+ // back, since a forced run bypasses this gate too.
+ if (outcome.job.runOnce) {
+ await recordQuotaBurnJobCompletion(candidate.family.id, outcome.job.id)
+ // A ledger failure must not fail a dispatch that already happened —
+ // the worst case is the job running one extra time next cycle, which
+ // is the pre-`runOnce` behavior.
+ .catch((err) => console.error(`⚠️ Quota-burn run-once ledger for ${candidate.family.id}/${outcome.job.id}: ${err.message}`));
+ }
}
// One run-log entry PER dispatch, recorded as it happens: the page's
// "Recent runs" list is how the user audits what their subscriptions were
// spent on, and folding three families into one row would hide two of them.
+ // A pending row is settled IN PLACE once its request is accepted or refused
+ // (`settleQuotaBurnRun`), so one burn stays one line in a capped feed.
dispatched.push(await finish({
dispatched: true,
familyId: candidate.family.id,
jobId: outcome.job.id,
...stepIdentity(outcome.job),
dispatchKey: candidate.dispatchKey,
- charged: candidate.charge,
+ requestId,
+ pending: Boolean(requestId),
+ taskId: outcome.result.detail?.taskId ?? null,
+ charged: candidate.charge && !requestId,
hoursUntilReset: Math.round(candidate.hoursUntilReset * 10) / 10,
percentRemaining: candidate.limit?.percentRemaining ?? null,
summary: outcome.result.summary || 'dispatched',
@@ -467,7 +532,7 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {
// Independent reads: only `quotas` is slow (a PTY scrape on the Refresh path),
// and nothing else waits on it.
const configPromise = getQuotaBurnConfig();
- const [config, quotas, dispatches, blocks, completions, runs, catalog] = await Promise.all([
+ const [config, quotas, charged, blocks, completions, runs, catalog, reservations] = await Promise.all([
configPromise,
getProviderQuotas({ wait: refresh ? WAIT.FRESH : WAIT.NEVER }).catch((err) => {
console.error(`❌ Quota-burn status could not read provider quota: ${err.message}`);
@@ -488,8 +553,16 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {
// Depends only on the config, never on `quotas` — so it overlaps the PTY
// scrape the Refresh path waits on instead of queueing behind it.
configPromise.then((cfg) => catalogFor(Object.values(cfg.families).flatMap((family) => family.jobs || []))),
+ // READ ONLY. The page shows a reserved burn as already used against the cap
+ // — it is committed to this window — but it never settles one: a probe read
+ // that charged quota would make opening the page a spend (AGENTS.md).
+ // Degrades to "nothing pending" for the same reason the two ledgers above
+ // do: on this path the cost of being wrong is a stale `N/M used` label,
+ // while the cycle refuses to run instead.
+ getQuotaBurnReservations().then((pending) => pending || {}),
]);
+ const dispatches = withPendingDispatches(charged, reservations);
const cards = new Map(quotas.map((card) => [card.family, card]));
// ONE pass over the gate ladder the runner uses — the page's "will burn" and
// its reason come from the same verdict, so they can't contradict each other.
diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.js
index 93ebd2b477..36faca3a14 100644
--- a/server/services/quotaBurnRunner.test.js
+++ b/server/services/quotaBurnRunner.test.js
@@ -23,6 +23,10 @@ const state = {
invokeResult: undefined,
catalog: { builtin: {}, custom: {} },
catalogReads: 0,
+ reservations: {},
+ reserved: [],
+ reserveOk: true,
+ settlement: { accepted: 0, refused: 0 },
};
vi.mock('./providerUsage.js', () => ({
@@ -33,6 +37,22 @@ vi.mock('./quotaBurnStore.js', () => ({
getQuotaBurnConfig: vi.fn(async () => state.config),
getQuotaBurnRuns: vi.fn(async () => state.runs),
recordQuotaBurnRun: vi.fn(async (entry) => { state.runs.unshift(entry); }),
+ // `null` — not a throw — is the module's real "could not read" signal, so the
+ // stub speaks the contract the runner is tested against.
+ getQuotaBurnReservations: vi.fn(async () => state.reservations),
+ quotaBurnReservationKey: (familyId, stepId) => `${familyId}::${stepId}`,
+}));
+
+// Settlement is doubled at the same altitude as the invocation path: this suite
+// owns the runner's accounting CONTRACT — reserve an asynchronous acceptance,
+// charge a synchronous one — while `quotaBurnAcceptance.test.js` owns what
+// settling a reservation actually does.
+vi.mock('./quotaBurnAcceptance.js', () => ({
+ reconcileQuotaBurnReservations: vi.fn(async () => state.settlement),
+ reserveQuotaBurnDispatch: vi.fn(async (record) => {
+ state.reserved.push(record);
+ return state.reserveOk;
+ }),
}));
// The shared REFERENCE path. Doubled at the same altitude as the legacy
@@ -138,6 +158,10 @@ beforeEach(() => {
state.invokePending = {};
state.invoked = [];
state.invokeResult = undefined;
+ state.reservations = {};
+ state.reserved = [];
+ state.reserveOk = true;
+ state.settlement = { accepted: 0, refused: 0 };
state.catalog = { builtin: {}, custom: {} };
state.catalogReads = 0;
__resetQuotaBurnRunner();
@@ -875,3 +899,124 @@ describe('reference steps route through the shared invocation path', () => {
expect(countJobPending).not.toHaveBeenCalled();
});
});
+
+// #6379. A reference step's work is not accepted when the request is recorded —
+// an on-demand engine may still refuse it — so the runner must reserve rather
+// than charge, and the cap must keep counting the reservation until
+// `quotaBurnAcceptance.js` settles it. Charging at the request is the #3179
+// undercount one hop earlier: the ledger says "spent" for work that never ran,
+// and a `runOnce` step retires without having done anything.
+describe('charging the cap and the run-once ledger exactly once', () => {
+ const refPlan = (jobs) => normalizeQuotaBurnConfig({
+ enabled: true,
+ families: { grok: { enabled: true, resetWithinHours: 24, jobs } },
+ });
+ const asyncStep = (overrides = {}) => refPlan([
+ { id: 'ref', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' }, ...overrides },
+ ]);
+ const held = (overrides = {}) => ({
+ 'grok::ref': {
+ familyId: 'grok', stepId: 'ref', dispatchKey: 'grok:1', charge: true, runOnce: false,
+ requestId: 'demand-1', at: now, chargedAt: null, ...overrides,
+ },
+ });
+ // The key the ladder will actually gate on for this card's window — a
+ // reservation only holds a cap slot when it names the same one.
+ const liveWindowKey = async () =>
+ (await import('./quotaBurn.js')).windowKey('grok', { resetsAt }, { now });
+
+ beforeEach(() => {
+ state.invokePending = { ref: { count: 1, detail: 'ready' } };
+ state.invokeResult = { dispatched: true, summary: 'Requested "ux"', awaiting: { requestId: 'demand-1' } };
+ });
+
+ it('reserves an asynchronous acceptance instead of charging it', async () => {
+ state.config = asyncStep({ runOnce: true });
+
+ const result = await runQuotaBurnCycle();
+
+ expect(result.dispatched).toBe(true);
+ expect(state.reserved).toEqual([{
+ familyId: 'grok', stepId: 'ref', dispatchKey: expect.any(String), charge: true, runOnce: true, requestId: 'demand-1',
+ }]);
+ // Neither ledger moves until the request is joined to a real task.
+ expect(state.recorded).toHaveLength(0);
+ expect(state.completed).toHaveLength(0);
+ expect(state.runs[0]).toMatchObject({ requestId: 'demand-1', pending: true, charged: false, taskId: null });
+ });
+
+ it('charges a synchronous acceptance directly and records the task it queued', async () => {
+ state.config = asyncStep({ runOnce: true });
+ // The custom-job and programmatic lanes queue (or perform) the work inside
+ // the call, so there is no request to wait on — and no reservation to take.
+ state.invokeResult = { dispatched: true, summary: 'Queued "job"', detail: { taskId: 'cos-5' } };
+
+ await runQuotaBurnCycle();
+
+ expect(state.reserved).toHaveLength(0);
+ expect(state.recorded).toHaveLength(1);
+ expect(state.completed).toEqual(['grok:ref']);
+ expect(state.runs[0]).toMatchObject({ pending: false, charged: true, taskId: 'cos-5' });
+ });
+
+ it('skips a step whose earlier burn is still awaiting acceptance', async () => {
+ state.config = refPlan([
+ { id: 'ref', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
+ { id: 'other', enabled: true, taskRef: { kind: 'builtin', taskType: 'docs', appId: 'app-1' } },
+ ]);
+ state.invokePending = { ref: { count: 1 }, other: { count: 1 } };
+ state.reservations = held();
+
+ const result = await runQuotaBurnCycle();
+
+ // The reserved step is passed over — no second request, no second charge —
+ // and the walk moves on to the next step in the plan.
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['other']);
+ expect(result.jobId).toBe('other');
+ });
+
+ it('counts a reservation against the window cap while it is in flight', async () => {
+ state.config = normalizeQuotaBurnConfig({
+ enabled: true,
+ families: { grok: { enabled: true, resetWithinHours: 24, maxDispatchesPerWindow: 1, jobs: [
+ { id: 'ref', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
+ ] } },
+ });
+ // Reserved against the window this cycle would select, but not yet charged.
+ // Reading the cap off the charged ledger alone would let this cycle dispatch
+ // a second burn the plan had already committed.
+ state.reservations = { 'grok::other': { ...held()['grok::ref'], stepId: 'other', dispatchKey: await liveWindowKey() } };
+
+ const result = await runQuotaBurnCycle();
+
+ expect(result.dispatched).toBe(false);
+ expect(result.reason).toContain('dispatch cap reached (1/1)');
+ });
+
+ it('refuses to run a cycle it cannot read the reservations for', async () => {
+ state.config = asyncStep();
+ state.reservations = null;
+
+ const result = await runQuotaBurnCycle();
+
+ // Same posture as the dispatch ledger: reading an unreadable file as "nothing
+ // pending" would re-queue a step already in flight and re-open its cap slot.
+ expect(result).toMatchObject({ dispatched: false, reason: 'pending reservations read failed' });
+ expect(state.invoked).toHaveLength(0);
+ });
+
+ it('settles nothing when the page reads status', async () => {
+ const { reconcileQuotaBurnReservations } = await import('./quotaBurnAcceptance.js');
+ state.config = asyncStep();
+ state.reservations = held({ dispatchKey: await liveWindowKey() });
+
+ const { status } = await getQuotaBurnStatus();
+
+ // A probe read must perform no ledger write — opening the page is not a spend.
+ expect(reconcileQuotaBurnReservations).not.toHaveBeenCalled();
+ expect(state.recorded).toHaveLength(0);
+ expect(state.completed).toHaveLength(0);
+ // It still SHOWS the reserved burn as used, because it is committed already.
+ expect(status.families.find((family) => family.id === 'grok').dispatchesUsed).toBe(1);
+ });
+});
diff --git a/server/services/quotaBurnStore.js b/server/services/quotaBurnStore.js
index 8c896501e2..89d00ecc23 100644
--- a/server/services/quotaBurnStore.js
+++ b/server/services/quotaBurnStore.js
@@ -1,9 +1,16 @@
/**
* Quota-burn config + run-log storage (machine-local).
*
- * Two files under `data/cos/`:
- * - `quota-burn.json` — the install's burn plan (see lib/quotaBurnConfig.js)
- * - `quota-burn-runs.json` — a capped log of what the runner did, for the page
+ * Four files under `data/cos/`:
+ * - `quota-burn.json` — the install's burn plan (see lib/quotaBurnConfig.js)
+ * - `quota-burn-runs.json` — a capped log of what the runner did, for the page
+ * - `quota-burn-inflight.json` — per-entry render cooldown keys, `key -> epochMs`
+ * - `quota-burn-pending.json` — reservations for burns whose request has gone
+ * out but has not been accepted yet (see `quotaBurnAcceptance.js`)
+ *
+ * None of them ships a `data.reference/` seed: an absent file means "nothing
+ * recorded", which is exactly right on a fresh install, so there is no migration
+ * to run and nothing for `setup-data.js` to overwrite.
*
* Deliberately NOT federated, for the same reason the dispatch ledger isn't:
* quota belongs to a particular machine and provider account. Two peers sharing
@@ -16,7 +23,7 @@
*/
import { join } from 'path';
-import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, PATHS, readJSONFile, readJSONFileStrict } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { isPlainObject } from '../lib/objects.js';
import { normalizeQuotaBurnConfig } from '../lib/quotaBurnConfig.js';
@@ -98,6 +105,106 @@ export async function recordQuotaBurnInFlight(keys, { now = Date.now() } = {}) {
});
}
+const reservationFile = () => join(PATHS.cos, 'quota-burn-pending.json');
+const reservationWriteQueue = createFileWriteQueue();
+
+/**
+ * How long a reservation survives without being settled.
+ *
+ * A reservation is released the moment the request it names is accepted or
+ * refused, so the TTL only ever catches a burn whose request vanished while the
+ * runner was not running (a crash between the request write and the next cycle,
+ * or a schedule edited by hand). The same 6h the in-flight cooldown uses, and
+ * for the same reason: long enough to outlast the slowest legitimate drain,
+ * short enough that a stranded step is retried the same day.
+ */
+const RESERVATION_TTL_MS = IN_FLIGHT_TTL_MS;
+
+/** `<familyId>::<stepId>` — one reservation per plan step at a time. */
+export const quotaBurnReservationKey = (familyId, stepId) => `${familyId}::${stepId}`;
+
+const liveReservations = (entries, now) => Object.fromEntries(Object.entries(entries)
+ .filter(([, record]) => isPlainObject(record)
+ && Number.isFinite(Number(record.at))
+ && now - Number(record.at) < RESERVATION_TTL_MS));
+
+/**
+ * Reservations still awaiting acceptance, or `null` when the file could not be
+ * read.
+ *
+ * The `null` is load-bearing, the same way it is on the three sibling ledgers
+ * (#4115): a reservation is what stops a second cycle queuing the step a first
+ * cycle already asked for AND what holds the step's share of the window cap
+ * before the charge lands. Reading a failed read back as "nothing pending" would
+ * both re-enqueue the work and re-open the cap, and the next write would then
+ * persist that empty file over the reservations that survived. Absent (nothing
+ * ever reserved) is still a trustworthy `{}`.
+ */
+export async function getQuotaBurnReservations({ now = Date.now() } = {}) {
+ const { ok, value } = await readJSONFileStrict(reservationFile(), {}, { logError: false });
+ if (!ok) return null;
+ return isPlainObject(value) ? liveReservations(value, now) : {};
+}
+
+/**
+ * Read-modify-write inside the queue, expiring aged reservations on the way
+ * through. `mutate` returns the next map, or `null` for "nothing to change".
+ * Never overwrites a file it could not read — the guard that is the whole point
+ * of the strict read above.
+ */
+const writeReservations = (mutate, now) => reservationWriteQueue(async () => {
+ const loaded = await getQuotaBurnReservations({ now });
+ if (!loaded) return null;
+ const next = mutate({ ...loaded });
+ if (!next) return null;
+ await atomicWrite(reservationFile(), next);
+ return next;
+});
+
+/**
+ * Hold a step's place while its request waits to be accepted. Returns null when
+ * the file was unreadable (the caller must then treat the dispatch as
+ * unreserved) or when the step is already reserved — a second reservation for
+ * one step is exactly the double-enqueue this primitive exists to prevent.
+ */
+export async function reserveQuotaBurnStep(record, { now = Date.now() } = {}) {
+ const key = quotaBurnReservationKey(record?.familyId, record?.stepId);
+ return writeReservations((reservations) => (reservations[key]
+ ? null
+ : { ...reservations, [key]: { ...record, at: now, chargedAt: null } }), now);
+}
+
+/**
+ * Stamp the instant a reservation's cap charge was CLAIMED, before the ledger
+ * write it authorizes.
+ *
+ * Claiming first is what makes settlement exactly-once across a crash: the
+ * ledger write and the release are two separate files, so a process that dies
+ * between them would otherwise charge the same accepted unit twice on the next
+ * reconcile. With the claim persisted first, a re-reconcile sees `chargedAt` and
+ * releases without charging again. The residual is the reverse and smaller
+ * failure — a crash in the gap between the claim and the ledger write loses one
+ * charge, which costs the user nothing but one extra burn later.
+ *
+ * Pass `null` to RELEASE a claim whose ledger write then failed: that is a
+ * reported failure rather than a crash, so the retry next cycle should charge
+ * rather than inherit a claim nothing ever honored.
+ */
+export async function markQuotaBurnReservationCharged(key, chargedAt, { now = Date.now() } = {}) {
+ return writeReservations((reservations) => (reservations[key]
+ ? { ...reservations, [key]: { ...reservations[key], chargedAt: chargedAt ?? null } }
+ : null), now);
+}
+
+/** Drop a reservation — its request was accepted, refused, or has aged out. */
+export async function releaseQuotaBurnStep(key, { now = Date.now() } = {}) {
+ return writeReservations((reservations) => {
+ if (!reservations[key]) return null;
+ delete reservations[key];
+ return reservations;
+ }, now);
+}
+
export async function getQuotaBurnRuns() {
const loaded = await readJSONFile(runLogFile(), null);
return Array.isArray(loaded?.runs) ? loaded.runs : [];
@@ -117,3 +224,27 @@ export async function recordQuotaBurnRun(entry) {
return next;
});
}
+
+/**
+ * Settle the run-log row a burn already wrote, in place.
+ *
+ * A reference burn is recorded when its request goes out and only ACCEPTED
+ * later, so the row is written twice — once as `pending`, once with the task id
+ * the request produced (or the reason it was refused). Patching the existing row
+ * rather than appending a second one keeps one line per burn in a feed capped at
+ * `RUN_LOG_LIMIT`, where a duplicate row per dispatch would halve the history
+ * the page can show. A row that has already aged out is simply not found, which
+ * is not an error — the burn still happened, the feed just moved on.
+ */
+export async function settleQuotaBurnRun(requestId, patch) {
+ if (!requestId) return null;
+ return runLogWriteQueue(async () => {
+ const loaded = await readJSONFile(runLogFile(), null);
+ const runs = Array.isArray(loaded?.runs) ? loaded.runs : [];
+ const at = runs.findIndex((entry) => entry?.requestId === requestId);
+ if (at < 0) return runs;
+ const next = runs.map((entry, index) => (index === at ? { ...entry, ...patch } : entry));
+ await atomicWrite(runLogFile(), { runs: next });
+ return next;
+ });
+}