Skip to content

Agents v1 (12/17): Cron schedule sweep in the daemon, deferred-run retry and stale grant cleanup #2811

Closed

Description

@propr-dev

Context

v1 supports a basic cron-like schedule per definition (issue 1 evaluator, next_run_at maintained by issue 2). The daemon already runs periodic sweeps (draft context sweep, push-rescue sweep), so the scheduler is another daemon sweep — not a new service. Every scheduled run goes through the same trigger primitive (issue 4) with the cost gate (issue 11).

Exactly-once per schedule slot matters: multiple daemons, restarts, or a slow sweep must not create two runs for the same 09:00 slot. We get this from two layers: (1) a compare-and-set claim on next_run_at and (2) an idempotency key schedule:<slot ISO> on the run (unique per definition).

Requirements

  1. New src/agentRunScheduler.ts exporting runAgentScheduleSweep(deps?) and scheduleAgentRunSweeps(intervalMs = 60_000) (returns a stop function), started from src/daemon.ts next to the existing sweeps and stopped on shutdown.
  2. Schedule sweep:
    • Select up to 50 definitions WHERE schedule_enabled AND enabled AND next_run_at <= now ORDER BY next_run_at.
    • For each: compute next = nextCronOccurrence(schedule, now); claim with UPDATE agent_definitions SET next_run_at = next WHERE id = ? AND next_run_at = <old>; skip if 0 rows (another sweep won).
    • Missed slots coalesce: if the daemon was down for 3 slots, only one run is created (for the latest due slot); the slot key uses the claimed next_run_at value.
    • Re-check the owner is still an instance member (resolveInstanceAuthorization-equivalent lookup in core: instance_members or bootstrap admin list); if not, disable the schedule (schedule_enabled=false) and log — an offboarded user's agent must stop running.
    • Call triggerAgentRun({ definition, trigger: 'schedule', triggerSource: 'schedule:<cron>', idempotencyKey: 'schedule:<slotIso>', gate: createAgentRunCostGate() }). Validation errors (AGENT_INVALID) record a skipped run with the reason so the history shows why nothing ran (add a recordSkippedRun helper using createAgentRun({ initialState: 'skipped' })).
  3. Deferred retry sweep (same interval): listDueDeferredRuns(now, 50); for each re-evaluate the gate with { deferrals }:
    • proceed → deferred → queued and enqueueAgentRunPhase(run, 'report').
    • defer → stay deferred with new deferred_until, incrementDeferrals. (Add deferred → deferred handling as a guarded same-state patch helper rescheduleDeferredRun.)
    • skip → deferred → skipped with reason.
  4. Grant cleanup sweep (every 10 minutes): revoke mcp_records(kind='agent_run_grant') whose run is terminal or whose record expired — calls the internal revoke route from issue 9 (backstop for crashed workers).
  5. Stuck-run recovery: runs in running/acting whose task (report_task_id/action_task_id) is terminal in task_history for more than 10 minutes → failed with "worker stopped before recording the result" (aligns agent receipts with the existing task-state reconciler).
  6. Tests test/agentRunScheduler.test.ts with an in-memory DB and fake trigger/clock.

Implementation Specification

  • Inject now, trigger, enqueue, gate, isMember for tests.
  • Each definition is processed in its own try/catch; one bad definition never stops the sweep.
  • Log one structured line per created/skipped/deferred run (definitionId, slot, runId, decision).

Acceptance Criteria

  • Two concurrent sweeps over the same due definition create exactly one run.
  • After the daemon was down across three slots, one run is created and next_run_at is the next future slot.
  • A due definition whose owner is no longer a member gets schedule_enabled=false and no run.
  • A deferred run whose provider recovered is queued and enqueued; one that stays limited past 6 deferrals is skipped.
  • Daemon shutdown clears the intervals.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The scheduler is a daemon sweep, consistent with how ProPR already runs periodic background work (draft context sweep, push-rescue sweep). It owns only timing: deciding a slot is due and calling the trigger primitive. Everything else (validation, idempotency, cost gate, enqueue) is the shared primitive, so a scheduled run is indistinguishable from an API-triggered one except for its trigger field.

    Exactly-once per slot uses two independent guards: an optimistic claim on next_run_at (cheap, avoids work) and the unique (definition_id, idempotency_key) index with key schedule:<slot> (correctness even if two processes both pass the claim due to clock skew). Missed slots coalesce into one run because flooding a provider after downtime is exactly the cost risk this feature must avoid.

    File: src/agentRunScheduler.ts (new file)

    Why this file: Time-based triggering and recovery sweeps for Agents, started by the daemon.

    import type { Knex } from 'knex';
    import { nextCronOccurrence } from '@propr/shared';
    import {
      createAgentRun, createAgentRunCostGate, db, enqueueAgentRunPhase, getAgentDefinitionById, listDueDeferredRuns, logger,
      rowToAgentRun, runDefinitionSnapshot, transitionAgentRun, triggerAgentRun, type AgentRunGateDecision,
    } from '@propr/core';
    
    const BATCH = 50;
    
    export interface SchedulerDeps {
      database?: Knex;
      now?: () => number;
      trigger?: typeof triggerAgentRun;
      enqueue?: typeof enqueueAgentRunPhase;
      gate?: ReturnType<typeof createAgentRunCostGate>;
      isMember?: (userId: string) => Promise<boolean>;
    }
    
    async function defaultIsMember(database: Knex, userId: string): Promise<boolean> {
      // Bootstrap admins (PROPR_ADMIN_USERS) are members without a row.
      const bootstrap = (process.env.PROPR_ADMIN_USERS ?? '').split(',').map(value => value.trim()).filter(Boolean);
      if (bootstrap.includes(userId)) return true;
      return Boolean(await database('instance_members').where({ github_user_id: userId }).first('github_user_id'));
    }
    
    export async function runAgentScheduleSweep(deps: SchedulerDeps = {}): Promise<{ triggered: number; skipped: number }> {
      const database = deps.database ?? db;
      const now = (deps.now ?? Date.now)();
      const gate = deps.gate ?? createAgentRunCostGate();
      const due = await database('agent_definitions').where({ schedule_enabled: true, enabled: true })
        .whereNotNull('next_run_at').where('next_run_at', '<=', now).orderBy('next_run_at').limit(BATCH).select('id', 'owner_id', 'schedule_cron', 'next_run_at');
      let triggered = 0;
      let skipped = 0;
      for (const row of due) {
        try {
          const slot = Number(row.next_run_at);
          const next = nextCronOccurrence(row.schedule_cron, new Date(now)).getTime();
          // Optimistic claim: only the sweep that moves next_run_at from this exact value proceeds.
          const claimed = await database('agent_definitions').where({ id: row.id, next_run_at: slot }).update({ next_run_at: next });
          if (!claimed) continue;
          if (!await (deps.isMember ?? (id => defaultIsMember(database, id)))(row.owner_id)) {
            // An offboarded user's automation must stop, visibly.
            await database('agent_definitions').where({ id: row.id }).update({ schedule_enabled: false, next_run_at: null, updated_at: now });
            logger.warn({ definitionId: row.id, ownerId: row.owner_id }, 'Disabled agent schedule: owner is no longer an instance member');
            continue;
          }
          const definition = (await getAgentDefinitionById(row.id, database))!;
          // Missed slots coalesce: the key is the slot we claimed, so one run per sweep at most.
          const idempotencyKey = `schedule:${new Date(slot).toISOString()}`;
          try {
            const result = await (deps.trigger ?? triggerAgentRun)({ definition, trigger: 'schedule', triggerSource: `schedule:${row.schedule_cron}`, idempotencyKey, gate }, { database });
            triggered += result.created ? 1 : 0;
            logger.info({ definitionId: row.id, slot: idempotencyKey, runId: result.run.id, state: result.run.state }, 'Scheduled agent run');
          } catch (error) {
            // Record why nothing ran so the history explains it (e.g. a repository was disabled).
            await createAgentRun({ definition, trigger: 'schedule', idempotencyKey, initialState: 'skipped', skipReason: `Skipped: ${(error as Error).message}` }, database);
            skipped++;
          }
        } catch (error) {
          logger.error({ definitionId: row.id, error: (error as Error).message }, 'Agent schedule sweep failed for definition');
        }
      }
      return { triggered, skipped };
    }
    
    export async function runDeferredRetrySweep(deps: SchedulerDeps = {}): Promise<void> {
      const database = deps.database ?? db;
      const now = (deps.now ?? Date.now)();
      const gate = deps.gate ?? createAgentRunCostGate();
      for (const row of await listDueDeferredRuns(now, BATCH, database)) {
        try {
          const decision: AgentRunGateDecision = await gate(runDefinitionSnapshot(row), row.trigger as never, { deferrals: row.deferrals });
          if (decision.action === 'proceed') {
            const queued = await transitionAgentRun(row.id, ['deferred'], 'queued', { deferredUntil: null }, database);
            if (queued) await (deps.enqueue ?? enqueueAgentRunPhase)(queued, 'report', { database });
          } else if (decision.action === 'defer') {
            // Same-state reschedule; guarded so a cancel in between wins.
            await database('agent_runs').where({ id: row.id, state: 'deferred' })
              .update({ deferred_until: decision.until, deferrals: database.raw('deferrals + 1'), skip_reason: decision.reason, updated_at: now });
          } else {
            await transitionAgentRun(row.id, ['deferred'], 'skipped', { skipReason: decision.reason }, database);
          }
        } catch (error) {
          logger.error({ runId: row.id, error: (error as Error).message }, 'Deferred agent run retry failed');
        }
      }
    }
    
    /** Receipts whose task already ended but whose worker died before recording the outcome. */
    export async function recoverStuckAgentRuns(deps: SchedulerDeps = {}): Promise<void> {
      const database = deps.database ?? db;
      const cutoff = new Date((deps.now ?? Date.now)() - 10 * 60_000).toISOString();
      const stuck = await database('agent_runs as run').whereIn('run.state', ['running', 'acting']).select('run.*');
      for (const row of stuck) {
        const taskId = row.state === 'running' ? row.report_task_id : row.action_task_id;
        if (!taskId) continue;
        const latest = await database('task_history').where({ task_id: taskId }).orderBy('history_id', 'desc').first('state', 'timestamp');
        if (latest && ['completed', 'failed', 'cancelled'].includes(latest.state) && String(latest.timestamp) < cutoff) {
          await transitionAgentRun(row.id, [row.state], 'failed', { failureReason: 'The worker stopped before recording the result; trigger the agent again.' }, database);
          logger.warn({ runId: row.id, run: rowToAgentRun(row).state }, 'Recovered stuck agent run');
        }
      }
    }
    
    export function scheduleAgentRunSweeps(intervalMs = 60_000): () => void {
      let running = false;
      const tick = async () => {
        // Never overlap sweeps: a slow tick is skipped, not stacked.
        if (running) return;
        running = true;
        try {
          await runAgentScheduleSweep();
          await runDeferredRetrySweep();
          await recoverStuckAgentRuns();
        } finally { running = false; }
      };
      const timer = setInterval(() => { void tick(); }, intervalMs);
      timer.unref?.();
      const grantTimer = setInterval(() => { void revokeStaleAgentRunGrants(); }, 10 * intervalMs);
      grantTimer.unref?.();
      return () => { clearInterval(timer); clearInterval(grantTimer); };
    }

    revokeStaleAgentRunGrants() lives in src/jobs/agentRuns/mcpGrantClient.ts: it selects mcp_records of kind agent_run_grant whose run is terminal or expires_at < now, and calls revokeAgentRunMcpGrant(runId, phase) (parse <runId>:<phase> from the record id).

    File: src/daemon.ts

    Why this file: The daemon is where periodic intake/sweep work lives; it already starts and tears down similar sweeps.

    --- a/src/daemon.ts
    +++ b/src/daemon.ts
    @@
    +import { scheduleAgentRunSweeps } from './agentRunScheduler.js';
    @@ async function startDaemon() {
         schedulePushRescueSweep();
    +    // Agents: cron schedules, deferred (cost-gated) retries, stuck-run recovery.
    +    const stopAgentRunSweeps = scheduleAgentRunSweeps();
    @@ shutdown handler
    +    stopAgentRunSweeps();

    File: test/agentRunScheduler.test.ts (new file)

    Why this file: Exactly-once per slot, coalescing, offboarding and deferred retry.

    import assert from 'node:assert/strict';
    import { after, test } from 'node:test';
    import knex from 'knex';
    import { closeConnection, createAgentDefinition, updateAgentDefinition } from '@propr/core';
    import { up } from '../packages/core/src/db/migrations/20261006000000_create_agent_definitions.js';
    import { runAgentScheduleSweep } from '../src/agentRunScheduler.js';
    
    after(closeConnection);
    
    async function fixture() {
      const database = knex({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
      await up(database);
      const definition = await createAgentDefinition('alice', { name: 'Hourly', repositories: ['acme/web'], prompt: 'p', agentAlias: 'claude', model: 'claude-opus-5-5', capabilities: [], autonomyMode: 'dry_run' }, database);
      await updateAgentDefinition(definition.id, 'alice', { schedule: '@hourly', scheduleEnabled: true }, { database });
      // Pretend three hourly slots were missed.
      await database('agent_definitions').where({ id: definition.id }).update({ next_run_at: Date.parse('2026-10-06T07:00:00Z') });
      const triggers: string[] = [];
      const trigger = (async ({ idempotencyKey }: { idempotencyKey: string }) => { triggers.push(idempotencyKey); return { run: { id: 'r', state: 'queued' }, created: true, enqueued: true }; }) as never;
      return { database, definition, triggers, trigger };
    }
    
    test('concurrent sweeps trigger one coalesced run per claim', async () => {
      const { database, definition, triggers, trigger } = await fixture();
      const deps = { database, trigger, now: () => Date.parse('2026-10-06T10:05:00Z'), isMember: async () => true, gate: (async () => ({ action: 'proceed' })) as never };
      await Promise.all([runAgentScheduleSweep(deps), runAgentScheduleSweep(deps)]);
      assert.deepEqual(triggers, ['schedule:2026-10-06T07:00:00.000Z']);
      const row = await database('agent_definitions').where({ id: definition.id }).first();
      assert.equal(new Date(Number(row.next_run_at)).toISOString(), '2026-10-06T11:00:00.000Z');
      await database.destroy();
    });
    
    test('an offboarded owner stops the schedule', async () => {
      const { database, definition, triggers, trigger } = await fixture();
      await runAgentScheduleSweep({ database, trigger, now: () => Date.parse('2026-10-06T10:05:00Z'), isMember: async () => false });
      assert.equal(triggers.length, 0);
      assert.equal(Boolean((await database('agent_definitions').where({ id: definition.id }).first()).schedule_enabled), false);
      await database.destroy();
    });
  2. propr-dev commented on Oct 7, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5-5 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5-5
    • Branch: 2811/claude-opus-5-5-agents-v1-12-17-cron-sche-20261007-0633-chq
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2811-20261007-0633-claude-opus-5-5-chq

    🔍 Track Task Execution

  3. added a commit that references this issue on Oct 7, 2026
  4. added a commit that references this issue on Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions