Advanced
โฑ 8 min read
๐ examples/30_scheduler.mjs
Lesson 40: An unattended queue that retries, parks and resumes
work sources, normalization, claims, the single-flight tick, retry/park, the durable attempt store, four engines
1. Why This Feature Exists
Nobody is watching this board: a scheduler polls it, claims one item at a time, and remembers what failed. One story, four parts:
2. What the Example Demonstrates
A โ one board, three sources
memory (
createMemoryWorkSource), a JSON directory (createJsonFileWorkSource) and a host function (createFunctionWorkSource). Each adapter normalizes what it reads and skips a row it cannot use; normalizeWorkItem freezes a strict record, sortForDispatch orders the merge, and the memory and file claim stores grant one owner per item.B โ one heartbeat
start() runs one immediate tick on a manual clock. The live item answers a marker through createEngineRunner; a rate_limit failure retries after its backoff and completes; a PERMISSION_DENIED failure parks on the first attempt; a promoted item meets limits.maxDispatches and the budget stops it.C โ a restart
createFileAttemptStore is the only state that outlives the process. A fresh scheduler hydrates the failure count, gets one more dispatch and parks as attempts_exhausted; that dispatch reports attempt 1 again, because the persisted number is a failure count, not an ordinal. resetItem clears the record so the item runs from a clean budget.D โ four engines
one attempt, four engines โ agentic, dag (
planFor), stateMachine (graphFor), discussion (agents) โ and a DAG checkpoint that resumes with no model call and no usage. What this shows: - the board is a read-only source; the scheduler never writes it - retry vs park is decided by the failure class, not by a counter - the attempt store carries the budget and the park, never the queue - one runner result is this attempt's spend, not a running total Run: node examples/30_scheduler.mjs Needs: provider credentials in secret.env (PROVIDER=google_genai). @version 0.27.0imported from 'merci-sdk'
EVENTS, RunContext, WorkSourceError, initializeClient, loadCredentials, log
3. How the Core Call Works
The entry point, condensed. The full runnable file is linked below.
import { EventEmitter } from 'node:events';
import { mkdir, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import {
EVENTS, RunContext, WorkSourceError, initializeClient, loadCredentials, log,
} from 'merci-sdk';
import { LocalFileSessionStore } from 'merci-sdk/sessions';
import {
CLAIM_STATES, SCHEDULER_DEFAULTS, WorkScheduler, createEngineRunner, createFileAttemptStore,
createFileClaimStore, createFunctionWorkSource, createJsonFileWorkSource, createMemoryClaimStore,
createMemoryWorkSource, normalizeWorkItem, sortForDispatch,
} from 'merci-sdk/scheduler';
import { SCRATCH_DIR } from './_shared/real-tools.mjs';
import { reportUsage, resolveExample, runMain, trackUsage, warnEmptyAnswer, wireClient } from './_shared/example-utils.mjs';
const STATE_DIR = join(SCRATCH_DIR, '30-scheduler');
const MARKER = 'QUEUE-30';
const LIVE_PROMPT = `Reply with exactly ${MARKER}-LIVE and nothing else.`;
const TASK = 'Name one condition that must hold before shipping on Friday. At most 12 words.';
/** @param {{id?: string, identifier?: string, state?: string, priority?: number|null, createdAt?: number|null}} [arg0] */
const rawItem = ({ id = 'id-1', identifier = 'MER-1', state = 'Todo', priority = null, createdAt = null } = {}) => ({
id, identifier, title: `Work ${identifier}`, state, dispatchable: true, priority, createdAt,
});
// โโ the manual clock โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// A retry is due at `now + baseMs`; the example advances the clock, never time.
let now = 1_000_000;
let timerSeq = 0;
/** @type {Map<number, {at: number, fn: () => void}>} */
const timers = new Map();
const createClock = () => ({
now: () => now,
/** @param {[() => void, number]} args */
setTimeout: (...args) => {
const [fn, ms] = args;
timers.set(++timerSeq, { at: now + ms, fn });
return timerSeq;
},
/** @param {[unknown]} args */
clearTimeout: (...args) => { timers.delete(Number(args[0])); },
});4. Behavior the Code Fixes
work sources, normalization, claims, the single-flight tick, retry/park, the durable attempt store, four engines
5. Run the Example
Execute the runnable example from the repository root:
node examples/30_scheduler.mjs
What it does: work sources, normalization, claims, the single-flight tick, retry/park, the durable attempt store, four engines