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(scheduler): prevent CPU spin on invalid cron expressions

Adam Eivy4534ab134233
diff --git a/.changelog/v0.16.x.md b/.changelog/v0.16.x.md
index 7b4f0d02f7..0a410d8a1b 100644
--- a/.changelog/v0.16.x.md
+++ b/.changelog/v0.16.x.md
@@ -61,6 +61,11 @@ Agent persistence, reliability, and decision transparency improvements.
- **Added turn-limit and billing-error patterns** -- new error categories for agents hitting turn budget limits and provider billing/subscription issues
- **Wait time extraction improved** -- now parses "resets Xam/pm" format in addition to "try again in..." for usage limit cooldown times
+### Cron parser no longer CPU-spins on invalid expressions
+- **Previously**, an invalid cron expression (e.g., month=13) caused the minute-by-minute search loop to iterate ~1 million times with no match, spinning the CPU for seconds
+- **Added upfront field validation** -- before entering the loop, each cron field is checked against its valid range (minutes 0-59, hours 0-23, day 1-31, month 1-12, day-of-week 0-7); out-of-range values return `null` immediately
+- **Added iteration safety cap** -- even for valid-but-unmatchable expressions, the loop now breaks after 525,960 iterations (1 year in minutes) instead of running for the full 2-year window
+
### Fixed byModelTier data corruption in task type reset
- **Model tier metrics drifted from reality** -- `resetTaskTypeLearning()` subtracted counts from `byTaskType`, `errorPatterns`, `routingAccuracy`, and `totals`, but never touched `byModelTier`; after rehabilitation resets, the heavy tier showed 653 completed / 3 succeeded (0.46% success) due to accumulated historical data that was cleared from other structures but not from tier metrics
- **Now subtracts routing accuracy data from byModelTier** -- when a task type is reset, its per-tier succeeded/failed counts are decremented from the corresponding `byModelTier` entries, with duration estimated proportionally from the task type's average
diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.js
index 54f34d4183..964604f73f 100644
--- a/server/services/eventScheduler.js
+++ b/server/services/eventScheduler.js
@@ -20,6 +20,24 @@ const activeTimers = new Map()
const eventHistory = []
const MAX_HISTORY = 500
+/**
+ * Validate that all numeric values in a cron field fall within the allowed range
+ * @param {string} expr - Cron field expression
+ * @param {number} min - Minimum allowed value
+ * @param {number} max - Maximum allowed value
+ * @returns {boolean} - True if all values are within range
+ */
+function validateCronFieldRange(expr, min, max) {
+ if (expr === '*') return true
+
+ // Extract all numeric values from the expression
+ const nums = expr.split(/[,\-\/]/).filter(p => p !== '*').map(Number)
+ return nums.every(n => !isNaN(n) && n >= min && n <= max)
+}
+
+// Maximum iterations for cron search loop (1 year in minutes)
+const MAX_CRON_ITERATIONS = 525960
+
/**
* Parse cron expression to next execution time
* Supports: minute hour dayOfMonth month dayOfWeek
@@ -31,7 +49,7 @@ const MAX_HISTORY = 500
*
* @param {string} cronExpr - Cron expression
* @param {Date} from - Starting point (default: now)
- * @returns {Date} - Next execution time
+ * @returns {Date|null} - Next execution time, or null if invalid/no match
*/
function parseCronToNextRun(cronExpr, from = new Date()) {
const parts = cronExpr.trim().split(/\s+/)
@@ -41,6 +59,21 @@ function parseCronToNextRun(cronExpr, from = new Date()) {
const [minuteExpr, hourExpr, dayOfMonthExpr, monthExpr, dayOfWeekExpr] = parts
+ // Validate cron field ranges before entering the search loop
+ const fieldRanges = [
+ [minuteExpr, 0, 59, 'minute'],
+ [hourExpr, 0, 23, 'hour'],
+ [dayOfMonthExpr, 1, 31, 'dayOfMonth'],
+ [monthExpr, 1, 12, 'month'],
+ [dayOfWeekExpr, 0, 7, 'dayOfWeek']
+ ]
+ for (const [expr, min, max, name] of fieldRanges) {
+ if (!validateCronFieldRange(expr, min, max)) {
+ console.error(`❌ Invalid cron ${name} field "${expr}" in expression: ${cronExpr}`)
+ return null
+ }
+ }
+
// Simple implementation - find next matching time
const next = new Date(from)
next.setSeconds(0, 0)
@@ -50,7 +83,12 @@ function parseCronToNextRun(cronExpr, from = new Date()) {
const maxDate = new Date(from)
maxDate.setFullYear(maxDate.getFullYear() + 2)
+ let iterations = 0
while (next < maxDate) {
+ if (++iterations > MAX_CRON_ITERATIONS) {
+ console.error(`❌ Cron search exceeded ${MAX_CRON_ITERATIONS} iterations for: ${cronExpr}`)
+ return null
+ }
if (matchesCronField(next.getMonth() + 1, monthExpr) &&
matchesCronField(next.getDate(), dayOfMonthExpr) &&
matchesCronField(next.getDay(), dayOfWeekExpr) &&