# How the Scheduled Cron Handler in open-seo Manages Audit Reconciliation and OAuth KV Purges

> Discover how open-seo's scheduled cron handler in src/server.ts manages audit reconciliation and OAuth KV purges using a dispatcher pattern for efficient maintenance.

- Repository: [Every App/open-seo](https://github.com/every-app/open-seo)
- Tags: internals
- Published: 2026-09-12

---

**The `scheduled` export in [`src/server.ts`](https://github.com/every-app/open-seo/blob/main/src/server.ts) uses a dispatcher pattern that checks `controller.cron` to branch between OAuth KV purges (hosted mode only) and general maintenance tasks including stale audit reconciliation and scheduled rank checks.**

The `every-app/open-seo` repository implements a robust **scheduled cron handler** that orchestrates multiple background maintenance tasks through a single Workers runtime entry point. Located in [`src/server.ts`](https://github.com/every-app/open-seo/blob/main/src/server.ts), this handler distinguishes between distinct cron triggers to execute environment-specific cleanup operations and database maintenance routines. According to the source code, the implementation prioritizes **transactional safety** through PostgreSQL client scoping and **error isolation** to prevent task failures from cascading.

## Cron Dispatch Architecture in [`src/server.ts`](https://github.com/every-app/open-seo/blob/main/src/server.ts)

The Workers runtime invokes the `scheduled` handler whenever a cron trigger fires, as defined in `wrangler.jsonc`. The handler immediately inspects `controller.cron` to determine which execution branch to follow.

The architecture supports two primary execution paths:

- **`MCP_OAUTH_PURGE_CRON`** (`"17 3 * * *"`): Executes OAuth data cleanup and referral-sale sweeps
- **Default cron**: Handles audit reconciliation and rank-check scheduling

This design keeps periodic jobs **isolated** while sharing a common entry point, allowing new cron-driven tasks to be added without modifying the core request handler logic.

## Handling OAuth KV Purges and Referral Sweeps

When the cron expression matches `MCP_OAUTH_PURGE_CRON`, the handler executes a specialized cleanup routine designed for hosted deployments.

### Hosted Mode Verification

Before executing any OAuth operations, the handler verifies the deployment configuration:

```typescript
if (isHostedAuthMode(getAuthMode(env.AUTH_MODE))) {
  // OAuth purge logic executes only in hosted mode
}

```

This guard ensures that self-hosted instances skip OAuth-specific maintenance, as implemented in lines 54-71 of [`src/server.ts`](https://github.com/every-app/open-seo/blob/main/src/server.ts).

### KV Purge Execution

The handler calls `openSeoOAuthProvider.purgeExpiredData(env)`, which iterates through the KV namespace keyspace and deletes stale entries. The method returns a `{ done: boolean }` summary indicating whether the scan completed the entire keyspace.

```typescript
const result = await openSeoOAuthProvider.purgeExpiredData(env as OpenSeoOAuthEnv);
console.log("[mcp-oauth] purged expired OAuth data", result);
if (!result.done) console.warn("[mcp-oauth] purge did not cover the full keyspace");

```

### Referral-Sale Sweep

Immediately following the KV purge, the handler executes `sweepDubReferredOrganizations()` to catch any missed Autumn billing events. This ensures data consistency between the OAuth layer and the referral tracking system defined in [`src/server/referrals/dub.ts`](https://github.com/every-app/open-seo/blob/main/src/server/referrals/dub.ts).

## Managing Audit Reconciliation and Rank Checks

For all other cron triggers, the handler executes a two-step maintenance routine inside a `withPgClient` block to ensure **transactional safety**.

### Watchdog Step: Reconciling Stale Audits

The first step invokes `reconcileStaleAudits()` imported from `@/server/features/audit/services/auditReconciler`. This function scans the `audit` table for rows stuck in the **"running"** state where the workflow terminated unexpectedly, marking them as failed or retrying them as appropriate.

Error handling uses a capture-and-continue pattern:

```typescript
let watchdogError: unknown;
try {
  await withPgClient(() => reconcileStaleAudits());
} catch (err) {
  watchdogError = err;
  console.error("[cron] Stale-audit reconcile failed:", err);
}

```

This pattern ensures that audit reconciliation failures do not block the subsequent rank-check step, as seen in lines 88-99.

### Rank-Check Step: Scheduling Daily Jobs

The second step calls `runScheduledRankChecks(env)` from `@/server/features/rank-tracking/services/scheduledRankChecks`. This function iterates over projects, creates rank-check jobs, and queues them for execution:

```typescript
await withPgClient(() => runScheduledRankChecks(env));

```

### Error Propagation Strategy

After both steps complete, the handler checks for captured watchdog errors and re-throws them to surface the failure to the Workers scheduler:

```typescript
if (watchdogError) throw watchdogError;

```

This approach ensures that the scheduler receives proper failure signals for monitoring while allowing the rank-check operation to complete independently.

## Summary

- The **scheduled cron handler** in [`src/server.ts`](https://github.com/every-app/open-seo/blob/main/src/server.ts) acts as a dispatcher, routing to specific maintenance routines based on `controller.cron` values.
- **OAuth KV purges** execute only in hosted mode, cleaning expired data and sweeping referral sales via `openSeoOAuthProvider.purgeExpiredData()` and `sweepDubReferredOrganizations()`.
- **Audit reconciliation** runs as a watchdog process to recover stuck workflows, with errors captured to prevent blocking rank-check operations.
- **Rank-check scheduling** queues daily jobs for all projects through `runScheduledRankChecks()`.
- All database operations execute within `withPgClient` scopes to maintain transactional integrity.

## Frequently Asked Questions

### How does the cron handler prevent OAuth cleanup from running on self-hosted instances?

The handler checks `isHostedAuthMode(getAuthMode(env.AUTH_MODE))` before executing any OAuth-related logic. This evaluation ensures that only deployments configured for hosted authentication mode proceed with KV purges, protecting self-hosted instances from executing inappropriate cleanup routines.

### What happens if audit reconciliation fails during the maintenance cron?

The implementation captures the error in a `watchdogError` variable and continues execution to the rank-check step. After rank checks complete, the handler re-throws the captured error to alert the Workers scheduler. This design prevents stuck audits from blocking daily rank-check operations while still surfacing failures for monitoring.

### Where is the logic for purging expired OAuth data implemented?

The purge logic resides in [`src/server/mcp/oauth-provider.ts`](https://github.com/every-app/open-seo/blob/main/src/server/mcp/oauth-provider.ts), specifically within the `purgeExpiredData` method. This function iterates through the KV namespace, deletes stale entries, and returns a status object indicating whether the scan completed the full keyspace.

### How are cron schedules configured in the open-seo repository?

Cron triggers are defined in `wrangler.jsonc` at the repository root. The `MCP_OAUTH_PURGE_CRON` is specifically scheduled for `"17 3 * * *"` (3:17 AM daily), while other maintenance tasks execute on the default cron schedule, all invoking the same `scheduled` export in [`src/server.ts`](https://github.com/every-app/open-seo/blob/main/src/server.ts).