cron: armLoop fires loops up to 59s early because the target is truncated down to the minute boundary

Open Beginner friendly
#2,849 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
75/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
node.js, typescript
Domain
cli, testing

Research direction

Read packages/cli/src/cron/scheduler.ts around armLoop and inspect the minute truncation and nextFireAt assignment. Run the reproduction command in the issue or the regression assertion in packages/cli/test/cron/scheduler.test.ts; verify that arming with a 60 second delay at second 59 never schedules earlier than 60 seconds and that nextFireTime() matches the reported time.

Written by the indexing model from the issue text.

Description

Description

armLoop in packages/cli/src/cron/scheduler.ts schedules a loop task by computing new Date(now + clamped * 1000) and then calling target.setUTCSeconds(0, 0), which truncates the target DOWN to the containing/next minute boundary. The guard if (target.getTime() <= now) target.setUTCMinutes(target.getUTCMinutes() + 1) only corrects truncation that lands in the past — it does nothing when the truncated minute boundary is still (barely) in the future.

Concretely: if a loop is armed at second 59 of a minute with delay_seconds: 60, the nominal target is 59s into the next minute, but truncation rewinds it to the next minute boundary — only ~1 second in the future. rt.nextFireAt.set(id, target.getTime()) then pins that early instant, so the loop fires up to 59 seconds earlier than requested, and the stored cron expression m h * * * is consistent with the early time (it never recomputes).

For a keepalive/idle-loop feature this means the model can be re-invoked almost immediately after arming a 60–3600s delay, defeating the delay and potentially causing a rapid-fire loop.

Plugins

N/A — core scheduler (packages/cli/src/cron/scheduler.ts).

MiMoCode version

main @ 75e1ed0b3b6561796bdfeb36edcf091f9793f24d

Steps to reproduce
  1. Pin Date.now() to 59,000ms after a minute boundary (i.e. xx:xx:59.000).
  2. Start the scheduler and call armLoop({ prompt: "loop", delay_seconds: 60, reason_length: 0 }).
  3. Observe res.scheduledFor - now is ~1,000ms instead of >= 60,000ms; nextFireTime() returns the same early instant.

Automated reproduction (runs the real armLoop under node:test; see packages/cli/test/cron/regression/):
node --import ./packages/cli/test/cron/regression/armloop-delay.register.mjs packages/cli/test/cron/regression/armloop-delay.regression.mjs — fails with armLoop(60s) scheduled only 1000ms in the future (armed at :59s).
The same assertion exists as a bun:test twin in packages/cli/test/cron/scheduler.test.ts.

Screenshot and/or share link

N/A

Operating System

Windows 11 (reproduced; platform-independent — UTC math)

Terminal

Windows Terminal

Executed reproduction

Baseline: 75e1ed0b3b6561796bdfeb36edcf091f9793f24d

{
  "argv": [
    "node",
    "--import",
    "./packages/cli/test/cron/regression/armloop-delay.register.mjs",
    "packages/cli/test/cron/regression/armloop-delay.regression.mjs"
  ],
  "exit_code": 1,
  "output": "✖ armLoop never fires earlier than delay_seconds (minute truncation) (9.6202ms)\nℹ tests 1\nℹ suites 0\nℹ pass 0\nℹ fail 1\nℹ cancelled 0\nℹ skipped 0\nℹ todo 0\nℹ duration_ms 14.9437\n\n✖ failing tests:\n\ntest at packages\\cli\\test\\cron\\regression\\armloop-delay.regression.mjs:45:1\n✖ armLoop never fires earlier than delay_seconds (minute truncation) (9.6202ms)\n  AssertionError [ERR_ASSERTION]: armLoop(60s) scheduled only 1000ms in the future (armed at :59s): minute truncation in armLoop fires the loop up to 59s early\n      at TestContext.<anonymous> (file:///C:/Users/lyp99/Documents/GitHub/oss-contributor/workspaces/XiaomiMiMo--MiMo-Code--hunt-source-befd8c45b46e7fe3f5e4eeb0/packages/cli/test/cron/regression/armloop-delay.regression.mjs:65:12)\n      at async Test.run (node:internal/test_runner/test:1409:7)\n      at async startSubtestAfterBootstrap (node:internal/test_runner/harness:387:3) {\n    generatedMessage: false,\n    code: 'ERR_ASSERTION',\n    actual: false,\n    expected: true,\n    operator: '==',\n    diff: 'simple'\n  }\n\n(node:1760) [DEP0205] DeprecationWarning: `module.register()` is deprecated. Use `module.registerHooks()` instead.\n(Use `node --trace-deprecation ...` to show where the warning was created)\n(node:1760) ExperimentalWarning: stripTypeScriptTypes is an experimental feature and might change at any time\n(Use `node --trace-warnings ...` to show where the warning was created)\n"
}

Regression test

diff --git a/packages/cli/test/cron/scheduler.test.ts b/packages/cli/test/cron/scheduler.test.ts
index 73de37b5..fc5c321c 100644
--- a/packages/cli/test/cron/scheduler.test.ts
+++ b/packages/cli/test/cron/scheduler.test.ts
@@ -1,4 +1,4 @@
-import { test, expect, beforeEach } from "bun:test"
+import { test, expect, beforeEach, spyOn } from "bun:test"
 import { Effect } from "effect"
 import { mkdtempSync, rmSync } from "fs"
 import { tmpdir } from "os"
@@ -121,6 +121,41 @@ test("armLoop clamps delay_seconds to [60, 3600]", async () => {
   rmSync(dir, { recursive: true, force: true })
 })
 
+// Regression: armLoop truncated `now + delay` DOWN to the minute boundary
+// (setUTCSeconds(0, 0)), so an arm issued mid-minute could pin nextFireAt
+// to an instant far earlier than delay_seconds — a 60s arm at second 59
+// fired ~1s later. A loop must never fire earlier than its requested delay.
+test("armLoop never fires earlier than delay_seconds (minute truncation)", async () => {
+  const dir = freshDir()
+  const minute = Math.floor(Date.now() / 60_000) * 60_000
+  const fixed = minute + 59_000 // arm at :59s — worst case for truncation
+  const spy = spyOn(Date, "now").mockReturnValue(fixed)
+  try {
+    await provided(
+      Effect.gen(function* () {
+        const sched = yield* Scheduler
+        yield* sched.start(baseStartOpts(dir))
+        try {
+          const res = yield* sched.armLoop({ prompt: "delay-bound", delay_seconds: 60, reason_length: 0 })
+          expect(res).not.toBe(null)
+          // Both `now + delay` and round-up-to-minute fixes satisfy this bound;
+          // the truncated baseline lands ~1s out and fails.
+          expect(res!.scheduledFor - fixed).toBeGreaterThanOrEqual(60_000)
+
+          // The pinned fire instant must agree with what was reported.
+          const next = yield* sched.nextFireTime()
+          expect(next).toBe(res!.scheduledFor)
+        } finally {
+          yield* sched.stop()
+        }
+      }),
+    )
+  } finally {
+    spy.mockRestore()
+  }
+  rmSync(dir, { recursive: true, force: true })
+})
+
 test("armLoop supersedes prior loop task for same prompt", async () => {
   const dir = freshDir()
   await provided(

New regression file: packages/cli/test/cron/regression/armloop-delay.regression.mjs
// Regression: armLoop must never schedule a loop fire EARLIER than the
// requested delay_seconds.
//
// Bug (packages/cli/src/cron/scheduler.ts): `armLoop` computes
//   const target = new Date(now + clamped * 1000)
//   target.setUTCSeconds(0, 0)            // truncates DOWN to the minute
//   if (target.getTime() <= now) ...      // only fixes truncation into the past
// Armed mid-minute (e.g. second 59), delay_seconds=60 nominally lands ~59s
// into the next minute; truncation rewinds target to the next minute
// boundary — only ~1s in the future — and `rt.nextFireAt` pins that early
// instant, so the loop fires up to 59s early.
//
// This file runs the REAL armLoop under `node:test` because no Bun binary is
// available in this environment (the repo suite uses bun:test). Only the
// `effect` primitives and sibling cron modules are stubbed via module hooks
// (see armloop-delay.hooks.mjs); the function under test is unmodified.
// A durable bun:test twin of this assertion lives in
// packages/cli/test/cron/scheduler.test.ts ("armLoop never fires earlier
// than delay_seconds (minute truncation)").
//
// Run from the repository root:
//   node --import ./packages/cli/test/cron/regression/armloop-delay.register.mjs packages/cli/test/cron/regression/armloop-delay.regression.mjs
// (the --import module installs the resolution hooks before this file loads;
// its specifier is resolved relative to the process cwd)

import { test } from "node:test"
import assert from "node:assert/strict"

// The dynamic imports below resolve `effect` and the scheduler module through
// the hooks installed by --import. Relative specifier resolves against THIS
// file, so only the --import path depends on cwd.
const { Effect } = await import("effect") // mapped to stub-effect.mjs
const { layer: schedulerLayer } = await import("../../../src/cron/scheduler.ts")

const startOpts = {
  workspaceRoot: "/tmp/armloop-regression",
  sessionID: "ses_regression",
  dir: "/tmp/armloop-regression",
  isLoading: () => true, // ticks stay inert; we invoke armLoop directly
  isKilled: () => false,
  onFire: () => {},
  onLoopEnded: () => {},
}

test("armLoop never fires earlier than delay_seconds (minute truncation)", async () => {
  const sched = schedulerLayer.make()

  // Pin the clock mid-minute: xx:xx:59.000. delay 60s then nominally lands
  // at xx:(x+1):59, which the baseline truncates to xx:(x+1):00 — ~1s away.
  const minute = Math.floor(Date.now() / 60000) * 60000
  const fixed = minute + 59_000
  const realNow = Date.now
  Date.now = () => fixed
  try {
    await Effect.runPromise(sched.start(startOpts))
    const res = await Effect.runPromise(
      sched.armLoop({ prompt: "regression-loop", delay_seconds: 60, reason_length: 0 }),
    )
    assert.ok(res, "armLoop returned null")

    const delayMs = res.scheduledFor - fixed
    // The oracle: a 60s arm must not fire in under 60s. Both an exact
    // `now + delay` fix and a round-UP-to-minute fix satisfy this; the
    // truncated baseline yields ~1_000ms here and fails.
    assert.ok(
      delayMs >= 60_000,
      `armLoop(60s) scheduled only ${delayMs}ms in the future (armed at :59s): ` +
        `minute truncation in armLoop fires the loop up to 59s early`,
    )

    // The pinned fire instant (what tick() actually waits on) must agree.
    const nextFire = await Effect.runPromise(sched.nextFireTime())
    assert.strictEqual(nextFire, res.scheduledFor)
  } finally {
    Date.now = realNow
    await Effect.runPromise(sched.stop())
  }
})

New regression file: packages/cli/test/cron/regression/armloop-delay.hooks.mjs
// Node module hooks that redirect scheduler.ts's bare/alias imports to the
// local stubs, so the REAL src/cron/scheduler.ts executes under plain Node
// (bun test is the repo's runner, but no Bun binary is available in this
// environment; only `effect` primitives and sibling cron modules are stubbed —
// `armLoop` itself runs unmodified).
import { readFile } from "node:fs/promises"
import { fileURLToPath } from "node:url"
import * as nodeModule from "node:module"

const dir = new URL("./", import.meta.url).href
const EFFECT_STUB = dir + "stub-effect.mjs"
const DEPS_STUB = dir + "stub-deps.mjs"

const STUBBED = new Set([
  "effect",
  "@/util",
  "./cron-task",
  "./cron-jitter",
  "./cron-lock",
  "./loop-state",
])

// Node >= 22.13 exposes stripTypeScriptTypes; >= 22.18 strips .ts natively.
// We handle .ts ourselves so the harness also works on versions where native
// stripping is off, and no-ops where the API is absent (native path used).
const strip = nodeModule.stripTypeScriptTypes

export const resolve = (specifier, context, next) => {
  if (specifier === "effect") {
    return { url: EFFECT_STUB, shortCircuit: true }
  }
  if (STUBBED.has(specifier)) {
    return { url: DEPS_STUB, shortCircuit: true }
  }
  return next(specifier, context)
}

export const load = async (url, context, next) => {
  if (url.endsWith(".ts") && typeof strip === "function") {
    const source = await readFile(fileURLToPath(url), "utf8")
    return { format: "module", source: strip(source), shortCircuit: true }
  }
  return next(url, context)
}

New regression file: packages/cli/test/cron/regression/armloop-delay.register.mjs
// Passed to `node --import` before the test file: installs the module
// resolution hooks that map scheduler.ts's imports onto the local stubs.
import { register } from "node:module"

register("./armloop-delay.hooks.mjs", import.meta.url)

New regression file: packages/cli/test/cron/regression/stub-effect.mjs
// Minimal Effect stand-in — enough surface for src/cron/scheduler.ts to load
// and run `armLoop` under plain Node (no `bun`, no installed node_modules).
// It implements only the API members that module actually calls:
//   Effect.gen, Effect.sync, Effect.succeed, Effect.promise,
//   Effect.orElseSucceed, Effect.runPromise, Layer.sync, Context.Service
// Anything else throws, so an accidental dependency on unstubbed machinery
// fails loudly instead of silently diverging.
//
// `yield* effect` semantics: scheduler.ts binds results like
//   const isOwner = yield* tryAcquireSchedulerLock(...)
// With `yield*`, the value sent into the outer generator by next(v) is
// forwarded into the sub-iterator, but the `yield*` expression evaluates to
// the sub-iterator's RETURN value. So each stub effect records its last run
// value in `__v` and returns it from its iterator, making
// `const x = yield* eff` observe the same value real Effect would deliver.

const run = (eff) => {
  if (eff && typeof eff._run === "function") {
    const v = eff._run()
    eff.__v = v
    return v
  }
  return eff
}

const mk = (runner) => {
  const eff = {
    __v: undefined,
    _run: runner,
    *[Symbol.iterator]() {
      // Yielding `eff` lets the outer Effect.gen driver run it; the driver
      // sends the run value back via next(v), which we store and then RETURN
      // so `yield* eff` evaluates to it (matching real Effect semantics).
      const sent = yield eff
      eff.__v = sent !== undefined ? sent : eff.__v
      return eff.__v
    },
    pipe(...fns) {
      return fns.reduce((e, f) => f(e), eff)
    },
  }
  return eff
}

const Effect = {
  gen: (genFn) =>
    mk(async () => {
      const it = genFn()
      let r = it.next()
      while (!r.done) r = it.next(await run(r.value))
      return r.value
    }),
  sync: (f) => mk(async () => f()),
  succeed: (v) => mk(async () => v),
  promise: (f) => mk(() => f()),
  runPromise: (eff) => Promise.resolve(run(eff)),
  orElseSucceed: (f) => (eff) =>
    mk(async () => {
      try {
        return await run(eff)
      } catch {
        return f()
      }
    }),
}

const Layer = {
  // Enough for `Layer.sync(Scheduler, () => Scheduler.of(makeImpl()))`:
  // the test reaches the concrete Interface via `layer.make()`.
  sync: (_tag, make) => ({ make }),
}

const Context = {
  // `class Scheduler extends Context.Service<Scheduler, Interface>()(key)`:
  // a factory returning a key-taking function returning the class. `.of`
  // returns the service itself so the layer yields the real implementation.
  Service:
    () =>
    (_key) =>
      class {
        static of(service) {
          return service
        }
      },
}

export { Context, Effect, Layer }

New regression file: packages/cli/test/cron/regression/stub-deps.mjs
// In-memory stand-ins for scheduler.ts's sibling imports (`./cron-task`,
// `./cron-jitter`, `./cron-lock`, `./loop-state`) and `@/util`, so the real
// `armLoop` implementation runs under Node without bun/node_modules.
// `Effect` here is our local stub (mapped by armloop-delay.hooks.mjs).

import { Effect } from "effect"

// ---- @/util: Log ---------------------------------------------------------
export const Log = {
  create: () => {
    const noop = () => undefined
    return { info: noop, warn: noop, error: noop, debug: noop }
  },
}

// ---- ./cron-task ---------------------------------------------------------
const sessionTasks = []

export const getSessionCronTasks = () => [...sessionTasks]
export const addSessionCronTask = (t) => sessionTasks.push(t)
export const removeSessionCronTasks = (ids) => {
  for (let i = sessionTasks.length - 1; i >= 0; i--) {
    if (ids.includes(sessionTasks[i].id)) sessionTasks.splice(i, 1)
  }
}
export const readCronTasks = () => Effect.succeed([])
export const writeCronTasks = () => Effect.succeed(undefined)
export const markCronTasksFired = () => Effect.succeed(undefined)
export const findMissedTasks = () => []

// ---- ./cron-jitter -------------------------------------------------------
export const DEFAULT_JITTER = {
  // Mirrors src/cron/cron-jitter.ts: the cap must far exceed the pinned
  // Date.now horizon so armLoop never takes the aged_out path.
  recurringMaxAgeMs: 7 * 24 * 60 * 60 * 1000,
}
export const jitteredNextCronRunMs = () => 0
export const oneShotJitteredNextCronRunMs = () => 0

// ---- ./cron-lock ---------------------------------------------------------
export const tryAcquireSchedulerLock = () => Effect.succeed(true)
export const releaseSchedulerLock = () => Effect.succeed(undefined)

// ---- ./loop-state --------------------------------------------------------
const loopStates = new Map()
export const getLoopState = (prompt) => loopStates.get(prompt)
export const setLoopState = (s) => loopStates.set(s.prompt, s)
export const deleteLoopState = (prompt) => loopStates.delete(prompt)
export const resetStrikes = () => undefined
export const incrementStrikes = () => undefined

Dominant language
TypeScript
Stars
13.7k
Forks
1.5k
Avg merge
7h 53m
Merged PRs (30d)
51

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from XiaomiMiMo/MiMo-Code

All issues in XiaomiMiMo/MiMo-Code

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.