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: record and propagate commission pre-fire read failures instead of silent no-op (#7528)

[._.]/ Adam Eivy36e2cd49d1b4
diff --git a/server/services/creativeCommissions/scheduler.eventBoundary.test.js b/server/services/creativeCommissions/scheduler.eventBoundary.test.js
new file mode 100644
index 0000000000..a8a13cb625
--- /dev/null
+++ b/server/services/creativeCommissions/scheduler.eventBoundary.test.js
@@ -0,0 +1,99 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+// #7528: the real regression only shows up at the eventScheduler boundary — a
+// pre-fire read failure caught INSIDE the handler (the old `.catch(() => null)`)
+// never reaches `runEvent`'s own try/catch, so the schedule's own history read
+// `success: true` for a tick that generated nothing. Unlike scheduler.test.js
+// (which mocks eventScheduler.js so isValidCron is deterministic), this suite
+// runs the REAL eventScheduler.js so the propagate-and-rearm contract is
+// verified against the actual contained boundary, not a mock standing in for it.
+
+vi.mock('../userTimezone.js', () => ({ getUserTimezone: async () => 'UTC' }));
+const settingsEvents = new EventEmitter();
+vi.mock('../settings.js', () => ({ settingsEvents, getSettings: async () => ({}) }));
+
+const getCommissionMock = vi.fn();
+const recordRunMock = vi.fn(async () => ({}));
+const commissionEvents = new EventEmitter();
+vi.mock('./store.js', () => ({
+ listCommissions: async () => [],
+ getCommission: (...a) => getCommissionMock(...a),
+ recordCommissionRun: (...a) => recordRunMock(...a),
+ commissionEvents,
+ ERR_NOT_FOUND: 'NOT_FOUND',
+ commissionStore: () => ({ readRaw: async () => null }),
+ sanitizeCommission: (raw) => raw,
+}));
+
+const { schedule, cancel, triggerNow, getEvent, getHistory } = await import('../eventScheduler.js');
+const { runScheduledCommission } = await import('./scheduler.js');
+
+const EVENT_ID = 'creative-commission-boundary-test-7528';
+
+afterEach(() => {
+ cancel(EVENT_ID); // clears the real pending timer so the test process can exit
+ vi.clearAllMocks();
+});
+
+function arm() {
+ return schedule({
+ id: EVENT_ID,
+ type: 'cron',
+ cron: '0 0 * * *',
+ handler: () => runScheduledCommission('commission-boundary'),
+ metadata: { source: 'creativeCommissionScheduler', commissionId: 'commission-boundary' },
+ });
+}
+
+describe('runScheduledCommission through the real eventScheduler boundary (#7528)', () => {
+ it('a pre-fire read failure is caught by runEvent, recorded failed on the SCHEDULE history, and the recurring event stays armed', async () => {
+ getCommissionMock.mockRejectedValueOnce(Object.assign(new Error('storage timeout'), { code: 'ETIMEDOUT' }));
+ arm();
+
+ await triggerNow(EVENT_ID);
+
+ // The contained boundary (runEvent) caught the throw — it never escaped as
+ // an unhandled rejection, and the tick reads as a failure, not a success.
+ const [entry] = getHistory({ eventId: EVENT_ID, limit: 1 });
+ expect(entry.success).toBe(false);
+ expect(entry.error).toBe('storage timeout');
+
+ // The recurring event is still active with a next run scheduled — a failed
+ // read must not cancel the schedule.
+ const event = getEvent(EVENT_ID);
+ expect(event.active).toBe(true);
+ expect(event.nextRunAt).toEqual(expect.any(Number));
+
+ // The failure also landed on the commission's OWN run history.
+ expect(recordRunMock).toHaveBeenCalledWith('commission-boundary', expect.objectContaining({
+ status: 'failed', trigger: 'schedule', error: 'read-failed:ETIMEDOUT',
+ }));
+ });
+
+ it('the next tick after a failed read runs normally — the schedule was never wedged', async () => {
+ getCommissionMock.mockRejectedValueOnce(Object.assign(new Error('storage timeout'), { code: 'ETIMEDOUT' }));
+ arm();
+ await triggerNow(EVENT_ID);
+
+ recordRunMock.mockClear();
+ getCommissionMock.mockResolvedValueOnce({ id: 'commission-boundary', enabled: false });
+ await triggerNow(EVENT_ID);
+
+ const [latest] = getHistory({ eventId: EVENT_ID, limit: 1 });
+ expect(latest.success).toBe(true); // the disabled commission is a quiet, successful no-op
+ expect(recordRunMock).not.toHaveBeenCalled();
+ expect(getEvent(EVENT_ID).active).toBe(true);
+ });
+
+ it('confirmed deletion (ERR_NOT_FOUND) reads as a quiet success on the schedule history — no failed tick, no ledger write', async () => {
+ getCommissionMock.mockRejectedValueOnce(Object.assign(new Error('gone'), { code: 'NOT_FOUND' }));
+ arm();
+
+ await triggerNow(EVENT_ID);
+
+ const [entry] = getHistory({ eventId: EVENT_ID, limit: 1 });
+ expect(entry.success).toBe(true);
+ expect(recordRunMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.js
index 9afe2a2c74..a0d504c967 100644
--- a/server/services/creativeCommissions/scheduler.js
+++ b/server/services/creativeCommissions/scheduler.js
@@ -5,8 +5,12 @@
* the user's cadence. Modeled directly on `seriesAutopilotScheduler.js`:
* - one eventScheduler cron per enabled commission (id namespace below),
* - a `registered` set + `lastSignature` guard so re-syncs are cheap no-ops,
- * - a fire handler that runs OUTSIDE the Express request lifecycle (whole body
- * in try/catch — a throw here would crash the process),
+ * - a fire handler that runs OUTSIDE the Express request lifecycle: the fire
+ * core (`fireCommission`) never throws (whole body in try/catch), and the
+ * one deliberate exception — a pre-fire read failure in
+ * `runScheduledCommission` — is re-thrown to eventScheduler's own
+ * contained `runEvent` boundary so the outage lands on that tick's run
+ * history instead of reading as a silent no-op,
* - re-reads the commission + autonomy config on every fire (only the cron is
* captured at registration).
*
@@ -28,7 +32,7 @@ import { getSettings, settingsEvents } from '../settings.js';
import { RENDER_TARGET } from '../../lib/renderTargets.js';
import { renderTargetDefaults } from '../imageGen/cloudProviderConfig.js';
import { resolveVideoMode, VIDEO_GEN_MODE } from '../videoGen/modes.js';
-import { listCommissions, getCommission, recordCommissionRun, commissionEvents } from './store.js';
+import { listCommissions, getCommission, recordCommissionRun, commissionEvents, ERR_NOT_FOUND } from './store.js';
import { commissionToCron, commissionToRecurrence } from './directive.js';
import { buildCommissionDirective, getAbilityAdapter } from './abilityAdapters.js';
import { buildMusicTasteRecipe } from './musicTasteRecipe.js';
@@ -203,16 +207,53 @@ export function stopCommissionScheduler() {
clearReconcileRetry();
}
+// Sentinel + validate (AGENTS.md): a pre-fire read failure must never persist
+// with the same shape as a legitimately-empty one. Never store the raw error
+// message — it can originate from a DB driver and, per this fix's acceptance
+// criteria, run history must exclude record contents, prompts and private
+// feedback. A short, bounded classification (an error `code` when the failure
+// supplies one, else its constructor name) is enough to distinguish outage
+// types on the commission's run history without repeating this file's log.
+function classifyPrefireReadError(err) {
+ if (typeof err?.code === 'string' && err.code) return `read-failed:${err.code}`;
+ if (typeof err?.name === 'string' && err.name) return `read-failed:${err.name}`;
+ return 'read-failed';
+}
+
/**
- * A scheduled cron tick. Runs outside the Express request lifecycle — every
- * throwable path is contained (getCommission is caught here, everything else
- * inside fireCommission), so a fire can't crash Node. Skips silently when the
- * commission vanished, was paused, or its schedule became invalid since
- * registration.
+ * A scheduled cron tick. Runs outside the Express request lifecycle. A
+ * confirmed deletion (ERR_NOT_FOUND), a paused commission, or a schedule that
+ * became invalid since registration are honest no-ops and skip silently.
+ *
+ * Any OTHER pre-fire read failure — a storage timeout on the commission row
+ * itself, or on its federated feedback (store.js's getCommission deliberately
+ * lets that propagate rather than substitute "no feedback", so generation
+ * never ignores ratings) — must not read as a quiet success. It is recorded
+ * as a failed run against the commission (id + a safe classification only),
+ * then RE-THROWN: eventScheduler's own contained boundary (`runEvent`) is
+ * where this fire is caught, marked failed on the schedule's own history, and
+ * the recurring event is rearmed for the next tick either way.
*/
export async function runScheduledCommission(commissionId) {
- const commission = await getCommission(commissionId).catch(() => null);
- if (!commission || commission.enabled === false) return;
+ let commission;
+ try {
+ commission = await getCommission(commissionId);
+ } catch (err) {
+ if (err?.code === ERR_NOT_FOUND) return; // confirmed deletion — quiet no-op
+ console.error(`❌ Creative commission ${commissionId} pre-fire read failed: ${err?.message || err}`);
+ await recordCommissionRun(commissionId, {
+ status: 'failed',
+ trigger: 'schedule',
+ error: classifyPrefireReadError(err),
+ }).catch((ledgerErr) => {
+ // The failed-run write above ITSELF failed — nothing landed on the
+ // commission's history, so this is the only surviving record of the
+ // outage. Its own diagnostic, per this fix's acceptance criteria.
+ console.error(`❌ Creative commission ${commissionId} pre-fire read failed AND its failure could not be recorded: ${ledgerErr?.message || ledgerErr}`);
+ });
+ throw err; // propagate to eventScheduler's runEvent, which contains it
+ }
+ if (commission.enabled === false) return; // paused — quiet no-op
const recurrence = commissionToRecurrence(commission.schedule);
const cron = commissionToCron(commission.schedule);
diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.js
index d35b2f92e2..10d6f32241 100644
--- a/server/services/creativeCommissions/scheduler.test.js
+++ b/server/services/creativeCommissions/scheduler.test.js
@@ -27,6 +27,9 @@ vi.mock('./store.js', () => ({
getCommission: (...a) => getCommissionMock(...a),
recordCommissionRun: (...a) => recordRunMock(...a),
commissionEvents,
+ // Real value from store.js — the scheduler branches on this to keep a
+ // confirmed deletion a quiet no-op (#7528).
+ ERR_NOT_FOUND: 'NOT_FOUND',
// projectControl (the commission:changed reconciler the scheduler subscribes)
// reads the raw record to find the projects a commission spawned. Empty here —
// the reconciler is covered by projectControl.test.js; these tests are about
@@ -344,9 +347,9 @@ describe('runScheduledCommission gates', () => {
expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'skipped', reason: 'budget' }));
});
- it('does nothing when the commission is missing or disabled', async () => {
- getCommissionMock.mockResolvedValue(null);
- await runScheduledCommission('gone');
+ it('does nothing when the commission is disabled (paused)', async () => {
+ getCommissionMock.mockResolvedValue(videoCommission({ enabled: false }));
+ await runScheduledCommission('commission-1');
expect(createProjectMock).not.toHaveBeenCalled();
expect(recordRunMock).not.toHaveBeenCalled();
});
@@ -432,6 +435,54 @@ describe('runScheduledCommission gates', () => {
});
});
+describe('runScheduledCommission pre-fire read failures (#7528)', () => {
+ it('confirmed deletion (ERR_NOT_FOUND) stays a quiet no-op — no failed run, nothing thrown', async () => {
+ getCommissionMock.mockRejectedValue(Object.assign(new Error('Commission not found: commission-1'), { code: 'NOT_FOUND' }));
+ await expect(runScheduledCommission('commission-1')).resolves.toBeUndefined();
+ expect(recordRunMock).not.toHaveBeenCalled();
+ expect(createProjectMock).not.toHaveBeenCalled();
+ });
+
+ it('a non-NOT_FOUND pre-fire read failure (e.g. a storage timeout, or the deliberately-propagated federated feedback read) records a failed run and propagates', async () => {
+ const readErr = Object.assign(new Error('storage timeout'), { code: 'ETIMEDOUT' });
+ getCommissionMock.mockRejectedValue(readErr);
+
+ await expect(runScheduledCommission('commission-1')).rejects.toBe(readErr);
+
+ // Never a successful no-op: the ledger shows a failed scheduled attempt.
+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', {
+ status: 'failed', trigger: 'schedule', error: 'read-failed:ETIMEDOUT',
+ });
+ // Never substitutes empty feedback / launches generation on an unreadable read.
+ expect(createProjectMock).not.toHaveBeenCalled();
+ });
+
+ it('classifies an error with no `.code` by constructor name, never by its raw message', async () => {
+ getCommissionMock.mockRejectedValue(new TypeError('cannot read property of undefined'));
+ await expect(runScheduledCommission('commission-1')).rejects.toThrow('cannot read property of undefined');
+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ error: 'read-failed:TypeError' }));
+ });
+
+ it('falls back to a bare classification when the error carries neither a code nor a name', async () => {
+ getCommissionMock.mockRejectedValue(Object.assign(Object.create(null), { message: 'opaque failure' }));
+ await expect(runScheduledCommission('commission-1')).rejects.toBeTruthy();
+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ error: 'read-failed' }));
+ });
+
+ it('emits an independent diagnostic and still propagates the original error when the failure ledger write ALSO fails', async () => {
+ const readErr = Object.assign(new Error('storage timeout'), { code: 'ETIMEDOUT' });
+ getCommissionMock.mockRejectedValue(readErr);
+ const ledgerErr = new Error('ledger write timeout');
+ recordRunMock.mockRejectedValueOnce(ledgerErr);
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await expect(runScheduledCommission('commission-1')).rejects.toBe(readErr);
+
+ expect(consoleErrorSpy.mock.calls.some(([line]) => line.includes('pre-fire read failed AND its failure could not be recorded'))).toBe(true);
+ consoleErrorSpy.mockRestore();
+ });
+});
+
describe('runCommissionNow (manual "Run Now")', () => {
it('fires through the CD pipeline, tags the run manual, and returns a started outcome', async () => {
recordRunMock.mockResolvedValue({ id: 'run-1', status: 'started' });