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

Scheduler: join an in-flight run instead of starting a second one

[._.]/ Adam Eivy8d6cb130c187
diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.js
index 36c7e51d63..d11e640fc4 100644
--- a/server/services/eventScheduler.js
+++ b/server/services/eventScheduler.js
@@ -394,7 +394,11 @@ function schedule(config) {
active: true,
lastRunSucceeded: null,
lastError: null,
- consecutiveFailures: 0
+ consecutiveFailures: 0,
+ // The promise of the run in progress, or null. One run per event at a
+ // time: a trigger that lands mid-run joins it instead of starting a
+ // second handler over the same state (#12022).
+ inFlight: null
}
// Calculate next run time
@@ -553,10 +557,26 @@ function recordEventHistory(event, { startTime, success, error }) {
}
/**
- * Run an event
+ * Run an event, or join the run already in flight for it. Only `runBackup`
+ * guards itself; every other handler relies on this latch to never execute
+ * twice concurrently.
* @param {Object} event - Event object
+ * @returns {Promise<void>}
*/
-async function runEvent(event) {
+function runEvent(event) {
+ if (event.inFlight) return event.inFlight
+ event.inFlight = executeEvent(event).finally(() => {
+ event.inFlight = null
+ })
+ return event.inFlight
+}
+
+/**
+ * Execute an event's handler once and record the outcome. Callers go through
+ * `runEvent`, which owns the in-flight latch.
+ * @param {Object} event - Event object
+ */
+async function executeEvent(event) {
const startTime = Date.now()
event.lastRunAt = startTime
@@ -776,14 +796,23 @@ function cancelAll() {
}
/**
- * Trigger an event immediately (for testing or manual runs)
+ * Trigger an event immediately (for testing or manual runs). A trigger that
+ * lands while the event's timer run is still in flight joins that run rather
+ * than starting a second one, and resolves once it finishes.
* @param {string} id - Event identifier
- * @returns {Promise<boolean>} - True if event was found and triggered
+ * @returns {Promise<boolean|{ joined: true }>} - `false` for an unknown id,
+ * `true` when this call ran the handler, `{ joined: true }` when it waited
+ * on a run already in progress.
*/
async function triggerNow(id) {
const event = scheduledEvents.get(id)
if (!event) return false
+ if (event.inFlight) {
+ await event.inFlight
+ return { joined: true }
+ }
+
// Disarm before running: a long manual run must not have its own pending
// deadline elapse underneath it and start a second, concurrent run.
clearPendingTimer(id)
diff --git a/server/services/eventScheduler.test.js b/server/services/eventScheduler.test.js
index 1249ee68cc..42724d8743 100644
--- a/server/services/eventScheduler.test.js
+++ b/server/services/eventScheduler.test.js
@@ -409,6 +409,32 @@ describe('schedule() lifecycle with fake timers', () => {
expect(await triggerNow('does-not-exist')).toBe(false);
});
+ it('triggerNow() mid-run joins the in-flight timer run instead of starting a second handler (#12022)', async () => {
+ let release;
+ const handler = vi.fn(() => new Promise(resolve => { release = resolve; }));
+ schedule({ id: 'trigger-join', type: 'interval', intervalMs: 60000, handler });
+
+ // The timer starts the run; "Run now" lands while it is still executing.
+ await vi.advanceTimersByTimeAsync(60000);
+ expect(handler).toHaveBeenCalledTimes(1);
+ const manual = triggerNow('trigger-join');
+ const secondManual = triggerNow('trigger-join');
+ await Promise.resolve();
+ expect(handler).toHaveBeenCalledTimes(1);
+
+ release();
+ expect(await manual).toEqual({ joined: true });
+ expect(await secondManual).toEqual({ joined: true });
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(getEvent('trigger-join').runCount).toBe(1);
+ expect(getHistory({ eventId: 'trigger-join' })).toHaveLength(1);
+
+ // The latch releases with the run: the next trigger executes again.
+ handler.mockResolvedValue(undefined);
+ expect(await triggerNow('trigger-join')).toBe(true);
+ expect(handler).toHaveBeenCalledTimes(2);
+ });
+
it('records a failed handler in history without deactivating a recurring event', async () => {
const handler = vi.fn().mockRejectedValue(new Error('boom'));
schedule({ id: 'fail-1', type: 'interval', intervalMs: 5000, handler });