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: retry the improvement-check wake-up calc instead of sleeping through a cron minute (#7527)

[._.]/ Adam Eivya0560ce4c7a9
diff --git a/client/src/components/UpcomingTasksWidget.jsx b/client/src/components/UpcomingTasksWidget.jsx
index 65697f88d6..af3d6fee12 100644
--- a/client/src/components/UpcomingTasksWidget.jsx
+++ b/client/src/components/UpcomingTasksWidget.jsx
@@ -17,13 +17,34 @@ import { useAutoRefetch } from '../hooks/useAutoRefetch';
* Helps users understand what the CoS will work on next
*/
const UpcomingTasksWidget = memo(function UpcomingTasksWidget() {
- const { data: upcoming, loading } = useAutoRefetch(
+ const { data: upcoming, loading, error } = useAutoRefetch(
() => api.getCosUpcomingTasks(6, { silent: true }),
60000
);
- // Don't render while loading or if no upcoming tasks
- if (loading || !upcoming?.length) {
+ // Don't render during the initial load.
+ if (loading) {
+ return null;
+ }
+
+ if (!upcoming?.length) {
+ // A genuine calculation failure (#7527 — the server now rejects rather
+ // than returning a misleadingly "complete" empty array) with no prior
+ // good result to fall back to. Say so instead of silently disappearing,
+ // which used to be indistinguishable from "nothing is scheduled".
+ if (error) {
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6">
+ <div className="flex items-center gap-3">
+ <Clock className="w-6 h-6 text-gray-500" aria-hidden="true" />
+ <div>
+ <h3 className="text-lg font-semibold text-white">Upcoming Tasks</h3>
+ <p className="text-sm text-port-warning">Schedule unavailable — retrying…</p>
+ </div>
+ </div>
+ </div>
+ );
+ }
return null;
}
@@ -208,6 +229,14 @@ const UpcomingTasksWidget = memo(function UpcomingTasksWidget() {
<span>Schedule adjusted based on task performance</span>
</div>
)}
+
+ {/* A later fetch failed but a prior good result is still on screen —
+ say so rather than silently going stale (#7527). */}
+ {error && (
+ <div className="mt-3 pt-3 border-t border-port-border text-xs text-port-warning text-center">
+ Showing last known schedule — live data unavailable
+ </div>
+ )}
</div>
);
});
diff --git a/client/src/components/UpcomingTasksWidget.test.jsx b/client/src/components/UpcomingTasksWidget.test.jsx
new file mode 100644
index 0000000000..ab1f206314
--- /dev/null
+++ b/client/src/components/UpcomingTasksWidget.test.jsx
@@ -0,0 +1,95 @@
+import { MemoryRouter } from 'react-router';
+import { render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// UpcomingTasksWidget's own logic is what response to a good/failed/absent
+// fetch should render — the polling/retry mechanics belong to useAutoRefetch
+// and are covered by its own test suite. Mocking the hook lets these tests
+// pin the widget's render contract directly against each { data, loading,
+// error } combination without fake timers or interval plumbing.
+const { mockUseAutoRefetch, mockGetCosUpcomingTasks } = vi.hoisted(() => ({
+ mockUseAutoRefetch: vi.fn(),
+ mockGetCosUpcomingTasks: vi.fn(),
+}));
+
+vi.mock('../hooks/useAutoRefetch', () => ({
+ useAutoRefetch: (...args) => mockUseAutoRefetch(...args),
+}));
+
+vi.mock('../services/api', () => ({
+ getCosUpcomingTasks: (...args) => mockGetCosUpcomingTasks(...args),
+}));
+
+import UpcomingTasksWidget from './UpcomingTasksWidget.jsx';
+
+const renderWidget = () => render(
+ <MemoryRouter>
+ <UpcomingTasksWidget />
+ </MemoryRouter>,
+);
+
+const readyTask = {
+ taskType: 'security',
+ status: 'ready',
+ description: 'Security audit',
+ intervalType: 'cron',
+ runCount: 2,
+ lastRunFormatted: '2h ago',
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('UpcomingTasksWidget', () => {
+ it('renders nothing during the initial load', () => {
+ mockUseAutoRefetch.mockReturnValue({ data: null, loading: true, error: null });
+ const { container } = renderWidget();
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('renders nothing when there is genuinely no upcoming work and no error', () => {
+ mockUseAutoRefetch.mockReturnValue({ data: [], loading: false, error: null });
+ const { container } = renderWidget();
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('shows an unavailable state instead of silently hiding when the first-ever fetch fails (#7527)', () => {
+ mockUseAutoRefetch.mockReturnValue({ data: null, loading: false, error: new Error('boom') });
+ renderWidget();
+ expect(screen.getByText('Schedule unavailable — retrying…')).toBeInTheDocument();
+ });
+
+ it('renders ready and scheduled tasks on a healthy load', () => {
+ mockUseAutoRefetch.mockReturnValue({
+ data: [
+ readyTask,
+ {
+ taskType: 'documentation',
+ status: 'scheduled',
+ description: 'Docs sweep',
+ intervalType: 'cron',
+ eligibleInFormatted: '3h',
+ successRate: null,
+ },
+ ],
+ loading: false,
+ error: null,
+ });
+ renderWidget();
+ expect(screen.getByText('1 ready now')).toBeInTheDocument();
+ expect(screen.getByText('Security audit')).toBeInTheDocument();
+ expect(screen.getByText('Docs sweep')).toBeInTheDocument();
+ });
+
+ it('keeps showing the last good schedule and flags it stale when a later fetch fails (#7527)', () => {
+ mockUseAutoRefetch.mockReturnValue({
+ data: [readyTask],
+ loading: false,
+ error: new Error('boom'),
+ });
+ renderWidget();
+ expect(screen.getByText('Security audit')).toBeInTheDocument();
+ expect(screen.getByText('Showing last known schedule — live data unavailable')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/hooks/useAutoRefetch.js b/client/src/hooks/useAutoRefetch.js
index 0843b9c89c..f8f91b08e9 100644
--- a/client/src/hooks/useAutoRefetch.js
+++ b/client/src/hooks/useAutoRefetch.js
@@ -39,13 +39,19 @@ import { useVisibilityEvent } from './useVisibilityEvent.js';
* no `applyResult` / setState calls run, and the return is `{ refetch }`
* only. Use when the caller owns its own state via `fetchFn`'s side
* effects and would otherwise `return null` and ignore `data` / `loading`.
- * @returns {{ refetch: Function, data?: any, loading?: boolean }}
- * `data` and `loading` are omitted when `pollOnly` is true.
+ * @returns {{ refetch: Function, data?: any, loading?: boolean, error?: Error|null }}
+ * `data` / `loading` / `error` are omitted when `pollOnly` is true. `error`
+ * holds the most recent fetch failure (cleared on the next success) — the
+ * `data` it accompanies is still the last GOOD result, per the note above,
+ * so a caller that wants to show a "showing stale data" indicator without
+ * erasing the last good render checks `error` alongside `data` rather than
+ * inferring staleness from an empty/falsy `data`.
*/
export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
const { enabled = true, immediate = true, compare, pollOnly = false } = options;
const [data, setData] = useState(null);
const [loading, setLoading] = useState(!pollOnly);
+ const [error, setError] = useState(null);
const fetchRef = useRef(fetchFn);
const compareRef = useRef(compare);
@@ -61,6 +67,7 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
const applyResult = useCallback((result) => {
if (pollOnly) return;
+ setError(null);
setData((prev) => {
const cmp = compareRef.current;
if (cmp && prev != null && result != null && cmp(prev, result)) return prev;
@@ -80,7 +87,10 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
return result;
} catch (err) {
console.warn(`⚠️ Auto-refetch failed: ${err?.message ?? String(err)}`);
- if (!pollOnly) setLoading(false);
+ if (!pollOnly) {
+ setLoading(false);
+ setError(err instanceof Error ? err : new Error(String(err ?? 'Auto-refetch failed')));
+ }
return undefined;
}
}, [applyResult, pollOnly]);
@@ -104,7 +114,10 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
if (!pollOnly) setLoading(false);
} catch (err) {
console.warn(`⚠️ Auto-refetch failed: ${err?.message ?? String(err)}`);
- if (!cancelled && !pollOnly) setLoading(false);
+ if (!cancelled && !pollOnly) {
+ setLoading(false);
+ setError(err instanceof Error ? err : new Error(String(err ?? 'Auto-refetch failed')));
+ }
}
};
@@ -124,5 +137,5 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
});
if (pollOnly) return { refetch };
- return { data, loading, refetch };
+ return { data, loading, error, refetch };
}
diff --git a/client/src/hooks/useAutoRefetch.test.jsx b/client/src/hooks/useAutoRefetch.test.jsx
index 6c0d05d86b..fe663abedd 100644
--- a/client/src/hooks/useAutoRefetch.test.jsx
+++ b/client/src/hooks/useAutoRefetch.test.jsx
@@ -83,6 +83,32 @@ describe('useAutoRefetch', () => {
warn.mockRestore();
});
+ it('exposes the failure as `error` alongside the preserved last-good `data`, and clears it on recovery', async () => {
+ // `enabled: false` + manual refetch() calls give deterministic control
+ // over each fetch, rather than racing an on-interval poll (refetch is
+ // intentionally unconditional — see the hook's own doc comment).
+ const fetchFn = vi.fn()
+ .mockResolvedValueOnce('first')
+ .mockRejectedValueOnce(new Error('boom'))
+ .mockResolvedValueOnce('recovered');
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const { result } = renderHook(() => useAutoRefetch(fetchFn, 60_000, { enabled: false }));
+
+ await act(async () => { await result.current.refetch(); });
+ expect(result.current.data).toBe('first');
+ expect(result.current.error).toBeNull();
+
+ await act(async () => { await result.current.refetch(); });
+ expect(result.current.error?.message).toBe('boom');
+ expect(result.current.data).toBe('first'); // last-good data is untouched by the failure
+
+ await act(async () => { await result.current.refetch(); });
+ expect(result.current.data).toBe('recovered');
+ expect(result.current.error).toBeNull();
+ warn.mockRestore();
+ });
+
it('survives non-Error rejections (null, string) without throwing inside the catch', async () => {
const fetchFn = vi.fn()
.mockResolvedValueOnce('first')
diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.js
index 9a663785e8..90fa875b73 100644
--- a/server/routes/cosScheduleRoutes.js
+++ b/server/routes/cosScheduleRoutes.js
@@ -214,7 +214,15 @@ router.get('/schedule', asyncHandler(async (req, res) => {
// GET /api/cos/upcoming - Get upcoming tasks preview
router.get('/upcoming', asyncHandler(async (req, res) => {
const { limit } = parsePagination(req.query, { defaultLimit: 10, maxLimit: 500 });
- const upcoming = await taskSchedule.getUpcomingTasks(limit);
+ // getUpcomingTasks now rejects (rather than returning a partial []) when an
+ // app inventory/override/readiness read fails (#7527) — surface that as a
+ // real failure instead of a misleading 200 with incomplete deadlines.
+ const upcoming = await taskSchedule.getUpcomingTasks(limit).catch((err) => {
+ throw new ServerError(`Upcoming tasks unavailable: ${err?.message || err}`, {
+ status: 503,
+ code: 'UPCOMING_TASKS_UNAVAILABLE'
+ });
+ });
res.json(upcoming);
}));
diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.js
index d0a3f3cd50..d349951ad1 100644
--- a/server/routes/cosScheduleRoutes.test.js
+++ b/server/routes/cosScheduleRoutes.test.js
@@ -138,6 +138,18 @@ describe('CoS Schedule Routes', () => {
expect(response.status).toBe(200);
expect(taskSchedule.getUpcomingTasks).toHaveBeenCalledWith(3);
});
+
+ // #7527: getUpcomingTasks now rejects (rather than silently returning a
+ // partial []) when an app inventory/override/readiness read fails. The
+ // route must not answer 200 with incomplete deadlines.
+ it('does not return 200 when the upcoming-tasks calculation is unavailable', async () => {
+ taskSchedule.getUpcomingTasks.mockRejectedValue(new Error('app inventory read failed'));
+
+ const response = await request(app).get('/api/cos/upcoming');
+
+ expect(response.status).toBe(503);
+ expect(response.body.code).toBe('UPCOMING_TASKS_UNAVAILABLE');
+ });
});
describe('GET /api/cos/schedule/task/:taskType', () => {
diff --git a/server/services/cosJobScheduler.js b/server/services/cosJobScheduler.js
index 54d08c3757..93429189a6 100644
--- a/server/services/cosJobScheduler.js
+++ b/server/services/cosJobScheduler.js
@@ -11,7 +11,9 @@
* (`spawningJobIds` / `addSpawningJob` / `clearSpawningJob`) that prevents
* duplicate spawns when timers overlap.
* - `scheduleNextImprovementCheck` — the improvement-check cadence timer that
- * queues eligible improvement tasks and asks the scheduler to dequeue.
+ * queues eligible improvement tasks and asks the scheduler to dequeue. Owns
+ * a short retry (`IMPROVEMENT_CHECK_RETRY_MS`) when getUpcomingTasks' inputs
+ * are unavailable, instead of falling back to the 1h default (#7527).
*
* Self-contained — imports only sibling services (no import back to cos.js).
* The paused check reads loadState() directly (cos.js's isPaused lived there),
@@ -21,7 +23,7 @@
* (job:spawned/job:spawn-failed → clearSpawningJob + re-register) back to these.
*/
-import { schedule as scheduleEvent, cancel as cancelEvent, parseCronToNextRun, parseRecurrenceToNextRun } from './eventScheduler.js';
+import { schedule as scheduleEvent, cancel as cancelEvent, getEvent as getScheduledEvent, parseCronToNextRun, parseRecurrenceToNextRun } from './eventScheduler.js';
import { getLocalParts, nextLocalTime } from '../lib/timezone.js';
import { getUserTimezone } from './userTimezone.js';
import { formatDuration } from '../lib/fileUtils.js';
@@ -452,31 +454,122 @@ export async function unregisterJobSchedules() {
}
}
+// Cap for the "nothing scheduled" fallback delay.
+const MAX_CHECK_INTERVAL = 60 * 60 * 1000;
+// Retry cadence when getUpcomingTasks' inputs (app inventory/override/
+// readiness reads) are unavailable — short enough that a transient outage
+// self-heals well inside a cron minute, per #7527.
+const IMPROVEMENT_CHECK_RETRY_MS = 15 * 1000;
+
+// Transition-based logging: log once when the input read starts failing and
+// once when it recovers, not on every 15s retry — a persistent outage would
+// otherwise flood the log every 15s.
+let improvementCheckInputUnavailable = false;
+
+/**
+ * The improvement-check one-shot handler — shared by every arm of the
+ * 'cos-improvement-check' event, whether the delay came from a normal
+ * calculation or the input-unavailable retry below. Queues eligible
+ * improvement work, then re-arms via scheduleNextImprovementCheck().
+ *
+ * This is a 'once' event — the eventScheduler does NOT auto-reschedule it,
+ * so the handler must re-arm itself. Re-arm in `finally` so a throw in the
+ * body (loadState / getCosTasks / queueEligibleImprovementTasks) can't
+ * permanently halt the improvement cadence until a process restart.
+ * scheduleNextImprovementCheck() never throws (its own getUpcomingTasks call
+ * is caught internally) — a naive throw from here would otherwise leave this
+ * fired 'once' event deactivated with no replacement registered.
+ */
+async function runImprovementCheckOnce() {
+ if (!isDaemonRunning()) return;
+ try {
+ const paused = (await loadState()).paused || false;
+ if (paused) return;
+
+ const state = await loadState();
+ // Gate on the CoS auto-run domain (see canQueueImprovementTasks): off/
+ // dry-run are planning postures that withhold the COS-TASKS.md mutation.
+ if (canQueueImprovementTasks(state)) {
+ const cosTaskData = await getCosTasks();
+ await queueEligibleImprovementTasks(state, cosTaskData);
+ cosEvents.emit('cos:dequeue-requested');
+ }
+ } finally {
+ await scheduleNextImprovementCheck();
+ }
+}
+
/**
* Schedule a one-shot timer for the next due improvement task.
* When it fires, queues eligible improvement tasks and re-schedules.
+ *
+ * Called from three places (cos.js boot, the 'schedule:changed' handler, and
+ * this same re-arm from runImprovementCheckOnce's `finally`) — every one of
+ * them must end up with exactly one 'cos-improvement-check' timer armed, so
+ * this function never throws. When getUpcomingTasks' inputs are unavailable
+ * it arms a short retry instead of propagating (#7527).
*/
export async function scheduleNextImprovementCheck() {
if (!isDaemonRunning()) return;
const taskSchedule = await import('./taskSchedule.js');
- // Pull a wider list so a perpetually-"ready" weekly task can't mask an upcoming
- // cron boundary. We sort by status (ready first), so 1-element peeks always miss
- // the cron slot when anything else is ready.
- const upcoming = await taskSchedule.getUpcomingTasks(50);
+ const now = Date.now();
+ let delayMs;
+ let description;
+ let upcoming;
+
+ try {
+ // Pull a wider list so a perpetually-"ready" weekly task can't mask an upcoming
+ // cron boundary. We sort by status (ready first), so 1-element peeks always miss
+ // the cron slot when anything else is ready.
+ upcoming = await taskSchedule.getUpcomingTasks(50);
+ } catch (err) {
+ // An app inventory/override/readiness read failed — the calculation is
+ // UNAVAILABLE, not "nothing scheduled". Falling back to the 1h default
+ // here could sleep through a cron minute a healthy read would have
+ // caught, so arm a short retry and let the next attempt recompute the
+ // real deadline once the input recovers.
+ if (!improvementCheckInputUnavailable) {
+ improvementCheckInputUnavailable = true;
+ console.error(`❌ Upcoming-tasks calculation unavailable, retrying in 15s: ${err?.message || err}`);
+ }
+
+ // Don't let the retry push out an earlier deadline this same event is
+ // already armed for (e.g. a cron boundary a prior successful calculation
+ // found) — arm the sooner of "now + retry delay" and that deadline.
+ const existing = getScheduledEvent('cos-improvement-check');
+ const existingDelay = existing?.active && Number.isFinite(existing.nextRunAt)
+ ? existing.nextRunAt - now
+ : null;
+ delayMs = existingDelay !== null && existingDelay > 0
+ ? Math.min(existingDelay, IMPROVEMENT_CHECK_RETRY_MS)
+ : IMPROVEMENT_CHECK_RETRY_MS;
+
+ scheduleEvent({
+ id: 'cos-improvement-check',
+ type: 'once',
+ delayMs: Math.max(delayMs, 1000),
+ handler: runImprovementCheckOnce,
+ metadata: { description: 'Improvement check retry (upcoming-tasks unavailable)' }
+ });
+ return;
+ }
+
+ if (improvementCheckInputUnavailable) {
+ improvementCheckInputUnavailable = false;
+ console.log('✅ Upcoming-tasks calculation recovered');
+ }
// Default: check again in 1 hour if nothing scheduled
// Cap at 1 hour as a fallback for work whose next boundary is not known;
// getUpcomingTasks also includes per-app cron overrides.
- const MAX_CHECK_INTERVAL = 60 * 60 * 1000;
- let delayMs = MAX_CHECK_INTERVAL;
- let description = 'Periodic improvement check (1h)';
+ delayMs = MAX_CHECK_INTERVAL;
+ description = 'Periodic improvement check (1h)';
// Keep future app deadlines even when another app makes the same task ready.
// Ready tasks don't gate the delay — they'll be queued on whatever the next check
// ends up being. Cron tasks DO gate the delay, because their firing window is a
// single minute; missing it pushes the next attempt out by a full period.
- const now = Date.now();
const nextScheduled = upcoming
.map(t => ({ ...t, eligibleIn: t.nextScheduledAt > now
? t.nextScheduledAt - now
@@ -495,28 +588,7 @@ export async function scheduleNextImprovementCheck() {
id: 'cos-improvement-check',
type: 'once',
delayMs: Math.max(delayMs, 1000),
- handler: async () => {
- if (!isDaemonRunning()) return;
- // This is a 'once' event — the eventScheduler does NOT auto-reschedule it,
- // so the handler must re-arm itself. Re-arm in `finally` so a throw in the
- // body (loadState / getCosTasks / queueEligibleImprovementTasks) can't
- // permanently halt the improvement cadence until a process restart.
- try {
- const paused = (await loadState()).paused || false;
- if (paused) return;
-
- const state = await loadState();
- // Gate on the CoS auto-run domain (see canQueueImprovementTasks): off/
- // dry-run are planning postures that withhold the COS-TASKS.md mutation.
- if (canQueueImprovementTasks(state)) {
- const cosTaskData = await getCosTasks();
- await queueEligibleImprovementTasks(state, cosTaskData);
- cosEvents.emit('cos:dequeue-requested');
- }
- } finally {
- await scheduleNextImprovementCheck();
- }
- },
+ handler: runImprovementCheckOnce,
metadata: { description }
});
}
diff --git a/server/services/cosJobScheduler.test.js b/server/services/cosJobScheduler.test.js
index 8ddd2757d9..1f1f166564 100644
--- a/server/services/cosJobScheduler.test.js
+++ b/server/services/cosJobScheduler.test.js
@@ -41,6 +41,7 @@ function deferred() {
vi.mock('./eventScheduler.js', () => ({
schedule: vi.fn(),
cancel: vi.fn(),
+ getEvent: vi.fn(() => null),
parseCronToNextRun: vi.fn(() => new Date(0)),
}));
vi.mock('../lib/timezone.js', () => ({
@@ -57,6 +58,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => ({
vi.mock('./cosState.js', () => ({
loadState: vi.fn(async () => sharedState),
isDaemonRunning: vi.fn(() => daemonRunning),
+ canQueueImprovementTasks: vi.fn(() => false),
}));
vi.mock('../lib/domainAutonomy.js', () => ({
getDomainMode: vi.fn(() => 'execute'),
@@ -107,11 +109,12 @@ import {
clearSpawningJob,
registerSingleJobSchedule,
} from './cosJobScheduler.js';
-import { schedule as scheduleEvent, cancel as cancelEvent } from './eventScheduler.js';
+import { schedule as scheduleEvent, cancel as cancelEvent, getEvent as getScheduledEvent } from './eventScheduler.js';
vi.mock('./taskSchedule.js', () => ({ getUpcomingTasks: vi.fn() }));
import { getUpcomingTasks } from './taskSchedule.js';
import { getJob } from './autonomousJobs.js';
import { getDomainBudgetStatus } from './domainUsage.js';
+import { canQueueImprovementTasks } from './cosState.js';
beforeEach(() => {
daemonRunning = true;
@@ -312,3 +315,97 @@ it('wakes at a future app deadline even while the task is ready for another app'
vi.useRealTimers();
}
});
+
+// #7527: getUpcomingTasks now REJECTS (rather than swallowing input failures
+// into a misleadingly "complete" []) when app inventory/override/readiness
+// reads fail. cosJobScheduler owns that failure — it must retry soon instead
+// of falling back to the 1h default, which could sleep through a cron minute.
+describe('scheduleNextImprovementCheck — getUpcomingTasks input failure (#7527)', () => {
+ beforeEach(async () => {
+ // Reset the module-level "input unavailable" transition flag to a known
+ // state (false) before each test, so the log-once assertions below don't
+ // depend on execution order with other tests in this file.
+ getScheduledEvent.mockReturnValue(null);
+ getUpcomingTasks.mockResolvedValueOnce([]);
+ await scheduleNextImprovementCheck();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('arms a short retry instead of the 1h fallback, and logs the outage once (not per consecutive failure)', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
+ scheduleEvent.mockClear();
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ getUpcomingTasks.mockRejectedValueOnce(new Error('inventory read failed'));
+ await scheduleNextImprovementCheck();
+ expect(scheduleEvent).toHaveBeenLastCalledWith(expect.objectContaining({
+ id: 'cos-improvement-check', delayMs: 15000
+ }));
+ expect(errSpy).toHaveBeenCalledTimes(1);
+
+ getUpcomingTasks.mockRejectedValueOnce(new Error('still down'));
+ await scheduleNextImprovementCheck();
+ expect(errSpy).toHaveBeenCalledTimes(1);
+
+ errSpy.mockRestore();
+ });
+
+ it('logs recovery exactly once when getUpcomingTasks succeeds again', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ getUpcomingTasks.mockRejectedValueOnce(new Error('inventory read failed'));
+ await scheduleNextImprovementCheck();
+
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ getUpcomingTasks.mockResolvedValueOnce([]);
+ await scheduleNextImprovementCheck();
+ expect(logSpy).toHaveBeenCalledTimes(1);
+
+ logSpy.mockRestore();
+ });
+
+ it('preserves an already-armed earlier deadline instead of pushing it out to the 15s retry', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
+ scheduleEvent.mockClear();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ getScheduledEvent.mockReturnValue({ active: true, nextRunAt: Date.now() + 5000 });
+
+ getUpcomingTasks.mockRejectedValueOnce(new Error('inventory read failed'));
+ await scheduleNextImprovementCheck();
+
+ expect(scheduleEvent).toHaveBeenLastCalledWith(expect.objectContaining({
+ id: 'cos-improvement-check', delayMs: 5000
+ }));
+ });
+
+ it('re-arms via the retry handler even when its own finally-block recompute also fails (no orphaned one-shot)', async () => {
+ // This is the trap called out in #7527: the fired handler recomputes the
+ // next arm from its own `finally`. If that recompute threw instead of
+ // catching internally, the eventScheduler's 'once' rearm logic would
+ // deactivate this fired event with no replacement — the improvement
+ // cadence would die silently until a process restart.
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
+ scheduleEvent.mockClear();
+ getScheduledEvent.mockReturnValue(null);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ canQueueImprovementTasks.mockReturnValue(false);
+
+ getUpcomingTasks.mockRejectedValueOnce(new Error('inventory read failed'));
+ await scheduleNextImprovementCheck();
+ const retryHandler = scheduleEvent.mock.calls.at(-1)[0].handler;
+
+ scheduleEvent.mockClear();
+ getUpcomingTasks.mockRejectedValueOnce(new Error('still down'));
+ await expect(retryHandler()).resolves.toBeUndefined();
+
+ expect(scheduleEvent).toHaveBeenCalledTimes(1);
+ expect(scheduleEvent).toHaveBeenLastCalledWith(expect.objectContaining({ id: 'cos-improvement-check' }));
+ });
+});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 05910c3842..4a4e60fc56 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -1538,10 +1538,16 @@ export async function getUpcomingTasks(limit = 10) {
// include app-scoped cadence overrides. In particular, an app can opt into a
// cron expression while the global task remains on-demand; omitting that
// boundary leaves the hourly fallback as the only chance to notice the slot.
- const activeApps = await getActiveApps().catch(() => []);
+ //
+ // Strict on purpose (#7527): a rejected inventory/override read used to be
+ // swallowed into [] / {}, which looked like "no apps configured" rather than
+ // "the calculation is unavailable" — cosJobScheduler.scheduleNextImprovementCheck
+ // would then arm its 1h fallback and could sleep through a cron minute a
+ // healthy read would have caught. Let the rejection propagate; the caller
+ // owns the retry.
+ const activeApps = await getActiveApps();
const activeAppOverrides = activeApps.length > 0
- ? await mapWithConcurrency(activeApps, 8, (app) =>
- getAppTaskTypeOverrides(app.id).catch(() => ({})))
+ ? await mapWithConcurrency(activeApps, 8, (app) => getAppTaskTypeOverrides(app.id))
: [];
for (const [taskType, interval] of Object.entries(schedule.tasks)) {
@@ -1563,7 +1569,7 @@ export async function getUpcomingTasks(limit = 10) {
.map(candidate => candidate.app);
const appChecks = scheduledApps.length > 0
? await mapWithConcurrency(scheduledApps, 8, (app) =>
- shouldRunTask(taskType, app.id, { featureEnabled, schedule }).catch(() => null))
+ shouldRunTask(taskType, app.id, { featureEnabled, schedule }))
: [];
const appReady = appChecks.some(appCheck => appCheck?.shouldRun);
const futureAppTimes = appChecks.map(appCheck => Date.parse(appCheck?.nextRunAt))
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 52fcb5a168..c2b4f0b286 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -2713,6 +2713,37 @@ describe('taskSchedule', () => {
})
})
+ // #7527: a rejected app inventory/override/readiness read used to be
+ // swallowed into [] / {} / null, which read as "no apps configured" or
+ // "not ready" rather than "the calculation is unavailable" — hiding the
+ // failure from cosJobScheduler.scheduleNextImprovementCheck (which then
+ // armed its 1h fallback and could sleep through a cron minute). Assert
+ // the rejection now propagates out of getUpcomingTasks instead.
+ describe('getUpcomingTasks — propagates input failures instead of swallowing them (#7527)', () => {
+ it('propagates a rejected active-apps read instead of treating it as no apps', async () => {
+ getActiveApps.mockRejectedValueOnce(new Error('app inventory unavailable'))
+ mockSchedule({ tasks: { 'release-check': { type: 'on-demand', enabled: true, runAfter: [] } } })
+ await expect(getUpcomingTasks(50)).rejects.toThrow('app inventory unavailable')
+ })
+
+ it('propagates a rejected app-override read instead of treating it as no overrides', async () => {
+ getActiveApps.mockResolvedValueOnce([{ id: 'app-1', name: 'Acme' }])
+ getAppTaskTypeOverrides.mockRejectedValueOnce(new Error('app overrides unavailable'))
+ mockSchedule({ tasks: { 'release-check': { type: 'on-demand', enabled: true, runAfter: [] } } })
+ await expect(getUpcomingTasks(50)).rejects.toThrow('app overrides unavailable')
+ })
+
+ it('propagates a rejected per-app readiness read instead of treating the app as not-ready', async () => {
+ getActiveApps.mockResolvedValueOnce([{ id: 'app-1', name: 'Acme' }])
+ getAppTaskTypeOverrides.mockResolvedValueOnce({
+ 'release-check': { enabled: true, interval: '15 9 * * *' }
+ })
+ isTaskTypeEnabledForApp.mockRejectedValueOnce(new Error('app readiness unavailable'))
+ mockSchedule({ tasks: { 'release-check': { type: 'on-demand', enabled: true, runAfter: [] } } })
+ await expect(getUpcomingTasks(50)).rejects.toThrow('app readiness unavailable')
+ })
+ })
+
describe('getScheduleStatus — appSchedules', () => {
// vi.clearAllMocks() keeps a mockResolvedValue, so these cases restore the
// apps.js factory defaults rather than leaking an app roster into the