Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(scheduler): reject malformed cron expressions safely (#2122)

mengfanyu9410-hub4fd0926d646c
diff --git a/packages/maker-scheduler/src/__tests__/cron.test.ts b/packages/maker-scheduler/src/__tests__/cron.test.ts
index c033051e7f..71c0ef58d4 100644
--- a/packages/maker-scheduler/src/__tests__/cron.test.ts
+++ b/packages/maker-scheduler/src/__tests__/cron.test.ts
@@ -31,6 +31,11 @@ describe('parseCron', () => {
expect(p.dayOfWeek).toEqual([0]);
});
+ it('expands dayOfWeek steps through the Sunday alias 7', () => {
+ expect(parseCron('0 0 * * 7/2').dayOfWeek).toEqual([0]);
+ expect(parseCron('0 0 * * 5/2').dayOfWeek).toEqual([0, 5]);
+ });
+
it('rejects out-of-range minute', () => {
expect(() => parseCron('60 * * * *')).toThrow();
});
@@ -39,6 +44,13 @@ describe('parseCron', () => {
expect(() => parseCron('* * * *')).toThrow();
expect(() => parseCron('* * * * * *')).toThrow();
});
+
+ it('rejects malformed numeric field segments instead of partially parsing them', () => {
+ expect(() => parseCron('5abc * * * *')).toThrow();
+ expect(() => parseCron('*/5abc * * * *')).toThrow();
+ expect(() => parseCron('1-2-3 * * * *')).toThrow();
+ expect(() => parseCron('1/2/3 * * * *')).toThrow();
+ });
});
describe('nextRun', () => {
diff --git a/packages/maker-scheduler/src/__tests__/scheduler.test.ts b/packages/maker-scheduler/src/__tests__/scheduler.test.ts
index 69439376ef..a030222643 100644
--- a/packages/maker-scheduler/src/__tests__/scheduler.test.ts
+++ b/packages/maker-scheduler/src/__tests__/scheduler.test.ts
@@ -648,6 +648,153 @@ describe('Scheduler', () => {
await h.scheduler.stop();
});
+ it('start() isolates legacy invalid interval cron records instead of blocking valid schedules', async () => {
+ const warn = vi.fn();
+ const local = makeHarness({ logger: { warn } });
+ local.storage.schedules.set('legacy-invalid', {
+ id: 'legacy-invalid',
+ name: 'legacy invalid cron',
+ prompt: 'p',
+ kind: 'cron',
+ cronExpr: '5abc * * * *',
+ timezone: 'UTC',
+ recurring: true,
+ manual: false,
+ intervalMs: 5 * 60_000,
+ agentKind: 'claude-code',
+ workspaceKind: 'project',
+ useWorktree: false,
+ notify: { desktop: false, feishu: false },
+ status: 'active',
+ createdAt: 0,
+ updatedAt: 0,
+ nextFireAt: Date.UTC(2020, 0, 1, 0, 0, 0),
+ });
+ local.storage.schedules.set('valid', {
+ id: 'valid',
+ name: 'valid cron',
+ prompt: 'p',
+ kind: 'cron',
+ cronExpr: '0 9 * * *',
+ timezone: 'UTC',
+ recurring: true,
+ manual: false,
+ agentKind: 'claude-code',
+ workspaceKind: 'project',
+ useWorktree: false,
+ notify: { desktop: false, feishu: false },
+ status: 'active',
+ createdAt: 0,
+ updatedAt: 0,
+ nextFireAt: Date.UTC(2020, 0, 1, 0, 0, 0),
+ });
+
+ await expect(local.scheduler.start()).resolves.toBeUndefined();
+
+ expect((await local.storage.get('legacy-invalid'))?.nextFireAt).toBeUndefined();
+ expect((await local.storage.get('valid'))?.nextFireAt).toBe(
+ Date.UTC(2026, 0, 1, 9, 0, 0),
+ );
+ expect(warn).toHaveBeenCalledWith(
+ 'scheduler: skipped invalid active schedule during startup',
+ expect.objectContaining({ scheduleId: 'legacy-invalid' }),
+ );
+
+ await local.scheduler.stop();
+ });
+
+ it('keeps a legacy invalid cron quarantined when clearing its stale fire time fails', async () => {
+ const local = makeHarness({ logger: { warn: vi.fn() } });
+ const staleFireAt = Date.UTC(2020, 0, 1, 0, 0, 0);
+ local.storage.schedules.set('legacy-invalid', {
+ id: 'legacy-invalid',
+ name: 'legacy invalid cron',
+ prompt: 'p',
+ kind: 'cron',
+ cronExpr: '5abc * * * *',
+ timezone: 'UTC',
+ recurring: true,
+ manual: false,
+ agentKind: 'claude-code',
+ workspaceKind: 'project',
+ useWorktree: false,
+ notify: { desktop: false, feishu: false },
+ status: 'active',
+ createdAt: 0,
+ updatedAt: 0,
+ nextFireAt: staleFireAt,
+ });
+ vi.spyOn(local.storage, 'update').mockRejectedValueOnce(new Error('database is locked'));
+
+ await local.scheduler.start();
+ expect((await local.storage.get('legacy-invalid'))?.nextFireAt).toBe(staleFireAt);
+
+ local.clock.advance(30_000);
+ await local.scheduler.tick();
+
+ expect(local.runner.fire).not.toHaveBeenCalled();
+ expect(await local.scheduler.listRuns('legacy-invalid')).toHaveLength(0);
+ await local.scheduler.stop();
+ });
+
+ it('quarantines an invalid interval cron first discovered during periodic DB sync', async () => {
+ const local = makeHarness({ logger: { warn: vi.fn() } });
+ await local.scheduler.start();
+ local.storage.schedules.set('late-invalid', {
+ id: 'late-invalid',
+ name: 'late invalid cron',
+ prompt: 'p',
+ kind: 'cron',
+ cronExpr: '5abc * * * *',
+ timezone: 'UTC',
+ recurring: true,
+ manual: false,
+ intervalMs: 5 * 60_000,
+ agentKind: 'claude-code',
+ workspaceKind: 'project',
+ useWorktree: false,
+ notify: { desktop: false, feishu: false },
+ status: 'active',
+ createdAt: 0,
+ updatedAt: 0,
+ nextFireAt: Date.UTC(2020, 0, 1, 0, 0, 0),
+ });
+
+ local.clock.advance(30_000);
+ await local.scheduler.tick();
+
+ expect(local.runner.fire).not.toHaveBeenCalled();
+ expect(await local.scheduler.listRuns('late-invalid')).toHaveLength(0);
+
+ await local.storage.update('late-invalid', {
+ cronExpr: '* * * * *',
+ nextFireAt: local.clock.now(),
+ });
+ local.clock.advance(30_000);
+ await local.scheduler.tick();
+
+ expect(local.runner.fire).toHaveBeenCalledTimes(1);
+ await local.scheduler.stop();
+ });
+
+ it('does not execute a schedule whose cron becomes malformed after cache sync but before due-fire claim', async () => {
+ const local = makeHarness({ logger: { warn: vi.fn() } });
+ await local.scheduler.start();
+ const sch = await local.scheduler.create({ ...baseInput, intervalMs: 10_000 });
+
+ // Simulate a second instance writing invalid metadata while retaining the
+ // same due time. The first instance still has the valid cached copy and
+ // reaches claimDueFire before its 30s DB refresh.
+ await local.storage.update(sch.id, { cronExpr: '5abc * * * *' });
+ local.clock.advance(10_000);
+ await local.scheduler.tick();
+
+ expect(local.runner.fire).not.toHaveBeenCalled();
+ expect(await local.scheduler.listRuns(sch.id)).toHaveLength(0);
+ expect((await local.storage.get(sch.id))?.nextFireAt).toBeUndefined();
+ await local.scheduler.stop();
+ });
+
// ── intervalMs("上次完成 + N" 语义)──
// 这条线和 cron-槽位 完全分支:fireOne / start / resume / create 都要分别覆盖。
@@ -658,6 +805,61 @@ describe('Scheduler', () => {
expect(sch.intervalMs).toBe(5 * 60_000);
});
+ it('create() rejects invalid cron metadata even when intervalMs controls the first fire', async () => {
+ await expect(h.scheduler.create({
+ ...baseInput,
+ cronExpr: '5abc * * * *',
+ intervalMs: 5 * 60_000,
+ })).rejects.toThrow();
+ expect(h.storage.schedules.size).toBe(0);
+ });
+
+ it('rejects enabling a legacy manual interval schedule with malformed cron metadata', async () => {
+ const schedule = await h.scheduler.create({
+ ...baseInput,
+ manual: true,
+ intervalMs: 5 * 60_000,
+ });
+ await h.storage.update(schedule.id, { cronExpr: '5abc * * * *' });
+
+ await expect(h.scheduler.update(schedule.id, { manual: false })).rejects.toThrow();
+ expect(await h.storage.get(schedule.id)).toMatchObject({
+ manual: true,
+ cronExpr: '5abc * * * *',
+ });
+ });
+
+ it('rejects reactivating an expired interval schedule with malformed cron metadata', async () => {
+ const schedule = await h.scheduler.create({
+ ...baseInput,
+ intervalMs: 5 * 60_000,
+ });
+ await h.storage.update(schedule.id, {
+ status: 'expired',
+ cronExpr: '5abc * * * *',
+ });
+
+ await expect(h.scheduler.update(schedule.id, { name: 'try to reactivate' })).rejects.toThrow();
+ expect(await h.storage.get(schedule.id)).toMatchObject({
+ status: 'expired',
+ cronExpr: '5abc * * * *',
+ name: schedule.name,
+ });
+ });
+
+ it('resume() keeps an interval schedule paused when legacy cron metadata is invalid', async () => {
+ const sch = await h.scheduler.create({
+ ...baseInput,
+ cronExpr: '*/10 * * * *',
+ intervalMs: 10 * 60_000,
+ });
+ await h.scheduler.pause(sch.id);
+ await h.storage.update(sch.id, { cronExpr: '5abc * * * *' });
+
+ await expect(h.scheduler.resume(sch.id)).rejects.toThrow();
+ expect((await h.storage.get(sch.id))?.status).toBe('paused');
+ });
+
it('intervalMs recurring fire schedules nextFireAt at finishedAt + intervalMs', async () => {
const sch = await h.scheduler.create({ ...baseInput, intervalMs: 30 * 60_000 });
// 触发到 next: 00:30:30, runner 立即 resolve(同一时刻 finishedAt = firedAt)
@@ -830,6 +1032,31 @@ describe('Scheduler', () => {
expect(after?.nextFireAt).toBe(Date.UTC(2026, 0, 1, 0, 11, 0));
});
+ it('rejects an invalid cronExpr update even when interval scheduling remains authoritative', async () => {
+ const sch = await h.scheduler.create({
+ ...baseInput,
+ cronExpr: '*/10 * * * *',
+ intervalMs: 10 * 60_000,
+ });
+
+ await expect(h.scheduler.update(sch.id, { cronExpr: '5abc * * * *' })).rejects.toThrow();
+
+ const stored = await h.storage.get(sch.id);
+ expect(stored).toMatchObject({
+ cronExpr: '*/10 * * * *',
+ intervalMs: 10 * 60_000,
+ });
+ });
+
+ it('rejects interval-only re-arms when legacy cron metadata is malformed', async () => {
+ const sch = await h.scheduler.create({ ...baseInput, intervalMs: 10 * 60_000 });
+ await h.storage.update(sch.id, { cronExpr: '5abc * * * *' });
+ const before = await h.storage.get(sch.id);
+
+ await expect(h.scheduler.update(sch.id, { intervalMs: 5 * 60_000 })).rejects.toThrow();
+ expect(await h.storage.get(sch.id)).toEqual(before);
+ });
+
it('update(prompt only) leaves intervalMs and nextFireAt completely untouched', async () => {
// 2026-07-29 #211 事故形态的回归:改 prompt 绝不能动 interval 语义
const sch = await h.scheduler.create({ ...baseInput, cronExpr: '*/10 * * * *', intervalMs: 10 * 60_000 });
diff --git a/packages/maker-scheduler/src/engine/cron.ts b/packages/maker-scheduler/src/engine/cron.ts
index 7de5d624a9..a76a8b2da6 100644
--- a/packages/maker-scheduler/src/engine/cron.ts
+++ b/packages/maker-scheduler/src/engine/cron.ts
@@ -58,10 +58,14 @@ function parseField(token: string, range: FieldRange, allowDowSeven = false): nu
if (part.length === 0) {
throw new Error(`Empty cron field segment in "${token}"`);
}
- const [rangePart, stepPart] = part.split('/');
+ const stepSegments = part.split('/');
+ if (stepSegments.length > 2) {
+ throw new Error(`Invalid step syntax in "${part}"`);
+ }
+ const [rangePart, stepPart] = stepSegments;
let step = 1;
if (stepPart !== undefined) {
- step = parseInt(stepPart, 10);
+ step = parseDecimalInteger(stepPart);
if (!Number.isInteger(step) || step <= 0) {
throw new Error(`Invalid step "${stepPart}" in "${part}"`);
}
@@ -72,20 +76,24 @@ function parseField(token: string, range: FieldRange, allowDowSeven = false): nu
lo = range.min;
hi = range.max;
} else if (rangePart.includes('-')) {
- const [aStr, bStr] = rangePart.split('-');
- lo = parseInt(aStr, 10);
- hi = parseInt(bStr, 10);
+ const rangeSegments = rangePart.split('-');
+ if (rangeSegments.length !== 2) {
+ throw new Error(`Invalid range "${rangePart}" in "${part}"`);
+ }
+ const [aStr, bStr] = rangeSegments;
+ lo = parseDecimalInteger(aStr);
+ hi = parseDecimalInteger(bStr);
if (!Number.isInteger(lo) || !Number.isInteger(hi) || lo > hi) {
throw new Error(`Invalid range "${rangePart}" in "${part}"`);
}
} else {
- const v = parseInt(rangePart, 10);
+ const v = parseDecimalInteger(rangePart);
if (!Number.isInteger(v)) {
throw new Error(`Invalid value "${rangePart}" in "${part}"`);
}
lo = v;
// "N/S" expands as "N,N+S,N+2S,...,max"
- hi = stepPart !== undefined ? range.max : v;
+ hi = stepPart !== undefined ? effectiveMax : v;
}
if (lo < range.min || hi > effectiveMax) {
throw new Error(`Field "${part}" out of range [${range.min}, ${effectiveMax}]`);
@@ -98,6 +106,10 @@ function parseField(token: string, range: FieldRange, allowDowSeven = false): nu
return [...out].sort((a, b) => a - b);
}
+function parseDecimalInteger(value: string): number {
+ return /^\d+$/.test(value) ? Number(value) : Number.NaN;
+}
+
// ---------- timezone helpers ----------
const FORMATTER_CACHE = new Map<string, Intl.DateTimeFormat>();
diff --git a/packages/maker-scheduler/src/engine/scheduler.ts b/packages/maker-scheduler/src/engine/scheduler.ts
index ba8bed2fc4..302e36938c 100644
--- a/packages/maker-scheduler/src/engine/scheduler.ts
+++ b/packages/maker-scheduler/src/engine/scheduler.ts
@@ -362,6 +362,11 @@ export class Scheduler extends EventEmitter {
* 只存内存:真到了重启,start() 的归一本来就会补上。
*/
private readonly pendingReplans = new Map<string, StalledClaimPlan>();
+ /**
+ * 严格 cron 解析上线前可能落库的畸形 active 任务。清空 nextFireAt 若遇到存储故障,
+ * 周期 DB 同步仍会读回旧的到期时间;在用户修正表达式前必须持续把它们隔离在内存里。
+ */
+ private readonly invalidScheduleIds = new Set<string>();
constructor(opts: SchedulerOptions) {
super();
@@ -403,6 +408,9 @@ export class Scheduler extends EventEmitter {
async start(): Promise<void> {
if (this.started) return;
+ // 隔离名单只描述本次运行周期里看到的存量坏记录。stop() 后再 start()
+ // 必须从持久化事实重新判定,不能把已删除或已修正任务的 id 带进新周期。
+ this.invalidScheduleIds.clear();
// 被动模式:不装 tick 时钟、不做僵尸清理(可能误伤另一个活跃实例正在跑的
// run)、不预载 activeSchedules(反正不 tick)。CRUD / runNow 照常可用。
if (this.passive) {
@@ -443,7 +451,32 @@ export class Scheduler extends EventEmitter {
// 节奏(cron 后续怎么改都不生效)。迁移已于 2026-05 上线并跑了一个月,存量
// 老任务均已转换完,该逻辑只剩误伤,故移除。
let current = sch;
- const next = computeNextFireAt(current, now);
+ let next: number | undefined;
+ try {
+ next = computeNextFireAt(current, now);
+ this.invalidScheduleIds.delete(current.id);
+ } catch (err) {
+ // 旧版本曾接受 parseInt 可部分解析的畸形 cron(例如 `5abc * * * *`)。
+ // 升级后严格解析会拒绝它们,但一条存量坏记录不能让整个 scheduler 启动失败。
+ // 清空旧的 nextFireAt,保留记录供用户修正;内存副本同样禁用,避免陈旧时间误触发。
+ this.logger?.warn?.('scheduler: skipped invalid active schedule during startup', {
+ scheduleId: current.id,
+ error: String(err),
+ });
+ this.invalidScheduleIds.add(current.id);
+ try {
+ const updated = await this.storage.update(current.id, { nextFireAt: undefined });
+ current = updated ?? { ...current, nextFireAt: undefined };
+ } catch (clearErr) {
+ current = { ...current, nextFireAt: undefined };
+ this.logger?.warn?.('scheduler: failed to clear invalid schedule nextFireAt', {
+ scheduleId: current.id,
+ error: String(clearErr),
+ });
+ }
+ this.activeSchedules.set(current.id, current);
+ continue;
+ }
if (next !== current.nextFireAt) {
const updated = await this.storage.update(current.id, { nextFireAt: next });
if (updated) current = updated;
@@ -523,8 +556,23 @@ export class Scheduler extends EventEmitter {
this.lastDbSyncAt = now;
try {
const actives = await this.storage.listActive();
+ const previousSchedules = new Map(this.activeSchedules);
this.activeSchedules.clear();
- for (const sch of actives) this.activeSchedules.set(sch.id, sch);
+ const activeIds = new Set(actives.map((sch) => sch.id));
+ for (const scheduleId of this.invalidScheduleIds) {
+ if (!activeIds.has(scheduleId)) this.invalidScheduleIds.delete(scheduleId);
+ }
+ for (const sch of actives) {
+ const previous = previousSchedules.get(sch.id);
+ const cadenceChanged =
+ !previous ||
+ previous.cronExpr !== sch.cronExpr ||
+ previous.timezone !== sch.timezone ||
+ previous.intervalMs !== sch.intervalMs ||
+ previous.manual !== sch.manual;
+ const current = this.keepInvalidScheduleQuarantined(sch, now, cadenceChanged);
+ this.activeSchedules.set(current.id, current);
+ }
} catch (err) {
this.logger?.warn?.('scheduler: active-schedule DB sync failed', err);
}
@@ -640,6 +688,22 @@ export class Scheduler extends EventEmitter {
return;
}
schedule = claimed;
+ // The CAS protects the fire time, not the rest of the row. Another
+ // instance can therefore change cron metadata while retaining the same
+ // nextFireAt and still return its new row here. Validate the claimed
+ // source of truth before creating a run so that 30-second cache windows
+ // cannot execute a newly malformed schedule once.
+ try {
+ computeNextFireAt(schedule, this.clock.now());
+ this.invalidScheduleIds.delete(schedule.id);
+ } catch (err) {
+ this.invalidScheduleIds.add(schedule.id);
+ this.logger?.warn?.('scheduler: quarantined invalid schedule after due-fire claim', {
+ scheduleId: schedule.id,
+ error: String(err),
+ });
+ return;
+ }
}
this.updateInflightAttempt(runId, 'persisting');
const firedAt = this.clock.now();
@@ -1171,6 +1235,10 @@ export class Scheduler extends EventEmitter {
const now = this.clock.now();
const id = this.generateId();
const manual = input.manual ?? false;
+ // intervalMs 只决定下一次何时触发,不会让 cronExpr / timezone 变成可跳过的
+ // 元数据。否则用户能先持久化一个坏表达式,等未来清掉 intervalMs 时才在调度
+ // 路径报错。此处纯校验,不影响 interval 的 now + N 首次触发语义。
+ nextCronOrMonthlyFire(input.cronExpr, now, input.timezone);
// 首次 nextFireAt:
// - manual → undefined(永不自动 fire)
// - intervalMs 设了 → createdAt + intervalMs(让"每 N 分钟"有 N 分钟暖场期)
@@ -1276,6 +1344,19 @@ export class Scheduler extends EventEmitter {
if (shouldReactivateExpired) {
updates.status = 'active';
}
+ // cronExpr 即使暂时被 intervalMs 覆盖,也会在调用方显式清除 interval 后重新
+ // 成为调度依据。不能让一次 interval 模式更新把畸形 cron 持久化,留到以后才
+ // 在重排或启动时爆炸;timezone 变更同样需要验证现有表达式在新时区可解析。
+ const intervalKeyPresent = Object.prototype.hasOwnProperty.call(patch, 'intervalMs');
+ if (
+ patch.cronExpr !== undefined ||
+ patch.timezone !== undefined ||
+ patch.manual === false ||
+ intervalKeyPresent ||
+ shouldReactivateExpired
+ ) {
+ nextCronOrMonthlyFire(candidate.cronExpr, now, candidate.timezone);
+ }
// manual / intervalMs / cronExpr / timezone 任一变化,或 expired 恢复 active 时,
// 都要重算 nextFireAt:
// - manual:true → 强制清空 nextFireAt(不再自动 fire)
@@ -1283,7 +1364,6 @@ export class Scheduler extends EventEmitter {
// - manual:false 且 触发字段没动 → nextFireAt 保留(避免 update 副作用)
// intervalMs 按「key 是否在场」判定而不是「值是否 undefined」:显式清空
// (key 在、值 undefined)同样是触发字段变化,必须重算回 cron 槽位。
- const intervalKeyPresent = Object.prototype.hasOwnProperty.call(patch, 'intervalMs');
const needsRecompute =
patch.cronExpr !== undefined ||
patch.timezone !== undefined ||
@@ -1328,8 +1408,9 @@ export class Scheduler extends EventEmitter {
const updated = await this.storage.update(id, updates);
if (!updated) throw new Error(`Schedule not found: ${id}`);
if (updated.status === 'active') {
- this.activeSchedules.set(id, updated);
+ this.activeSchedules.set(id, this.keepInvalidScheduleQuarantined(updated, now));
} else {
+ this.invalidScheduleIds.delete(id);
this.activeSchedules.delete(id);
}
// DEBUG: 帮排查"编辑后 pending fire 没刷新"问题;只在触发字段变更时打。
@@ -1363,6 +1444,7 @@ export class Scheduler extends EventEmitter {
await this.abortInflightAndWait(id, opts?.exemptRunId);
const updated = await this.storage.update(id, { status: 'paused', updatedAt: this.clock.now() });
if (!updated) throw new Error(`Schedule not found: ${id}`);
+ this.invalidScheduleIds.delete(id);
this.activeSchedules.delete(id);
this.emitEvent({ type: 'changed', scheduleId: id });
return updated;
@@ -1376,6 +1458,9 @@ export class Scheduler extends EventEmitter {
const existing = await this.storage.get(id);
if (!existing) throw new Error(`Schedule not found: ${id}`);
const now = this.clock.now();
+ // 与 create/update 对齐:恢复 interval 任务前也验证它保留的 cron 元数据,不能
+ // 重新激活一条未来清 interval 后必坏的记录。
+ nextCronOrMonthlyFire(existing.cronExpr, now, existing.timezone);
// resume 视作冷启动:interval 模式起新一轮 N 倒计时(从 now 起算,与 update() 一致);
// cron 模式找下一个壁钟槽位。不要复用 nextIntervalFire —— 它按 lastFinishedAt+N 尊重原
// 节奏(restart 语义),会让「上次完成不到一个 N 就 resume」比冷启动更早触发。
@@ -1389,6 +1474,7 @@ export class Scheduler extends EventEmitter {
nextFireAt: next,
});
if (!updated) throw new Error(`Schedule not found: ${id}`);
+ this.invalidScheduleIds.delete(id);
this.activeSchedules.set(id, updated);
this.emitEvent({ type: 'changed', scheduleId: id });
return updated;
@@ -1398,6 +1484,29 @@ export class Scheduler extends EventEmitter {
return this.serializeScheduleMutation(id, () => this.deleteUnlocked(id, opts));
}
+ private keepInvalidScheduleQuarantined(
+ schedule: Schedule,
+ now: number,
+ validate = false,
+ ): Schedule {
+ const wasKnownInvalid = this.invalidScheduleIds.has(schedule.id);
+ if (!validate && !wasKnownInvalid) return schedule;
+ try {
+ computeNextFireAt(schedule, now);
+ this.invalidScheduleIds.delete(schedule.id);
+ return schedule;
+ } catch (err) {
+ this.invalidScheduleIds.add(schedule.id);
+ if (!wasKnownInvalid) {
+ this.logger?.warn?.('scheduler: quarantined invalid active schedule during DB sync', {
+ scheduleId: schedule.id,
+ error: String(err),
+ });
+ }
+ return { ...schedule, nextFireAt: undefined };
+ }
+ }
+
private async deleteUnlocked(id: string, opts?: { exemptRunId?: string }): Promise<void> {
// 先中断 in-flight,等它们 settle,再删 schedule 行。否则被删 schedule 名下的
// in-flight run 会继续跑到底(原行为),用户点删除后看到的是"还在跑"。
@@ -1412,6 +1521,7 @@ export class Scheduler extends EventEmitter {
// fireOne 尾部对 schedule 行的重排 update 同样 no-op —— 均无副作用。
await this.abortInflightAndWait(id, opts?.exemptRunId);
await this.storage.delete(id);
+ this.invalidScheduleIds.delete(id);
this.activeSchedules.delete(id);
this.emitEvent({ type: 'changed', scheduleId: id });
}
@@ -2700,6 +2810,10 @@ function computeNextFireAt(schedule: Schedule, fromMs: number): number | undefin
// manual schedule 永远不参与自动触发,跳过 cron 计算(runNow 是单独路径)
if (schedule.manual) return undefined;
if (!schedule.recurring && schedule.lastFiredAt !== undefined) return undefined;
+ // interval schedules still persist cron metadata. Validate it before taking
+ // the interval fast path so legacy rows accepted by older parsers cannot
+ // evade startup/DB-sync quarantine and fire from a stale nextFireAt.
+ nextCronOrMonthlyFire(schedule.cronExpr, fromMs, schedule.timezone);
if (schedule.intervalMs !== undefined) {
// 冷启动:基线取 lastFinishedAt(跑过)或 createdAt(没跑过),再 max(base+N, now+N)
// —— 漏掉的不补发,重新起 N 倒计时。