Skip to content

ClusterCron InitialRun messages are deduplicated on pod restart, breaking cron chain #5960

Closed
Smerly/effect-ts-clone
#5

Description

@Necmttn

Description

When using ClusterCron.make() with SQL storage, the InitialRun singleton's message gets silently rejected on pod/process restart if a previous "initial" message still exists in the database. This breaks the cron chain and requires manual database cleanup to fix.

Current Behavior

  1. First deployment: InitialRun singleton creates a message with entity_id="initial" and message_id="ClusterCron/{name}/initial/run/"
  2. Cron chain works correctly, scheduling subsequent runs with timestamp-based entity_ids
  3. Pod restarts (or deployment update)
  4. InitialRun singleton attempts to create a new "initial" message
  5. Message is silently rejected due to UNIQUE constraint on message_id in cluster_messages table
  6. Cron chain is broken - no new executions occur

Expected Behavior

Pod restarts should not break the cron chain. Either:

  • InitialRun should detect an existing cron chain and skip re-initialization
  • InitialRun messages should have unique message_ids (e.g., include timestamp)
  • The message should use upsert semantics

Root Cause

The CronPayload class has an empty PrimaryKey:

// From @effect/cluster/src/ClusterCron.ts
class CronPayload extends Schema.Class<CronPayload>("@effect/cluster/ClusterCron/CronPayload")({
  dateTime: Schema.DateTimeUtc
}) {
  [PrimaryKey.symbol]() {
    return ""  // Empty string means all InitialRun messages have same message_id
  }
  // ...
}

This results in a deterministic message_id:

ClusterCron/{name}/initial/run/

When the InitialRun singleton runs again, it generates the same message_id, which violates the UNIQUE constraint.

Reproduction Steps

  1. Create a ClusterCron with SQL storage:
const MyCron = ClusterCron.make({
  name: "MyCron",
  cron: Cron.parse("*/5 * * * * *").pipe(Either.getOrThrow),
  execute: Effect.log("Cron executed")
})
  1. Run the cluster - observe cron executing every 5 seconds
  2. Stop the process
  3. Wait a moment
  4. Start the process again
  5. Observe that cron no longer executes (InitialRun message rejected)

Workaround

Manually delete the "initial" messages from the database:

DELETE FROM cluster_messages
WHERE entity_id = 'initial'
AND entity_type LIKE 'ClusterCron%';

Suggested Fix

Option A: Include timestamp in InitialRun's entity_id or primary key:

const InitialRun = Singleton.make(
  `ClusterCron/${options.name}`,
  Effect.gen(function*() {
    const client = (yield* CronEntity.client)(`initial-${Date.now()}`) // Unique each time
    // ...
  })
)

Option B: Check if cron chain is already active before creating InitialRun message:

const InitialRun = Singleton.make(
  `ClusterCron/${options.name}`,
  Effect.gen(function*() {
    // Check if there's already a pending/scheduled message for this cron
    const hasPending = yield* checkPendingMessages(options.name)
    if (hasPending) return

    const client = (yield* CronEntity.client)("initial")
    // ...
  })
)

Option C: Use upsert semantics for persisted messages (might have broader implications)

Environment

  • @effect/cluster version: 0.56.x
  • Storage: SQL (PostgreSQL)
  • Runtime: Bun
  • Platform: Kubernetes

Additional Context

This issue particularly affects Kubernetes deployments where pods are frequently restarted due to:

  • Rolling updates
  • Node scaling
  • Pod evictions
  • Crash restarts

This edge case might not be obvious in development but becomes problematic in production Kubernetes environments with frequent pod restarts.

Activity

  1. Necmttn commented on Jan 7, 2026

    @Necmttn
    ContributorAuthor

    update;
    temporary deleting 'initial' doesn't help either it happens again.

         ClusterCron jobs stopped executing after noktaapp-runner pods were restarted. This is the same
         recurring issue from January 6th.
    
         Root Cause
    
         The @effect/cluster library has a bug where:
         1. InitialRun singleton creates messages with entity_id = "initial" and a deterministic message_id
         2. CronPayload class has an empty PrimaryKey (returns ""), so all InitialRun messages get the same
         message_id
         3. The cluster_messages table has a UNIQUE constraint on message_id
         4. When pods restart, the new InitialRun message is silently rejected as a duplicate
         5. The cron chain breaks - no new executions occur
    
  2. Necmttn commented on Apr 14, 2026

    @Necmttn
    ContributorAuthor

    Encountered the same empty-PK root cause as a multi-replica race today on @effect/[email protected] with 2 runner replicas behind HttpRunner + @effect/sql-pg.

    Repro: >= 2 runner replicas, any ClusterCron. Both replicas independently compute Cron.next(...) and call client.run({ dateTime: next }) for the same firing instant. With CronPayload[PrimaryKey.symbol]() => "", both submits collapse to identical (request_id, kind) tuples on insert into cluster_replies.

    Postgres error:

    duplicate key value violates unique constraint "cluster_replies_request_id_kind_key"
    

    Trace evidence (one cron tick, ~1 second apart):

    09:10:01.092  ClusterCron/KGColdExtractionBackfillCron(2026-04-14T09:10:00.000Z).run   Ok
    09:10:02.086  ClusterCron/KGColdExtractionBackfillCron(2026-04-14T09:10:00.000Z).run   Error [dup key]
    

    The fix proposed in Smerly/effect-ts-clone#5 (add id: Schema.String to CronPayload, source from crypto.randomUUID() at both client.run callsites, return id from PrimaryKey) resolves both the original restart-stall variant of #5960 and this multi-replica race because every submission now produces a unique message_id.

    We've shipped the same patch via bun patch on our side as a stopgap. Happy to help land an upstream PR if a maintainer can confirm the approach.

  3. added
    3.0
    on Jul 14, 2026
  4. added
    bug
    on Jul 28, 2026
  5. nick-inkeep commented on Oct 15, 2026

    @nick-inkeep

    On effect 4.0.5 (main unchanged), only calculateNextRunFromPrevious: true stays broken. Since #5775 the default mode seeds at the next run's ISO time. true still seeds at the fixed ClusterCron/<name>/initial/run/ (ClusterCron.ts:95; empty primary key at :160-162), which never matches a chain message. A restart in which the cron registers in time breaks neither mode: the pending next-run row carries the chain.

    The chain breaks when Sharding fails the pending run because ClusterCron/<name> is not registered by the deadline (Sharding.ts:782-790; defect reply at :836-845). No database edit is needed for that. A deploy without the cron does it. So does a boot that registers the cron more than entityRegistrationTimeout (default 1 minute) after its first entity. On v3 the deadline counts from Sharding start (0.60.2 Sharding.ts:554, :580-587), so any boot that slow does it. The default mode then re-seeds. true re-sends initial, which hits the processed row and is ignored (SqlMessageStorage.ts:352; :295 on pg), so the cron never runs again.

    The same address fails the other way. ClusterCron never deletes its processed rows, and if a cleanup job purges them, the next boot's seed runs beside the live chain and that tick runs twice.

    Setup for the table below:

    • 4.0.5 rows: effect, @effect/sql-sqlite-node and @effect/platform-node 4.0.5.
    • 0.60.2 rows: effect 3.22.2 and @effect/cluster 0.60.2.
    • Node 24.21.0. One runner (SingleRunner.layer, memory runner storage) over one SQLite file, and one process per deploy (3.5 s, 3 s and 4.5 s after boot).
    • Cron * * * * * *, entityRegistrationTimeout: 1000.
    version calculateNextRunFromPrevious deploy 2 runs in deploys 1 / 2 / 3
    4.0.5 false without the cron 4 / 0 / 5
    4.0.5 true without the cron 4 / 0 / 0
    4.0.5 false with the cron 4 / 3 / 5
    4.0.5 true with the cron 4 / 3 / 5
    4.0.5 true cron registered 1.5 s after another entity 4 / 0 / 0
    4.0.5 false same 3 / 0 / 5 ¹
    0.60.2 true 1.5 s layer before any entity registers 4 / 0 / 0
    0.60.2 false same 3 / 3 / 6

    ¹ The default mode loses that boot too: no seed row is written, and the InitialRun singleton is no longer running at shutdown.

    Purging processed rows before a restart, on 4.0.5: with true the first tick ran twice (entity ids …T05:54:32.000Z and initial); with false none did. With the default timeout and a 70 s deploy 2 without the cron, deploy 3 ran 0 times for true and 4 times for false.

    Test: fails for true, passes for false (packages/platform/node/test/cluster/ClusterCron.test.ts)
    import { NodeCrypto, NodeFileSystem } from "@effect/platform-node"
    import { SqliteClient } from "@effect/sql-sqlite-node"
    import { assert, describe, it } from "@effect/vitest"
    import { Cron, Effect, FileSystem, Layer } from "effect"
    import { ClusterCron, Entity, type Sharding, SingleRunner } from "effect/cluster"
    import { Rpc } from "effect/rpc"
    import { TestClock } from "effect/testing"
    
    const everySecond = Cron.parseUnsafe("* * * * * *", "UTC")
    
    // Stands in for the rest of the application in a deploy without the cron.
    const Other = Entity.make("Other", [Rpc.make("Ping")])
    const OtherLayer = Other.toLayer({ Ping: () => Effect.void })
    
    // One runner process over a SQLite file that outlives it.
    const deploy = (
      filename: string,
      entities: Layer.Layer<never, never, Sharding.Sharding>,
      millis: number
    ) =>
      Effect.gen(function*() {
        yield* Layer.build(entities.pipe(
          Layer.provideMerge(SingleRunner.layer({
            runnerStorage: "memory",
            shardingConfig: {
              entityRegistrationTimeout: 1000,
              entityTerminationTimeout: 0,
              entityMessagePollInterval: 100,
              refreshAssignmentsInterval: 100
            }
          })),
          Layer.provide(SqliteClient.layer({ filename })),
          Layer.provide(NodeCrypto.layer)
        ))
        yield* TestClock.adjust(millis)
      }).pipe(Effect.scoped)
    
    describe("ClusterCron", () => {
      for (const calculateNextRunFromPrevious of [false, true]) {
        it.effect(`resumes after being removed and re-added (calculateNextRunFromPrevious: ${calculateNextRunFromPrevious})`, () =>
          Effect.gen(function*() {
            const fs = yield* FileSystem.FileSystem
            const filename = (yield* fs.makeTempDirectoryScoped()) + "/cluster.db"
            let runs = 0
            const cron = ClusterCron.make({
              name: "report",
              cron: everySecond,
              calculateNextRunFromPrevious,
              execute: Effect.sync(() => {
                runs++
              })
            })
    
            yield* deploy(filename, Layer.merge(cron, OtherLayer), 3_500)
            const beforeRemoval = runs
            assert.isAbove(beforeRemoval, 0)
    
            // The pending run is failed once the entity type misses its registration timeout.
            yield* deploy(filename, OtherLayer, 3_000)
            assert.strictEqual(runs, beforeRemoval)
    
            yield* deploy(filename, Layer.merge(cron, OtherLayer), 3_500)
            assert.isAbove(runs, beforeRemoval)
          }).pipe(Effect.provide(NodeFileSystem.layer)))
      }
    })
    $ pnpm test --run packages/platform/node/test/cluster/ClusterCron.test.ts
     × resumes after being removed and re-added (calculateNextRunFromPrevious: true)
       AssertionError: expected 3 to be above 3
     Tests  1 failed | 1 passed (2)
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.0bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions