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: preserve armed creative-commission crons when the inventory read fails

[._.]/ Adam Eivy4a7175815544
diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.js
index e1cd0b93bb..9afe2a2c74 100644
--- a/server/services/creativeCommissions/scheduler.js
+++ b/server/services/creativeCommissions/scheduler.js
@@ -40,6 +40,39 @@ const registered = new Set();
let lastSignature = null;
let syncTail = Promise.resolve(); // serializes concurrent re-syncs (see syncCommissionSchedules)
+// Bounded-backoff retry for a failed inventory read (#7526). A rejected
+// `listCommissions()` must not cancel every armed cron — see
+// `doSyncCommissionSchedules` — but the install still needs to notice once the
+// store recovers, without a settings/commission save to nudge it. One
+// coalesced timer only: a second failure while a retry is already pending
+// reuses it rather than stacking another, so a burst of `commission:changed`/
+// `settings:updated` events during an outage can't multiply timers or spam
+// logs faster than the backoff interval.
+const RECONCILE_RETRY_TIERS_MS = [5_000, 15_000, 60_000, 300_000]; // 5s, 15s, 1m, capped at 5m
+let reconcileRetryTimer = null;
+let reconcileRetryTier = 0;
+
+function scheduleReconcileRetry() {
+ if (reconcileRetryTimer) return; // already coalesced onto a pending retry
+ const delay = RECONCILE_RETRY_TIERS_MS[Math.min(reconcileRetryTier, RECONCILE_RETRY_TIERS_MS.length - 1)];
+ reconcileRetryTier = Math.min(reconcileRetryTier + 1, RECONCILE_RETRY_TIERS_MS.length - 1);
+ reconcileRetryTimer = setTimeout(() => {
+ reconcileRetryTimer = null;
+ // Registration only — never a catch-up fire/generation. `runScheduledCommission`
+ // re-checks enabled/schedule validity fresh on every tick regardless of when it
+ // was armed, so a retry that lands after a commission was paused or deleted
+ // cannot run it.
+ syncCommissionSchedules().catch((err) =>
+ console.error(`❌ Creative commission schedule reconciliation retry failed: ${err.message}`));
+ }, delay);
+ if (typeof reconcileRetryTimer.unref === 'function') reconcileRetryTimer.unref();
+}
+
+function clearReconcileRetry() {
+ if (reconcileRetryTimer) { clearTimeout(reconcileRetryTimer); reconcileRetryTimer = null; }
+ reconcileRetryTier = 0;
+}
+
function triggerResync() {
syncCommissionSchedules().catch((err) =>
console.error(`❌ Creative commission schedule re-sync failed: ${err.message}`));
@@ -124,7 +157,25 @@ export function syncCommissionSchedules(commissions) {
}
async function doSyncCommissionSchedules(commissions) {
- const list = commissions || await listCommissions().catch(() => []);
+ let list;
+ if (commissions) {
+ list = commissions;
+ } else {
+ try {
+ list = await listCommissions();
+ } catch (err) {
+ // Sentinel + validate (AGENTS.md): a REJECTED inventory read is not the
+ // same value as a genuinely empty one, and must not collapse into it.
+ // The old `.catch(() => [])` here made a transient DB error look like
+ // "zero commissions" and cancelled every armed cron below — preserve
+ // `registered`/`lastSignature` instead and let the retry below notice
+ // when the store recovers.
+ console.error(`❌ Creative commission inventory read failed — preserving ${registered.size} armed cron(s): ${err.message}`);
+ scheduleReconcileRetry();
+ return registered.size;
+ }
+ }
+ clearReconcileRetry(); // a successful read is itself evidence of recovery
const active = activeCommissions(list);
const timezone = await getUserTimezone().catch(() => 'UTC');
@@ -149,6 +200,7 @@ export async function startCommissionScheduler() {
export function stopCommissionScheduler() {
for (const id of [...registered]) { cancel(eventId(id)); registered.delete(id); }
lastSignature = null;
+ clearReconcileRetry();
}
/**
diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.js
index 530c869bd0..d35b2f92e2 100644
--- a/server/services/creativeCommissions/scheduler.test.js
+++ b/server/services/creativeCommissions/scheduler.test.js
@@ -195,6 +195,73 @@ describe('startCommissionScheduler (no cold-boot generation)', () => {
});
});
+describe('inventory read failure recovery (#7526)', () => {
+ it('preserves armed crons and the signature when the inventory read rejects, and emits an actionable error', async () => {
+ listCommissionsMock.mockResolvedValueOnce([videoCommission()]);
+ await startCommissionScheduler();
+ expect(scheduleMock).toHaveBeenCalledTimes(1);
+ cancelMock.mockClear(); // beforeEach's teardown of the PRIOR test's cron is not under test here
+
+ listCommissionsMock.mockRejectedValueOnce(new Error('connection terminated'));
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const count = await syncCommissionSchedules();
+
+ // The regression: a rejected read used to be swallowed into `[]`, which
+ // read as "zero commissions" and cancelled every armed cron below.
+ expect(cancelMock).not.toHaveBeenCalled();
+ expect(count).toBe(1); // still-armed count, not zero
+ expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('connection terminated'));
+ // Actionable, not a record dump — no commission payload in the log line.
+ expect(consoleErrorSpy.mock.calls.some((args) => args[0].includes('Nightly Surreal'))).toBe(false);
+ consoleErrorSpy.mockRestore();
+ });
+
+ describe('with fake timers', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('recovers registrations via the coalesced backoff retry once the store recovers, with no further user save', async () => {
+ listCommissionsMock.mockResolvedValueOnce([videoCommission()]);
+ await startCommissionScheduler();
+ cancelMock.mockClear(); // beforeEach's teardown of the PRIOR test's cron is not under test here
+
+ // The commission was actually deleted while the store was unreachable —
+ // the failed read must not have raced ahead and cancelled it early.
+ listCommissionsMock.mockRejectedValueOnce(new Error('connection terminated'));
+ listCommissionsMock.mockResolvedValue([]);
+ await syncCommissionSchedules();
+ expect(cancelMock).not.toHaveBeenCalled();
+
+ // No settings/commission mutation follows — only the scheduler's own
+ // retry should notice the store is back.
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(cancelMock).toHaveBeenCalledWith('creative-commission-commission-1');
+ });
+
+ it('coalesces repeated failures onto one pending retry instead of stacking timers', async () => {
+ listCommissionsMock.mockRejectedValue(new Error('connection terminated'));
+ await syncCommissionSchedules(); // failure #1 arms a retry at the first backoff tier
+ await syncCommissionSchedules(); // failure #2 while that retry is pending — must coalesce
+ expect(listCommissionsMock).toHaveBeenCalledTimes(2);
+
+ listCommissionsMock.mockResolvedValueOnce([]);
+ await vi.advanceTimersByTimeAsync(5_000); // first tier only
+ // A stacked second timer would fire an extra attempt at the same tick.
+ expect(listCommissionsMock).toHaveBeenCalledTimes(3);
+ });
+
+ it('shutdown cancels a pending reconciliation retry', async () => {
+ listCommissionsMock.mockRejectedValue(new Error('connection terminated'));
+ await syncCommissionSchedules();
+ stopCommissionScheduler();
+ listCommissionsMock.mockClear();
+
+ await vi.advanceTimersByTimeAsync(300_000); // past every backoff tier
+ expect(listCommissionsMock).not.toHaveBeenCalled();
+ });
+ });
+});
+
describe('runScheduledCommission gates', () => {
it('generates through the CD directive pipeline when autonomy is execute + within budget', async () => {
getCommissionMock.mockResolvedValue(videoCommission());