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([issue-984]): synchronous daily-action reservation against same-tick scheduled jobs

Adam Eivy2aa9876c6494
diff --git a/server/services/cosJobScheduler.js b/server/services/cosJobScheduler.js
index d604058b51..3b8badd093 100644
--- a/server/services/cosJobScheduler.js
+++ b/server/services/cosJobScheduler.js
@@ -128,6 +128,26 @@ export async function registerSingleJobSchedule(jobId) {
const spawningJobIds = new Set();
const spawningJobTimeouts = new Map();
+// Synchronous daily-action reservation counter (#984). The budget gate in
+// executeScheduledJob reads recorded usage + spawningJobIds + running autonomous
+// agents — but there are awaits between a job passing that gate and being
+// counted by spawningJobIds (agent jobs) or recordDomainUsage (script/shell
+// jobs). Two jobs coming due in the SAME event-loop tick could therefore both
+// clear a `maxActionsPerDay == 1` gate before either was counted, nudging a soft
+// daily cap by one. This counter is incremented the instant a job is admitted to
+// fire — synchronously, before any further await — and included in the gate's
+// in-flight term, so a same-tick sibling sees the reservation and is withheld.
+// It's released the moment the job is handed off to spawningJobIds /
+// recordDomainUsage or hits any exit path (a `finally` plus the agent handoff
+// cover every path, so the two counters never double-count the same job).
+let scheduledActionReservations = 0;
+
+// Test-only observability: lets the concurrency test assert the reservation
+// counter settles back to zero after a tick (no leak across any exit path).
+export function getScheduledActionReservations() {
+ return scheduledActionReservations;
+}
+
function addSpawningJob(jobId) {
spawningJobIds.add(jobId);
// Auto-clear after 5 minutes if spawn never completes, and re-register the timer
@@ -199,18 +219,19 @@ export async function executeScheduledJob(jobId) {
overBudget = true;
} else if (cosBudget.budget?.maxActionsPerDay != null) {
// In-flight = autonomous agents already running PLUS jobs admitted this
- // tick whose agent hasn't registered yet (`spawningJobIds`), so a burst of
- // concurrently-due jobs can't all pass before any usage is recorded.
- // Residual: two jobs coming due in the SAME event-loop tick can each clear
- // this gate before either is counted (agent jobs reserve `spawningJobIds`
- // only after later awaits; inline script/shell record only post-execution),
- // nudging a SOFT daily cap by one. Closing that needs a synchronous
- // reservation across every exit path — deferred as over-engineering for a
- // soft guardrail under the single-process trust model. Tracked in #984.
+ // tick whose agent hasn't registered yet (`spawningJobIds`) PLUS jobs
+ // admitted-to-fire this tick but not yet handed off to `spawningJobIds`
+ // or recorded usage (`scheduledActionReservations`, #984). The reservation
+ // term closes the same-tick window: two jobs coming due in one event-loop
+ // tick used to each clear this gate before either was counted, because an
+ // agent job reserves `spawningJobIds` only after later awaits and an inline
+ // script/shell job records usage only post-execution. The reservation is
+ // bumped synchronously the instant a job is admitted (below), so a same-tick
+ // sibling reading this gate sees it and is correctly withheld.
const runningAutonomous = Object.values(state.agents).filter(
(a) => a.status === 'running' && a.metadata?.taskType && a.metadata.taskType !== 'user'
).length;
- const inFlight = runningAutonomous + spawningJobIds.size;
+ const inFlight = runningAutonomous + spawningJobIds.size + scheduledActionReservations;
if (remainingActionBudget(cosBudget.budget, cosBudget.usage, inFlight) < 1) overBudget = true;
}
if (overBudget) {
@@ -230,104 +251,134 @@ export async function executeScheduledJob(jobId) {
return;
}
- // Script jobs and shell jobs execute directly without spawning an AI agent —
- // so they never reach completeAgent's budget tally. Record them against the CoS
- // daily budget (#711) here on success, since a fired scheduled job is exactly
- // the autonomous action the gate above withholds when over budget.
- if (isScriptJob(job)) {
- const startedAt = Date.now();
- const scriptOk = await executeScriptJob(job).then(() => true, err => {
- emitLog('error', `Script job failed: ${job.name} - ${err.message}`, { jobId: job.id });
- return false;
- });
- // Count the fired attempt against the budget whether it succeeded or failed —
- // a failing/looping scheduled job still consumes autonomous work + wall-clock,
- // and must not be able to bypass the daily cap.
- await recordDomainUsage('cos', { actions: 1, ms: Date.now() - startedAt })
- .catch(err => console.error(`❌ Failed to record CoS budget usage for script job ${job.id}: ${err.message}`));
- if (scriptOk) emitLog('info', `Script job executed: ${job.name}`, { jobId: job.id });
- } else if (isShellJob(job)) {
- const startedAt = Date.now();
- const shellOk = await executeShellJob(job).then(() => true, err => {
- emitLog('error', `Shell job failed: ${job.name} - ${err.message}`, { jobId: job.id });
- return false;
- });
- await recordDomainUsage('cos', { actions: 1, ms: Date.now() - startedAt })
- .catch(err => console.error(`❌ Failed to record CoS budget usage for shell job ${job.id}: ${err.message}`));
- if (shellOk) emitLog('info', `Shell job executed: ${job.name}`, { jobId: job.id });
- } else {
- // Check if this job is already being spawned or has a running agent.
- // Don't re-register the timer here — the job:spawned handler will do it
- // after recordJobExecution updates lastRun. Re-registering with stale
- // lastRun causes a 1-second re-fire loop.
- if (spawningJobIds.has(jobId)) {
- emitLog('debug', `Job ${job.name} skipped - already spawning`, { jobId });
- return;
- }
- const agentAlreadyRunning = Object.values(state.agents).some(
- a => a.status === 'running' && a.metadata?.jobId === jobId
- );
- if (agentAlreadyRunning) {
- emitLog('debug', `Job ${job.name} skipped - agent already running`, { jobId });
- return;
- }
-
- // Check capacity before spawning an agent
- const runningAgents = Object.values(state.agents).filter(a => a.status === 'running').length;
- if (runningAgents >= state.config.maxConcurrentAgents) {
- emitLog('debug', `Job ${job.name} deferred - no agent slots`, { jobId });
- // Retry in 60s
- scheduleEvent({
- id: `job:${jobId}`,
- type: 'once',
- delayMs: 60000,
- handler: () => executeScheduledJob(jobId),
- metadata: { description: `Autonomous job: ${job.name} (retry)`, jobId }
+ // Admitted to fire: reserve one daily action SYNCHRONOUSLY, before any further
+ // await (#984). The budget gate above read `scheduledActionReservations`, and
+ // there is no `await` between that read and this increment — so "read gate →
+ // reserve" is an atomic critical section. Two jobs coming due in the same tick
+ // serialize on it: the first reads remaining≥1 and reserves; the second reads
+ // the reservation and is withheld. The reservation is handed off to
+ // `spawningJobIds` (agent jobs) or recorded usage (script/shell jobs) the
+ // moment either takes over the in-flight accounting, and the `finally`
+ // releases it on every non-firing exit path (already-spawning, already-running,
+ // capacity-defer, gate-skip, spawn failure). `releaseReservation` is idempotent
+ // so the explicit handoff release and the `finally` can both fire harmlessly.
+ let reserved = true;
+ scheduledActionReservations += 1;
+ const releaseReservation = () => {
+ if (!reserved) return;
+ reserved = false;
+ scheduledActionReservations = Math.max(0, scheduledActionReservations - 1);
+ };
+
+ try {
+ // Script jobs and shell jobs execute directly without spawning an AI agent —
+ // so they never reach completeAgent's budget tally. Record them against the CoS
+ // daily budget (#711) here on success, since a fired scheduled job is exactly
+ // the autonomous action the gate above withholds when over budget.
+ if (isScriptJob(job)) {
+ const startedAt = Date.now();
+ const scriptOk = await executeScriptJob(job).then(() => true, err => {
+ emitLog('error', `Script job failed: ${job.name} - ${err.message}`, { jobId: job.id });
+ return false;
});
- return;
- }
-
- // Run gate check — skip LLM if precondition not met
- // Gate errors fail-open (run the job) to avoid silently dropping scheduled work
- let gateResult;
- try {
- gateResult = await checkJobGate(jobId);
- } catch (gateErr) {
- emitLog('warn', `Job ${job.name} gate error, failing open: ${gateErr?.message || gateErr}`, { jobId });
- gateResult = { shouldRun: true, reason: 'Gate error — failing open' };
- }
- if (!gateResult.shouldRun) {
- emitLog('debug', `Job ${job.name} gate skipped: ${gateResult.reason}`, { jobId, gate: gateResult });
- // Update lastRun so the job reschedules at its normal interval, but don't increment runCount
- await recordJobGateSkip(jobId).catch(err =>
- console.error(`❌ Failed to record gate-skip for ${jobId}: ${err.message}`)
+ // Count the fired attempt against the budget whether it succeeded or failed —
+ // a failing/looping scheduled job still consumes autonomous work + wall-clock,
+ // and must not be able to bypass the daily cap.
+ await recordDomainUsage('cos', { actions: 1, ms: Date.now() - startedAt })
+ .catch(err => console.error(`❌ Failed to record CoS budget usage for script job ${job.id}: ${err.message}`));
+ releaseReservation(); // recorded usage now owns the in-flight count for this action
+ if (scriptOk) emitLog('info', `Script job executed: ${job.name}`, { jobId: job.id });
+ } else if (isShellJob(job)) {
+ const startedAt = Date.now();
+ const shellOk = await executeShellJob(job).then(() => true, err => {
+ emitLog('error', `Shell job failed: ${job.name} - ${err.message}`, { jobId: job.id });
+ return false;
+ });
+ await recordDomainUsage('cos', { actions: 1, ms: Date.now() - startedAt })
+ .catch(err => console.error(`❌ Failed to record CoS budget usage for shell job ${job.id}: ${err.message}`));
+ releaseReservation(); // recorded usage now owns the in-flight count for this action
+ if (shellOk) emitLog('info', `Shell job executed: ${job.name}`, { jobId: job.id });
+ } else {
+ // Check if this job is already being spawned or has a running agent.
+ // Don't re-register the timer here — the job:spawned handler will do it
+ // after recordJobExecution updates lastRun. Re-registering with stale
+ // lastRun causes a 1-second re-fire loop.
+ if (spawningJobIds.has(jobId)) {
+ emitLog('debug', `Job ${job.name} skipped - already spawning`, { jobId });
+ return;
+ }
+ const agentAlreadyRunning = Object.values(state.agents).some(
+ a => a.status === 'running' && a.metadata?.jobId === jobId
);
- await registerSingleJobSchedule(jobId);
- return;
- }
- if (hasGate(jobId)) {
- emitLog('info', `Job ${job.name} gate passed: ${gateResult.reason}`, { jobId, gate: gateResult });
- }
+ if (agentAlreadyRunning) {
+ emitLog('debug', `Job ${job.name} skipped - agent already running`, { jobId });
+ return;
+ }
+
+ // Check capacity before spawning an agent
+ const runningAgents = Object.values(state.agents).filter(a => a.status === 'running').length;
+ if (runningAgents >= state.config.maxConcurrentAgents) {
+ emitLog('debug', `Job ${job.name} deferred - no agent slots`, { jobId });
+ // Retry in 60s
+ scheduleEvent({
+ id: `job:${jobId}`,
+ type: 'once',
+ delayMs: 60000,
+ handler: () => executeScheduledJob(jobId),
+ metadata: { description: `Autonomous job: ${job.name} (retry)`, jobId }
+ });
+ return;
+ }
- // Mark as spawning before emitting task:ready to prevent races
- addSpawningJob(jobId);
- try {
- const task = await generateTaskFromJob(job);
- emitLog('info', `Autonomous job firing: ${job.name}`, { jobId, category: job.category });
- cosEvents.emit('task:ready', task);
- // Don't re-register timer here — lastRun hasn't been updated yet, so
- // computeNextJobFireTime would return a past-due time and the timer would
- // fire in 1s, creating a rapid re-fire loop. The job:spawned handler
- // re-registers after recordJobExecution updates lastRun.
- return;
- } catch (err) {
- clearSpawningJob(jobId);
- emitLog('error', `Failed to fire autonomous job: ${job.name} - ${err?.message || err}`, { jobId, category: job.category });
+ // Run gate check — skip LLM if precondition not met
+ // Gate errors fail-open (run the job) to avoid silently dropping scheduled work
+ let gateResult;
+ try {
+ gateResult = await checkJobGate(jobId);
+ } catch (gateErr) {
+ emitLog('warn', `Job ${job.name} gate error, failing open: ${gateErr?.message || gateErr}`, { jobId });
+ gateResult = { shouldRun: true, reason: 'Gate error — failing open' };
+ }
+ if (!gateResult.shouldRun) {
+ emitLog('debug', `Job ${job.name} gate skipped: ${gateResult.reason}`, { jobId, gate: gateResult });
+ // Update lastRun so the job reschedules at its normal interval, but don't increment runCount
+ await recordJobGateSkip(jobId).catch(err =>
+ console.error(`❌ Failed to record gate-skip for ${jobId}: ${err.message}`)
+ );
+ await registerSingleJobSchedule(jobId);
+ return;
+ }
+ if (hasGate(jobId)) {
+ emitLog('info', `Job ${job.name} gate passed: ${gateResult.reason}`, { jobId, gate: gateResult });
+ }
+
+ // Mark as spawning before emitting task:ready to prevent races
+ addSpawningJob(jobId);
+ releaseReservation(); // spawningJobIds now owns the in-flight count for this action
+ try {
+ const task = await generateTaskFromJob(job);
+ emitLog('info', `Autonomous job firing: ${job.name}`, { jobId, category: job.category });
+ cosEvents.emit('task:ready', task);
+ // Don't re-register timer here — lastRun hasn't been updated yet, so
+ // computeNextJobFireTime would return a past-due time and the timer would
+ // fire in 1s, creating a rapid re-fire loop. The job:spawned handler
+ // re-registers after recordJobExecution updates lastRun.
+ return;
+ } catch (err) {
+ clearSpawningJob(jobId);
+ emitLog('error', `Failed to fire autonomous job: ${job.name} - ${err?.message || err}`, { jobId, category: job.category });
+ }
}
- }
- // Re-register for next fire time (script/shell jobs, early returns, and error paths)
- await registerSingleJobSchedule(jobId);
+ // Re-register for next fire time (script/shell jobs, early returns, and error paths)
+ await registerSingleJobSchedule(jobId);
+ } finally {
+ // Catch-all: release on every exit path that didn't hand the reservation off
+ // (already-spawning / already-running / capacity-defer / gate-skip /
+ // generation+spawn failure). Idempotent, so a path that already handed off is
+ // a no-op here.
+ releaseReservation();
+ }
}
/**
diff --git a/server/services/cosJobScheduler.test.js b/server/services/cosJobScheduler.test.js
new file mode 100644
index 0000000000..269c88c27e
--- /dev/null
+++ b/server/services/cosJobScheduler.test.js
@@ -0,0 +1,219 @@
+/**
+ * Tests for cosJobScheduler.js — the same-tick daily-action budget race (#984).
+ *
+ * The per-domain CoS daily action budget is enforced in executeScheduledJob from
+ * recorded usage + an in-flight count. Before #984 there was a narrow same-process
+ * window: a second scheduled job that read the budget gate while a first job was
+ * parked AFTER passing the gate but BEFORE being counted could also pass — agent
+ * jobs reserve `spawningJobIds` only after the `checkJobGate` await, and inline
+ * script/shell jobs record usage only post-execution. A `maxActionsPerDay: 1` cap
+ * could therefore be overshot by one. #984 adds a synchronous reservation counter,
+ * bumped the instant a job is admitted to fire (before any further await) and
+ * included in the gate's in-flight term, so a second job in that window sees the
+ * reservation and is withheld.
+ *
+ * Unlike the source-level regression guards in cos.test.js, these tests exercise
+ * the REAL executeScheduledJob (the race lives in the await interleaving, which a
+ * pure inline copy can't reproduce). We deterministically reproduce the window by
+ * parking the first job at its first post-reservation await, then running the
+ * second job to completion while the first sits in the window. The only un-mocked
+ * dependency is the pure `remainingActionBudget` math — everything with I/O is
+ * mocked.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+let daemonRunning = true;
+const sharedState = {
+ paused: false,
+ config: { autonomousJobsEnabled: true, maxConcurrentAgents: 5 },
+ agents: {},
+};
+
+// A manually-resolved deferred — lets a test park one call at a chosen await and
+// release it after the other call has run, modelling the exact race interleaving.
+function deferred() {
+ let resolve;
+ const promise = new Promise((r) => { resolve = r; });
+ return { promise, resolve };
+}
+
+vi.mock('./eventScheduler.js', () => ({
+ schedule: vi.fn(),
+ cancel: vi.fn(),
+ parseCronToNextRun: vi.fn(() => new Date(0)),
+}));
+vi.mock('../lib/timezone.js', () => ({
+ getUserTimezone: vi.fn().mockResolvedValue('UTC'),
+ getLocalParts: vi.fn(() => ({ dayOfWeek: 1 })),
+ nextLocalTime: vi.fn((ms) => ms),
+}));
+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ formatDuration: vi.fn(() => '1h'),
+}));
+vi.mock('./cosState.js', () => ({
+ loadState: vi.fn(async () => sharedState),
+ isDaemonRunning: vi.fn(() => daemonRunning),
+}));
+vi.mock('../lib/domainAutonomy.js', () => ({
+ getDomainMode: vi.fn(() => 'execute'),
+ DOMAIN_IDS: ['brain', 'memory', 'cos', 'messages'],
+}));
+// remainingActionBudget is pure — keep it REAL so the gate math is the math.
+vi.mock('./domainUsage.js', () => ({
+ getDomainBudgetStatus: vi.fn(),
+ recordDomainUsage: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock('./cosEvents.js', () => ({
+ cosEvents: { emit: vi.fn() },
+ emitLog: vi.fn(),
+}));
+vi.mock('./cosTaskStore.js', () => ({ getCosTasks: vi.fn() }));
+vi.mock('./cosTaskGenerator.js', () => ({ queueEligibleImprovementTasks: vi.fn() }));
+
+const generateTaskFromJob = vi.fn(async (job) => ({ id: `task-${job.id}`, description: job.name }));
+const executeScriptJob = vi.fn().mockResolvedValue(undefined);
+const checkJobGate = vi.fn().mockResolvedValue({ shouldRun: true, reason: 'ok' });
+vi.mock('./autonomousJobs.js', () => ({
+ generateTaskFromJob: (...a) => generateTaskFromJob(...a),
+ recordJobGateSkip: vi.fn().mockResolvedValue(undefined),
+ isScriptJob: (job) => job?.type === 'script',
+ executeScriptJob: (...a) => executeScriptJob(...a),
+ isShellJob: (job) => job?.type === 'shell',
+ executeShellJob: vi.fn().mockResolvedValue(undefined),
+ // Dynamically imported inside executeScheduledJob — return a job built from the
+ // requested id so two distinct ids model two distinct same-tick jobs.
+ getJob: vi.fn(async (jobId) => ({
+ id: jobId,
+ name: jobId,
+ enabled: true,
+ category: 'test',
+ intervalMs: 86_400_000,
+ type: globalThis.__nextJobType || 'agent',
+ })),
+}));
+vi.mock('./jobGates.js', () => ({
+ checkJobGate: (...a) => checkJobGate(...a),
+ hasGate: vi.fn(() => false),
+}));
+
+import {
+ executeScheduledJob,
+ getScheduledActionReservations,
+ clearSpawningJob,
+} from './cosJobScheduler.js';
+import { getDomainBudgetStatus } from './domainUsage.js';
+
+beforeEach(() => {
+ daemonRunning = true;
+ sharedState.agents = {};
+ globalThis.__nextJobType = 'agent';
+ generateTaskFromJob.mockClear();
+ executeScriptJob.mockClear();
+ checkJobGate.mockReset();
+ checkJobGate.mockResolvedValue({ shouldRun: true, reason: 'ok' });
+ // maxActionsPerDay:1, nothing recorded yet — the exact same-tick boundary.
+ getDomainBudgetStatus.mockResolvedValue({
+ withinBudget: true,
+ exceeded: null,
+ budget: { maxActionsPerDay: 1, maxMinutesPerDay: null },
+ usage: { actions: 0, ms: 0 },
+ });
+});
+
+afterEach(() => {
+ // Success paths leave the job in spawningJobIds (+ a 5-min timeout); clear so the
+ // module-level set and timer don't leak across tests.
+ clearSpawningJob('job-a');
+ clearSpawningJob('job-b');
+ clearSpawningJob('script-a');
+ clearSpawningJob('script-b');
+ delete globalThis.__nextJobType;
+});
+
+describe('executeScheduledJob — same-tick daily-action budget race (#984)', () => {
+ it('a second AGENT job in the post-gate window is withheld (maxActionsPerDay:1)', async () => {
+ // Park job-a at checkJobGate — its FIRST await after the budget gate passed
+ // and (with the fix) after the synchronous reservation was taken, but BEFORE
+ // addSpawningJob counts it. Distinct ids so the `spawningJobIds.has` guard
+ // can't be what stops job-b — only the reservation gate should.
+ const gateReached = deferred();
+ const releaseGate = deferred();
+ checkJobGate.mockImplementation(async (jobId) => {
+ if (jobId === 'job-a') {
+ gateReached.resolve();
+ await releaseGate.promise;
+ }
+ return { shouldRun: true, reason: 'ok' };
+ });
+
+ const pA = executeScheduledJob('job-a');
+ await gateReached.promise; // job-a now sits in the race window
+
+ // job-b reads the budget gate while job-a is parked. Buggy code: remaining is
+ // still 1 (job-a not yet in spawningJobIds), so job-b fires too → two spawns.
+ // Fixed code: job-b sees the reservation, is over budget, and is withheld.
+ await executeScheduledJob('job-b');
+
+ releaseGate.resolve();
+ await pA;
+
+ expect(generateTaskFromJob).toHaveBeenCalledTimes(1);
+ expect(generateTaskFromJob).toHaveBeenCalledWith(expect.objectContaining({ id: 'job-a' }));
+ });
+
+ it('a second SCRIPT job in the post-record window is withheld (maxActionsPerDay:1)', async () => {
+ globalThis.__nextJobType = 'script';
+ // Script jobs reach their first post-reservation await at executeScriptJob
+ // (recordDomainUsage runs only after it resolves). Park job-a there.
+ const execReached = deferred();
+ const releaseExec = deferred();
+ executeScriptJob.mockImplementation(async (job) => {
+ if (job.id === 'script-a') {
+ execReached.resolve();
+ await releaseExec.promise;
+ }
+ });
+
+ const pA = executeScheduledJob('script-a');
+ await execReached.promise;
+
+ await executeScheduledJob('script-b');
+
+ releaseExec.resolve();
+ await pA;
+
+ expect(executeScriptJob).toHaveBeenCalledTimes(1);
+ expect(executeScriptJob).toHaveBeenCalledWith(expect.objectContaining({ id: 'script-a' }));
+ });
+
+ it('releases the reservation on every exit path (counter settles to zero)', async () => {
+ const gateReached = deferred();
+ const releaseGate = deferred();
+ checkJobGate.mockImplementation(async (jobId) => {
+ if (jobId === 'job-a') {
+ gateReached.resolve();
+ await releaseGate.promise;
+ }
+ return { shouldRun: true, reason: 'ok' };
+ });
+
+ const pA = executeScheduledJob('job-a');
+ await gateReached.promise;
+ // While job-a is parked the reservation is live (the window the gate read).
+ expect(getScheduledActionReservations()).toBe(1);
+
+ await executeScheduledJob('job-b'); // withheld path releases its reservation
+ releaseGate.resolve();
+ await pA; // handoff to spawningJobIds releases job-a's reservation
+
+ expect(getScheduledActionReservations()).toBe(0);
+ });
+
+ it('a single job still fires when the budget has room for exactly one', async () => {
+ await executeScheduledJob('job-a');
+ expect(generateTaskFromJob).toHaveBeenCalledTimes(1);
+ expect(getScheduledActionReservations()).toBe(0);
+ });
+});